Python: load variables in a dict into namespace

前端 未结 7 755
天命终不由人
天命终不由人 2020-11-27 12:15

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

7条回答
  •  半阙折子戏
    2020-11-27 12:58

    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!
    

提交回复
热议问题