在创建函数时生成带有参数的函数?

RAb*_*ham 8 python

我的目标是动态生成函数,然后将它们保存在文件中.例如,在我目前的尝试中,在呼叫时create_file

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')
Run Code Online (Sandbox Code Playgroud)

我想要的输出是(文件/tmp/code.py):

def concrete_func(b, k):
    return b + k + 'my_value'
Run Code Online (Sandbox Code Playgroud)

我得到的输出是(文件'/tmp/code.py'):

def concrete_func(b, k):
    return b + k + a_value
Run Code Online (Sandbox Code Playgroud)

更新:我的解决方案使用inspect.getsource返回字符串.我想知道我是否限制了你的选择,因为大多数解决方案建议更换字符串.解决方案无需使用inspect.getsource.你无论如何都可以编写它以获得所需的输出.

更新2:我这样做的原因是因为我想为Amazon Lambda生成一个文件.Amazon Lambda将获取一个python文件及其虚拟环境,并将为您执行它(使您免于担心可伸缩性和容错性).你必须告诉Lambda要调用哪个文件和哪个函数,Lambda将为你执行它.

Håk*_*Lid 3

用于getsource将函数转换为字符串,并用简单的字符串操作替换变量名称。

from inspect import getsource

def write_func(fn, path, **kwargs):
    fn_as_string = getsource(fn)
    for var in kwargs:
        fn_as_string = fn_as_string.replace(var, kwargs[var])
    with open(path, 'a') as fp:  # append to file
        fp.write('\n' + fn_as_string)

def base_func(b, k):
    return b + k + VALUE

# add quotes to string literals   
write_func(base_func, '/tmp/code.py', VALUE="'my value'")

# you should replace the function name if you write multiple functions to the file
write_func(base_func, '/tmp/code.py', base_func='another_func', VALUE='5')
Run Code Online (Sandbox Code Playgroud)

输出如 /tmp/code.py 中的预期:

def base_func(b, k):
    return b + k + 'my value'

def another_func(b, k):
    return b + k + 5
Run Code Online (Sandbox Code Playgroud)