简体   繁体   中英

Add to locals() in Python 3.2+?

I'm trying to programmatically define several variables in the local namespace:

for build_step in 'prepare', 'configure', 'make', 'stage', 'package', 'all':
    p = build_subparsers.add_parser(build_step)
    p.set_defaults(build_step=build_step)
    if build_step != 'package':
        p.add_argument('specfile')
    locals()['build_'+build_step+'_parser'] = p
build_prepare_parser
NameError: global name 'build_prepare_parser' is not defined

However after running this code, none of the variables I presumed to create actually exist despite appearing in locals() . How do I do this in Python 3.2?

Update0

I know locals() is a bad idea, that's why I'm asking this question.

The answer is: don't do that.

If you want to programmatically store values, use a container:

>>> d = dict()
>>> d['a'] = 5

Or create a container class, if you really must.

>>> class Container(object):
...     pass
... 
>>> c = Container()
>>> setattr(c, 'a', 5)
>>> c.a
5

Why not give build it's own namespace?

class Build(dict):
    def __init__(self):
        self.__dict__ = self

build = Build()
for build_step in 'prepare', 'configure', 'make', 'stage', 'package', 'all':
    p = build_subparsers.add_parser(build_step)
    p.set_defaults(build_step=build_step)
    if build_step != 'package':
        p.add_argument('specfile')
    build[build_step+'_parser'] = p
build.prepare_parser

According to the docs for locals():

The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.

Try putting them in globals() (which is the symbol dictionary for the current module, not truly global.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM