Question: Dynamic code import
Károly Ladvánszky
aa at bb.cc
Thu Oct 25 15:39:30 EDT 2001
Hi,
I've been experimenting with Python for a short period of time and I really
enjoy it.
It allows me to do a lot of things that are much harder or even not possible
to
accomplish in other languages.
I'd like to receive comments on the following problems.
1. Is it possible to 'import' Python code in a dynamic fashion?
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!
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
def test():
print gx # prints 1
set_gx(2)
print gx # prints 1 !
Trying a simpler version of it produces something strange:
a.
#--- 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
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!
Thanks for any help.
Károly
______________________________________________________________________________
Posted Via Binaries.net = SPEED+RETENTION+COMPLETION = http://www.binaries.net
More information about the Python-list
mailing list