Question: Dynamic code import

Chris Barker chrishbarker at home.net
Thu Oct 25 18:46:42 EDT 2001


"Károly Ladvánszky" wrote:
> 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
> #---

sure is:

#######file functions.py:
def f2(x):
    return x**2

def f3(x):
    return x**3

def f4(x):
    return x**4

####Another file, or command line:
>>> def f1(x):
...     return x
...
>>>
>>> f = f1
>>>
>>> f(4)
4
>>> import functions
>>> f = functions.f2
>>> f(4)
16
>>> f = functions.f3
>>> f(4)
64
>>> f = f1
>>> f(4)
4


So there you go. If the new function you want is not one of a set that
you know about ahead of time, you can build it as a string, and use
exec(), or read it from a file with execfile(). 

These are the straightforward ways to do it. There are also fancy ways
that you probably don't need like:

>>> f.func_code = functions.f3.func_code
>>> f(4)
64

Another thing to consider is curried functions: functions that generate
functions. Check the newsgroup archives for curried functions, you'll
find dome nifty discussion.

-Chris







-- 
Christopher Barker,
Ph.D.                                                           
ChrisHBarker at home.net                 ---           ---           ---
http://members.home.net/barkerlohmann ---@@       -----@@       -----@@
                                   ------@@@     ------@@@     ------@@@
Oil Spill Modeling                ------   @    ------   @   ------   @
Water Resources Engineering       -------      ---------     --------    
Coastal and Fluvial Hydrodynamics --------------------------------------
------------------------------------------------------------------------



More information about the Python-list mailing list