python dynamic scoping question

Bjorn Pettersen BPettersen at NAREX.com
Sun Apr 20 19:28:02 EDT 2003


> From: Julia Goolia [mailto:juliagoolia301 at hotmail.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.

Good luck, given what you're saying, as opposed to only the fragment of
code, you would need perfect knowledge of all assignments that have
dynamically happened in a program, i.e. you can't find these variables
by static/lexical analysis. I'm almost positive there doesn't exists a
language where you can perform this operation in this direction unless
you consider making _all_ variables global (dynamic scoping does
something similar, but in the other direction :-)

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

Try e.g. creating a a global object called e.g. GlobalState and store
the variables there instead?

-- bjorn





More information about the Python-list mailing list