Question: Dynamic code import

Bjorn Pettersen BPettersen at NAREX.com
Thu Oct 25 15:47:02 EDT 2001


> From: Károly Ladvánszky [mailto:aa at bb.cc] 
> 
> Hi,

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.

Welcome

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

Try it in the interpreter:

>>> def f1(a): return a*1.25
...
>>> ff = f1
>>> ff(1)
1.25
>>> def f2(a): return a*1.3+5
...
>>> ff = f2
>>> ff(1)
6.2999999999999998
>>>

 
> 2. Something is wrong with globals. Given the example below, 
> I'd expect 2 for the second print.

You're misunderstanding the "global" directive. It is used inside a
function to tell the interpreter that it should look for a given
variable in the global scope:

var = 1

def f(x):
    global var # look for var in global namespace
    var += x

(the global directive is also only needed when assigning to the global,
but you can probably forget that for now...)

-- bjorn




More information about the Python-list mailing list