Python: include entries of a dictionary in the loc

2019-07-09 19:20发布

问题:

This has probably been asked before, but a quick search didn't give me an answer.

Suppose there is a dictionary containing all variables. How can I pass this dictionary on to the local namespace of a function? For example:

data = dict(a=1,b=2,c=3,d=4)
def f(data):
    return data['a'] + data['d']

requires to write data[' '] around each variable you would like to access. How can you add all entries of the dictionary to the local namespace of the function? For objects you can use

self.__dict__.update(data)

Is there something equivalent for functions, so that you get something along the lines of:

data = dict(a=1,b=2,c=3,d=4)
def f(data):
    add_to_local_namespace(data)
    return a + d

回答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.