Question: Dynamic code import

Károly Ladvánszky aa at
Thu Oct 25 22:24:12 CEST 2001

Hi Bjorn,

Thanks for your quick answer. Yes, I was mistaken with the global directive.
It's clear now.
Regarding the first question, it works fine with the interpreter but I would
like to read
f11(a) from somewhere else, most likely from a file.



"Bjorn Pettersen" <BPettersen at> az alábbiakat írta a következo
üzenetben: news:mailman.1004039306.14596.python-list at
> From: Károly Ladvánszky [mailto:aa at]
> 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!

Try it in the interpreter:

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

> 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