Easily dumping variables from/to namespaces/dictionaries in Python
You have several options to create your 'namespace'. The easiest two are:
Create a quick custom class:
class Namespace(object): def __init__(self, **kw): self.__dict__.update(kw) def dump_into_namespace(**kw): return Namespace(**kw)
Call with
dump_into_namespace(a='a', b='b', c='c')
; this takes an arbitrary number of keyword arguments.Use a
collections.namedtuple
class:from collections import namedtuple Namespace = namedtuple('Namespace', 'a b c') def dump_into_namespace(a, b, c): return Namespace(a, b, c)
Call with
dump_into_namespace('a', 'b', 'c')
; this only takes a fixed number of arguments, but yourdump_into_namespace()
function could provide defaults.
What you call 'dot notation' is really just attribute access.
The solution below provides syntax very close to your requirement, the only difference is that you have to pass to the function environment where the variables are defined explicitly:
x = 10
y = 20
class dump_into_namespace:
def __init__(self, env, *vars):
self.vars = dict([(x, env[x]) for v in vars for x in env if v is env[x]])
def __getattr__(self, name): return self.vars[name]
o = dump_into_namespace(locals(), x, y)
print o.x, o.y
You can then 'dump' back the variables to your locals (say, in a different function):
>>> locals().update(o.vars)
>>> x
10
EDIT:
Thanks to the suggestion of eyquem this can be even shorter. The idea is to put variables into self.__dict__
of the 'dump' object (note: syntax of update changes here):
class dump_into_namespace:
def __init__(self, env, *vs):
vars(self).update(dict([(x, env[x]) for v in vs for x in env if v is env[x]]))
def f():
x = 10
y = 20
return dump_into_namespace(locals(), x, y)
o = f()
print o.x, o.y
globals().update(vars(o))
print x