My goal is to dynamically generate functions and then save them in a file. For example, in my current attempt, When create_file called
import io def create_file(a_value): a_func = make_concrete_func(a_value) write_to_file([a_func], '/tmp/code.py') def make_concrete_func(a_value): def concrete_func(b, k): return b + k + a_value return concrete_func def write_to_file(code_list, path): import inspect code_str_list = [inspect.getsource(c) for c in code_list] with open(path, 'w') as ofh: for c in code_str_list: fh = io.StringIO(c) ofh.writelines(fh.readlines()) ofh.write('\n') create_file('my_value')
The output I want is (file /tmp/code.py ):
def concrete_func(b, k): return b + k + 'my_value'
The output I get (file '/tmp/code.py' ):
def concrete_func(b, k): return b + k + a_value
UPDATE: my solution uses inspect.getsource , which returns a string. I wonder if I have limited your options since most of the solutions below offer a string replacement. There is no need to use inspect.getsource for the solution. You could write it anyway to get the desired result.
UPDATE 2: The reason I am doing this is because I want to create a file for Amazon Lambda. Amazon Lambda takes the python file and its virtual environment and runs it for you (freeing you from worries about scalability and resiliency). You must tell Lambda which file and which function to call, and Lambda will execute it for you.
python
RAbraham
source share