Question: Dynamic code import

Petr Kubanek petr at kubanek.net
Thu Oct 25 15:49:44 EDT 2001


> For instance, the running program refers to function f1 through ff:
> 
> def f1(a):
>     return a*1.25
> 
> ff=f1
> 
> At some point, it turns out that f1(a) should return a*1.3+5. If it was
> possible to insert a
> new function, the running program could be modified like this:
> 
> #--- this is to be 'imported'
> def f11(a):
>     return a*1.3+5
> #---
> 
> ff=f11
> 
> Now ff(a) would produce results by using the new rule embodied in f11!
 
Yes, it does. So where is problem?
 
> 2. Something is wrong with globals. Given the example below, I'd expect 2
> for the second print.
> 
> global gx
> gx=1
> 
> def set_gx(gx_new):
>     gx=gx_new

gx is local variable (at that point). Python works so. To work as expected, 
you should add global:

def set_gx(gx_new):
    global gx
    gx=gx_new

> 
> #--- This one works, test() prints the global gx.
> global gx
> gx=1
> 
> def test():
>     print gx # prints 1
> 
> b.
> #--- This one runs to error -> 'UnboundLocalError: local variable 'gx'
> referenced before assignment' !!!
> global gx
> gx=1
> 
> def test():
>     print gx
>     gx=2

Ansewer is in error. Same problem:

def test():
    global gx
    print gx
    gx=2

> 
> c.
> #--- This one works but treats gx as local. Try test() first, then test1()
> will print the original 1 for the global gx!
> global gx
> gx=1
> 
> def test():
>     gx=2
>     print gx # prints 2
> 
> def test1():
>     print gx # prints 1!

Again, it's in syntax. Insert global gx before first statement in def.

Using global in Python is quite strange and you should try to avoid it, or 
remeber to use global every time. Other possible way is throught __main__  
module, which worked like:

import __main__

__main__.gx=1

def test:
        print __main__.gx

Even when __main__ gets reimported in second module, it's contents remains.

Petr Kubanek



More information about the Python-list mailing list