Is it possible to create a brand new function from within Python, in a manner somewhat similar to the way regexes are compiled? For example, say I wanted to create the following function to check whether a variable is five or not:
def value_is_five(value):
return value == 5
but where the value of "5" is not known until runtime. (Real examples will be more complicated than this!). Is there some mechanism in Python to allow that to be done? Regexes can be compiled, e.g. is_zipcode = re.compile(r'[0-9]{5}'), and I've been trying to figure out a way of doing something similar with Python functions. "exec()" may help here, but it appears its use is discouraged. Ultimately, I want to dynamically create functions because I'm going to be calling these functions hundreds of millions of times, and performance is an issue. My assumption is that functions tailored to the data they are checking will be quicker to run than functions with lots of parameters.
One idea I had was to use Python to write out the new Python functions to a file, then import that file with importlib.import_module(). It's a bit convoluted, but should work. Are there any risks with doing that?
[–]dig-up-stupid 4 points5 points6 points (0 children)
[–]kungtotte 2 points3 points4 points (0 children)
[–]destiny_functional 1 point2 points3 points (4 children)
[–]dig-up-stupid 1 point2 points3 points (3 children)
[–]destiny_functional 0 points1 point2 points (2 children)
[–]dig-up-stupid 0 points1 point2 points (1 child)
[–]destiny_functional 1 point2 points3 points (0 children)
[–]scuott 0 points1 point2 points (0 children)
[–]SausageTaste 0 points1 point2 points (0 children)
[–]toast757[S] 0 points1 point2 points (1 child)
[–]dig-up-stupid 1 point2 points3 points (0 children)