Dynamically defined functions via exec in imported module

George Sakkis george.sakkis at gmail.com
Sat Aug 16 04:05:00 CEST 2008


On Aug 15, 7:26 pm, Nadeem <nadeemabdulha... at gmail.com> wrote:

> Hello all,
> I'm trying to write a function that will dynamically generate other
> functions via exec.

General tip: whenever you think you need to use exec (or eval), 99% of
the time you don't; most of the time there is a better (meaning, less
fragile and obscure) solution.

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

Unsurprisingly, there is indeed a better way, a closure:

def adder(amt):
  def closure(x):
    return x + amt
  return closure

>>> plus5 = adder(5)
>>> plus5(7)
12

HTH,
George



More information about the Python-list mailing list