根据另一个函数中的位置提取 kwargs 和 args
Extract kwargs and args based on positions in another function
我想围绕另一个函数为一个函数的参数建模。例如,如果我有:
def f(arg1, arg2=0, otherargs=...):
# Does something.
然后我想创建一个可以使用相同参数的函数:
def g(*): # Or however best to parameterize.
arg1 = # Extract arg1 value.
arg2 = # Extract arg2 value, if provided.
# Do something with arg1 and arg2.
f_result = f(arg1, arg2, otherargs)
# Do something else with f_result and return.
这可能吗?
这可以通过 inspect.getcallargs
实现:它接受函数、args 和 kwargs,以及 returns 参数字典。使用上面定义的 f 和 g,这看起来像:
import inspect
def f(arg1, arg2=0, otherargs=...):
# Does something.
return
def g(*args, **kwargs): # Or however best to parameterize.
kwargs = inspect.getcallargs(f, *args, **kwargs)
arg1 = kwargs["arg1"] # Extract arg1 value.
arg2 = kwargs["arg2"] # Extract arg2 value, if provided.
otherargs = kwargs["otherargs"]
# Do something with arg1 and arg2.
f_result = f(arg1, arg2, otherargs)
# Do something else with f_result and return.
我想围绕另一个函数为一个函数的参数建模。例如,如果我有:
def f(arg1, arg2=0, otherargs=...):
# Does something.
然后我想创建一个可以使用相同参数的函数:
def g(*): # Or however best to parameterize.
arg1 = # Extract arg1 value.
arg2 = # Extract arg2 value, if provided.
# Do something with arg1 and arg2.
f_result = f(arg1, arg2, otherargs)
# Do something else with f_result and return.
这可能吗?
这可以通过 inspect.getcallargs
实现:它接受函数、args 和 kwargs,以及 returns 参数字典。使用上面定义的 f 和 g,这看起来像:
import inspect
def f(arg1, arg2=0, otherargs=...):
# Does something.
return
def g(*args, **kwargs): # Or however best to parameterize.
kwargs = inspect.getcallargs(f, *args, **kwargs)
arg1 = kwargs["arg1"] # Extract arg1 value.
arg2 = kwargs["arg2"] # Extract arg2 value, if provided.
otherargs = kwargs["otherargs"]
# Do something with arg1 and arg2.
f_result = f(arg1, arg2, otherargs)
# Do something else with f_result and return.