python dynamic scoping question

Jp Calderone exarkun at intarweb.us
Mon Apr 21 06:49:42 CEST 2003


On Sun, Apr 20, 2003 at 07:49:55PM -0500, Greg Krohn wrote:
> [snip]
> 
> From the docs:
> 
> globals() - Return a dictionary representing the current global symbol
> table. This is always the dictionary of the current module (inside a
> function or method, this is the module where it is defined, not the module
> from which it is called).
> 
> >>> def f():
> ...   def g():
> ...     x = 5
> ...     globals()['x'] = 5
> ...   g()
> ...   print x
> ...
> >>> f()
> 5
> 
> 
> Cool?
> 

  No.  The right way to do this is:

    def f():
        def g():
            global x
            x = 5
        g()
        print x

  But isn't the answer to the original poster's question, afaict.

  Jp

-- 
        "I quite agree with you," said the Duchess; "and the moral of
that is -- Be what you would seem to be' -- or, if you'd like it put
more simply -- Never imagine yourself not to be otherwise than what it
might appear to others that what you were or might have been was not 
otherwise than what you had been would have appeared to them to be
otherwise.'"       -- Lewis Carrol, "Alice in Wonderland"
-- 
 up 32 days, 1:02, 3 users, load average: 0.21, 0.21, 0.25





More information about the Python-list mailing list