On 1 Dec 2003 08:55:38 -0800,
be*******@aol.com wrote:
How can I pass global data to function stored in a separate file?
For example, in file "funk.py" is the code
ipow = 2
def xpow(xx): return xx**ipow
and in "xfunk.py" is the code
from funk import xpow,ipow
xx = 4.0
print xpow(xx)
ipow = 3
print xpow(xx)
Running Python against xfunk.py, I get the output
16.0
16.0,
so the value of ipow in function xpow is not being changed. I want ipow to equal
4 in the 2nd call to xpow, so that the output would be
16.0
64.0
I found the scoping rules confusing also. In case anyone is writing a
text, here is a simpler example:
def fonc(): return p
# from funk import fonc # same def, but in module funk.py
# import funk
p = 2; print fonc()
p = 3; print fonc()
### RESULTS from uncommenting line #N, where #N =
#1) As expected.
#2) 'p' is not defined.
#3) 'fonc' is not defined
The variable 'p' trickles down ONLY to definitions within the same
module. ( "Lexical scoping", as explained by Terry Reedy. ) I'm not
sure why this is the right thing to do, but after a few months of
working with Python, my confidence is still growing that the designers
made the right choices. This is a superb language!! Perfect for a
technical professional like myself who is not a programmer.
Anyway, I have no complaint about this limitation. I agree with Bengt
Richter, this "back door" is not a good way to pass parameters into a
function.
Now if only we could simplify the scoping rules by having global
definitions pass down through nested classes the same as they do
through nested functions ... :>)
-- Dave