python dynamic scoping question

Greg Krohn ('rot-13') 'tert at pncen.hf'.decode
Sun Apr 20 20:49:55 EDT 2003


"Julia Goolia" <juliagoolia301 at hotmail.com> wrote in message
news:79ad5955.0304201513.6ffd4f83 at posting.google.com...
> Hi,
>
> I have a question regarding scoping in python.  I wish to have some
> mechanism which puts variables at a function level scope into the
> global scope, dynamically.  I cannot alter my design.
>
> For example, I want this to work:
>
> def f():
>   def g():
>     x = 5
>   g()
>   print x
> f()
>
> I want to be able to see x in f, event though it was assigned in a
> lower scope, g.
>
> Thank you for your time.

>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?

greg






More information about the Python-list mailing list