Creating functions dynamically
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) print