Python: load variables in a dict into namespace
Consider the Bunch
alternative:
class Bunch(object): def __init__(self, adict): self.__dict__.update(adict)
so if you have a dictionary d
and want to access (read) its values with the syntax x.foo
instead of the clumsier d['foo']
, just do
x = Bunch(d)
this works both inside and outside functions -- and it's enormously cleaner and safer than injecting d
into globals()
! Remember the last line from the Zen of Python...:
>>> import thisThe Zen of Python, by Tim Peters ...Namespaces are one honking great idea -- let's do more of those!
This is perfectly valid case to import variables inone local space into another local space as long asone is aware of what he/she is doing.I have seen such code many times being used in useful ways.Just need to be careful not to pollute common global space.
You can do the following:
adict = { 'x' : 'I am x', 'y' : ' I am y' }locals().update(adict)blah(x)blah(y)