5

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.

2

3 Answers 3

6

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
Sign up to request clarification or add additional context in comments.

1 Comment

See here for a slightly more sophisticated container class.
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

2 Comments

I like this one... but somehow the self.__dict__ = self thing makes me feel funny inside. What if you did this?
@senderle, sure, that would work. You could also add nice __repr__ etc to the class
0

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.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.