passing global data to a function

Bengt Richter bokr at oz.net
Mon Dec 1 13:51:14 EST 2003


On 1 Dec 2003 08:55:38 -0800, beliavsky at 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
>
>How can this be done? Thanks.

Not nice to pass args via globals, but
(oops, extra blank lines at end of funk.py):

 >>> print '----\n%s\n----'%file('funk.py').read()
 ----
 ipow = 2
 def xpow(xx): return xx**ipow


 ----
 >>> import funk
 >>> xpow = funk.xpow
 >>> xx = 4.0
 >>> print xpow(xx)
 16.0
 >>> funk.ipow = 3
 >>> print xpow(xx)
 64.0

IOW, if you use
     from funk import xpow, ipow
you get local bindings of the names xpow and ipow
and when you call xpow(xx) you are accessing funk.xpow,
but when you assign ipow = 3 you are just changing the local
binding of ipow from what it was (same as funk.ipow) to a new value 3,
which doesn't affect funk.ipow, which is what xpow is using.
So you have to rebind the ipow name in xpow's global name space,
hence funk.ipow = 3 does what you wanted.

But you probably ought to find a better way to design this functionality.

Regards,
Bengt Richter




More information about the Python-list mailing list