-2

Possible Duplicate:
declaring a global dynamic variable in python

>>> def f():
        global cat
        exec 'cat'+'="meow"'
        return
>>> f()
>>> cat
Traceback (most recent call last):
  File "<pyshell#23>", line 1, in <module>
    cat
NameError: name 'cat' is not defined

This is just a stripped down example of the issue I've come across. In my actual script, I need various instances of a class be created and named, hence the exec statement.

Just calling

exec 'cat'+'="meow"'

directly in the shell works fine, but as soon as it's packed in a function, it doesn't seem to work anymore.

Community
  • 1
  • 1
Axim
  • 332
  • 3
  • 11

2 Answers2

3

I still don't understand why you are using exec, its a bad design choice and alternatives are usually easier, for example instead of global and then something else you could simply do this

ns = {}

def f():
    ns["cat"] = "miow"

print ns

Now isn't that cleaner?

Jakob Bowyer
  • 33,878
  • 8
  • 76
  • 91
0

looks like the exec ignores the global, the documentation is a bit vague. but this works:

>>> def f():
...         global cat
...         exec 'global cat; cat'+'="meow"'
... 
>>> 
>>> f()
>>> cat
'meow'
Not_a_Golfer
  • 47,012
  • 14
  • 126
  • 92
  • 2
    Excuse me while I run off to write a PEP on replacing the `global` keyword with `global_and_I_really_understand_why_global_is_almost_always_bad`. (and possibly a similar PEP for `exec`.) – Wooble Apr 12 '12 at 11:27
  • And, by the way, the first `global cat` is completely unnecessary; just the one inside the `exec` is in the scope where the name is used. – Wooble Apr 12 '12 at 11:29
  • @Wooble yeah I just forgot to delete it copying his example. and bad or not is not the question here. it's a weird pattern but who am I to judge. – Not_a_Golfer Apr 12 '12 at 11:30
  • Well, I personally don't downvote for telling people how to do things they shouldn't be doing, but I can certainly see the downvoter's point :) – Wooble Apr 12 '12 at 11:31
  • 1
    Well then, I guess I'll stop answering people who shouldn't be doing what they're doing in my opinion! ;) – Not_a_Golfer Apr 12 '12 at 11:32