passing global data to a function

David MacQuigg dmq at
Tue Dec 2 03:05:51 CET 2003

On 1 Dec 2003 08:55:38 -0800, beliavsky at wrote:

>How can I pass global data to function stored in a separate file? 
>For example, in file "" is the code 
>ipow = 2
>def xpow(xx): return xx**ipow
>and in "" is the code
>from funk import xpow,ipow
>xx = 4.0
>print xpow(xx)
>ipow = 3
>print xpow(xx)
>Running Python against, I get the output
>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 

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

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

More information about the Python-list mailing list