Python: Include Entries Of A Dictionary In The Local Namespace Of A Function
Solution 1:
It is impossible in the general case, because the dict can have keys which are not valid variable names, e.g. Python keywords or non-strings.
If you desperately need this, and you can guarantee that the dict keys are all valid variable names, and you don't need it to work on Python 3, it's possible to loop over the dict items and use an exec
statement. There are some weird scoping consequences of this approach, it's very ugly, and should be strongly discouraged.
An acceptable alternative is to create a dummy object and set them as attributes, for example:
>>>data = dict(a=1,b=2,c=3,d=4)>>>from types import SimpleNamespace>>>v = SimpleNamespace(**data)>>>v.a
1
>>>v.d
4
But it's only really like a syntactic sugar for dict access. Read zen of Python #19. Whichever way you look at it, you will need namespacing!
Another idea: create a callable class instead of a function (by inheriting collections.Callable
), and unpack the dict into attributes on the class. Then at least your variables will be namespaced by the class.
Post a Comment for "Python: Include Entries Of A Dictionary In The Local Namespace Of A Function"