如何在Python中将函数作为字符串返回?

时间:2015-11-20 11:53:45

标签: python function

我已经创建了一个函数来创建函数并将它们写入文件,但问题是它们将文件写为默认的 repr 。如何将它们作为普通函数写入文件?

def make_route(title):
    test = 1
    def welcome():
        return test + 1

    welcome.__name__ = title 
    with open('test2.py', 'a') as f:
        f.write('\n%s\n' % (welcome))

    return welcome

我需要它来写

def welcome():
    return test + 1

到文件

1 个答案:

答案 0 :(得分:-1)

您需要使用marshal

序列化您的功能
import marshal
def f(x): return 2*x
saved = marshal.dumps(f.func_code)

然后你可以使用保存的字符串:

import marshal, types
code = marshal.loads(saved)
f= types.FunctionType(code, globals(), "your_name")

f(10)  #returns 20
相关问题