开发者

Making all variables accessible to namespace

Say I have a simple function:

def myfunc():
    a = 4.2
    b = 5.5
    ... many similar variables ...

I use this function one time only and I am wondering what is the easiest way to make all the varia开发者_运维问答bles inside the function accessible to my main name-space.

Do I have to declare global for each item? or any other suggested methods?

Thanks.


Best way, in my biased opinion, is to wrap the dictionary into a nice object where the "variables" are accessed as attributes -- the pattern I named Bunch when I introduced it many years ago, and a great example of the last item in the Zen of Python (if you don't know what that is, import this at an interpreter interactive prompt). To wit...:

class Bunch(object):
    def __init__(self, d=None):
        if d is not None: self.__dict__.update(d)

def myfunc():
    a = 4.2
    b = 5.5
    ...
    return Bunch(locals())

x = myfunc()

print x.a, x.b

Using qualified names like x.a and x.b, rather than barenames such as a and b, is the crucial idea here: qualified names let you separate namespaces and treat them right, while barenames would make one big soup of everything and violate the Zen of Python;-). And of course there's no need to use an unwrapped dict and unsightly x['a'], x['b'] accesses!-)


If what you want is separation of your constants then put them in another module:

consts.py:

foo = 42
bar = 'quux'

main.py:

import consts

print consts.foo
print consts.bar[::-1]


I can't think of any good reason for doing this, but if you REALLY want to for some strange reason:

def myfunc():
    x = 5.6
    y = 7.3
    # many other variables
    globals().update( locals() )

This works because the globals function returns a dictionary of the global variables in your module's namespace, which you can dynamically update with the dictionary of all local variables returned by the locals function.

This is very dangerous because it will clobber everything in your global namespace, so if you already had an x or y variable, then they'll get overwritten. And as I said, I really can't think of a good reason to ever do this, so definitely think twice before resorting to this kind of trickery!


It sounds like what you want to do isn't natural because it isn't something you should generally do much.

Perhaps what you really want is to make a class and set all these things on an instance of it.

class MyState(object):
    def __init__(self):
        self.a = 4.2
        self.b = 5.5
        ... many similar variables ...

Storing state on an instance of a class you create is usually very strongly preferred to mutating global state. This method also does not require any magic.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜