Creating functions dynamically

share on google plus share on facebook share on twitter share on linkedin share via email

Sometimes you want to create functions on the fly, at runtime. This came up when using some of the SciPy optimisation functions that require constraints on the variables to be defined as functions.

As per this StackOverflow post there seem to be several ways to accomplish this.

All methods revolve in one way or another around Python’s built-in ast and types modules. For more info, see for example here:

For our problem with the constraint functions, we ended up using the following.

funcs = {}

for i in range(10):
    code = """def constraint_{0}(x): return x[{0:d}] > 1e-12""".format(i)
    exec(code, {}, funcs)
import random

r = [random.random() for _ in range(10)]

for name in funcs:
    print funcs[name].__name__
    print type(funcs[name])
    print funcs[name](r)

Leave a response

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>