我想在内存中动态创建一个函数,并带有参数的类型提示。我确实有一些工作代码,但感觉非常老套和脆弱。
import typing
func_name = 'some_function_name'
req_type=int
a = None
exec(f'''def {func_name}(my_argument:{req_type.__name__}): pass
a = {func_name}''')
print(a) # <function some_function_name at 0x000001B89F3311F0>
print(typing.get_type_hints(a)) # {'my_argument': <class 'int'>}
Run Code Online (Sandbox Code Playgroud)
必须有更好的方法来做到这一点。有什么建议么?
您可以使用它FunctionType来创建新函数。您可以复制模板函数并更改其类型提示和名称。您还可以code使用 Python 函数更改函数对象的compile。
我做了一个例子,复制并更改模板函数的名称和类型提示(不更改代码)
import types
import typing
def copy_func(f, func_types, name=None):
# add your code to first parameter
new_func = types.FunctionType(f.__code__, f.__globals__, name or f.__name__,
f.__defaults__, f.__closure__)
new_func.__annotations__ = func_types
return new_func
def template(arg):
print('called template func')
a = copy_func(template, {'my_argument': int}, "test")
a(2) # can call it
print("types:", typing.get_type_hints(a)) # types: {'my_argument': <class 'type'>}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
947 次 |
| 最近记录: |