【python】动态创建函数的一些方法
1、使用lambda函数
# 匿名函数, 返回值为函数 func = lambda: "foo" print(func)
2、使用内部函数(局部函数)
# 类似装饰器写法 def decorator(func): def _(*args, **kwargs): return func(*args, **kwargs) return _
3、使用types.FunctionType创建
import types def foo(): return "foo" func = types.FunctionType(foo.__code__, {}) print(func())
4、使用eval
foo = eval('lambda: "foo"') print(foo)
5、使用AST
首先了解
https://docs.python.org/zh-cn/3.8/library/ast.html
import ast import types import codegen from ast import * import astunparse as astunparse # 格式化展示AST Node function_ast = FunctionDef( name='func', args=arguments(posonlyargs=[], args=[], vararg=None, kwonlyargs=[], kw_defaults=[], kwarg=None, defaults=[]), body=[Return(value=Str(s='hello world', lineno=1, col_offset=0), lineno=1, col_offset=0)], decorator_list=[], lineno=1, col_offset=0 ) module_ast = Module(body=[function_ast], type_ignores=[]) module_code = compile(module_ast, "<>", "exec") function_code = [c for c in module_code.co_consts if isinstance(c, types.CodeType)][0] func = types.FunctionType(function_code, {}) print(func()) # 格式化展示AST Node print(astunparse.dump(module_ast)) # 展示定时的源码 print(codegen.to_source(module_ast))
输出:
hello world Module( body=[FunctionDef( name='func', args=arguments( posonlyargs=[], args=[], vararg=None, kwonlyargs=[], kw_defaults=[], kwarg=None, defaults=[]), body=[Return(value=Constant(value='hello world'))], decorator_list=[])], type_ignores=[]) def func(): return 'hello world'
参考链接:
https://www.cnblogs.com/olivetree123/p/5067685.html
https://www.cnblogs.com/LaoYuanPython/p/11087716.html
https://blog.csdn.net/ThinkTimes/article/details/110831176
https://blog.csdn.net/cunchi4221/article/details/107475657
https://github.com/journaldev/journaldev/tree/master/Python-3/basic_examples/
https://www.ghcc.net/node/3331829
https://docs.python.org/zh-cn/3.8/library/ast.html
https://pycoders-weekly-chinese.readthedocs.io/en/latest/issue3/static-modification-of-python-with-python-the-ast-module.html#
https://greentreesnakes.readthedocs.io/en/latest/nodes.html#function-and-class-definitions
https://www.csdn.net/tags/MtTaMg4sMjc5NzQ3LWJsb2cO0O0O.html
https://www.codenong.com/768634/