开发者

Is there a way to make every variable inside a definition or class to become global automatically?

I am using a large list of variables inside some definitions and classes (mainly because I want to be able to use the code-folding feature of pydev). Is there any constructor I can use on a definition or class to make its variables automatically considered globals?


This is an example of what I did after following some of the recommendations provided on the comments:

From:

img_globe       = os.path.join(set_img_dir, 'img_globe.png')
img_help        = os.path.join(set_img_dir, 'img_help.png')
img_exit        = os.path.join(set_img_dir, 'img_exit.png')
img_open        = os.path.join(set_img_dir, 'img_open.png')
img_tutorial    = os.path.join(set_img_dir, 'img_tutorial.png')
img_save        = os.path.join(set_img_dir, 'img_save.png')
img_site        = os.path.join(set_img_dir, 'img_site.png')

... (long, long list)

To:

varies = {}
dirList=os.listdir(set_img_dir)
for fname in dirList: 
  开发者_JAVA百科  varies[fname.split(".")[0]] = os.path.join(set_img_dir, fname)


Although you should not do this and the solution you are looking for is not as simple as you might think, here is a very simple example of how you might take the local variables from within a function and make them global:

def make_locals_globals():
    """This is just bad"""
    foo = 1
    bar = 2

    locals_dict = locals()
    globals_dict = globals()

    print 'Locals:', locals_dict

    for varname, varval in locals_dict.items():
        print 'Setting global: %s=%s' % (varname, varval)
        globals_dict[varname] = varval

if __name__ == '__main__':
    make_locals_globals()

    print '\nGlobals:'
    print 'foo=', foo
    print 'bar=', bar
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜