Question: Dynamic code import

Károly Ladvánszky aa at bb.cc
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.

Cheers,

Károly

"Bjorn Pettersen" <BPettersen at NAREX.com> az alábbiakat írta a következo
üzenetben: news:mailman.1004039306.14596.python-list at python.org...
> 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



______________________________________________________________________________
Posted Via Binaries.net = SPEED+RETENTION+COMPLETION = http://www.binaries.net



More information about the Python-list mailing list