exec "global" problem

Tim Peters tim.one at home.com
Thu Jun 28 00:24:09 EDT 2001


[Michaell Taylor]
> I have seen lots of discussion of the problem of executing the
> following code:

That's odd -- I haven't seen any!  Where are you hiding it <wink>?

> global sub
> sub=['sub1', 'sub2', ...'sub600']
> def make():
> 	for X in range(1,600):
> 		exec "global sub%s" % (X)
> 		exec "sub%s={}" % (X)
> 		other stuff
>
> The problem is the
>
> exec "global sub%s" % (X)
>
> line which doesn't execute ...

Sure it does.  But it has nothing to do with the next line:  each exec
creates a new code block, and calling a thing "global" in one block has no
effect on its local-vs-global status in any other code block.

You can study the reference manual to try to sort that all out (it's
functioning as documented), but it's much easier not to use exec at all:

def make():
    g = globals()
    for i in range(1, 600):
        g["sub%d" % i] = {}

Run that and you'll find it creates 599 dicts in your global namespace.

> ...
> These 600 dictionaries are subsequently passed to a variety of
> functions.

You should really say something about what you're trying to accomplish in
the *end*, so c.l.py can help.  Think of this as the c.l.py Suicide
Prevention Line <wink>.

not-even-mother-earth-is-*that*-global-ly y'rs  - tim





More information about the Python-list mailing list