Dynamically defined functions via exec in imported module

Nadeem nadeemabdulhamid at gmail.com
Sat Aug 16 01:26:50 CEST 2008


Hello all,
I'm trying to write a function that will dynamically generate other
functions via exec. I then want to be able to import the file (module)
containing this function and use it in other modules, but for some
reason it only works using the "import <mod>" syntax, and not "from
<mod> import *" syntax... i.e. in the latter case, the function is
dynamically generated, but not accessible from the importing module.
Any ideas on what I can do to be able to retain the second form of
import and still have the exec'd functions visible?

Here's the code... I have three files:

###################################
# modA.py

def dynamicdef(name, amt):
    '''Dynamically defines a new function with the given name that
adds
    the given amt to its argument and returns the result.'''
    stm = "def %s(x):\n\treturn x + %d" % (name, amt)
    print stm
    # exec stm      # --- with this, 'name' is only accessible within
this fn
    exec stm in globals()   # --- this makes it global within this
module...

    print eval(name)


dynamicdef('plus5', 5)

print plus5(7)


###################################
# modB.py
# This uses the dynamicdef to dynamically define a new function, and
it
# works fine, with the newly defined function being accessible thru
the modA
# module...

import modA

modA.dynamicdef('plus10', 10)

print help(modA.plus5)
print help(modA.plus10)

print modA.plus5(20)
print modA.plus10(20)



###################################
# modC.py
# This uses the dynamicdef to dynamically define a new function, but
it
# doesn't work; seems like knowledge of the newly defined function in
the
# modA module is not propagated back to this context or something...?

from modA import *

dynamicdef('plus10', 10)

print help(plus5)
#print help(plus10)    # !!! Fails: NameError: name 'plus10' is not
defined

print plus5(20)
print plus10(20)
###################################


Thanks for any help/suggestions,
---nadeem




More information about the Python-list mailing list