Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: load variables in a dict into namespace

I want to use a bunch of local variables defined in a function, outside of the function. So I am passing x=locals() in the return value.

How can I load all the variables defined in that dictionary into the namespace outside the function, so that instead of accessing the value using x['variable'], I could simply use variable.

like image 622
D R Avatar asked Apr 08 '10 02:04

D R


People also ask

Should I use dict () or {}?

With CPython 2.7, using dict() to create dictionaries takes up to 6 times longer and involves more memory allocation operations than the literal syntax. Use {} to create dictionaries, especially if you are pre-populating them, unless the literal syntax does not work for your case.

Can a dictionary value be a variable?

Variables can't be dict values. Dict values are always objects, not variables; your numbers dict's values are whatever objects __first , __second , __third , and __fourth referred to at the time the dict was created. The values will never update on the dictionary unless you do it manually. when they change..

Can dict list have value?

It definitely can have a list and any object as value but the dictionary cannot have a list as key because the list is mutable data structure and keys cannot be mutable else of what use are they.


1 Answers

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 this The Zen of Python, by Tim Peters    ... Namespaces are one honking great idea -- let's do more of those! 
like image 113
Alex Martelli Avatar answered Sep 20 '22 23:09

Alex Martelli