[英]passing keyword argument to inner function when outer function has keyword argument with the same name
I have two functions defined roughly like this:我有两个大致这样定义的函数:
def func_inner(bar=0):
print('inner bar:', bar)
def func_outer(bar=-1, *args, **kwargs):
print('outer bar:', bar)
func_inner(*args, **kwargs)
Is there a way to call func_outer
and provide it with two values of bar
- one for func_outer
, and the other to be passed over to func_inner
?有没有办法调用func_outer
并为它提供两个bar
值 - 一个用于func_outer
,另一个传递给func_inner
? Calling func_outer(bar=1,bar=2)
clearly does not work.调用func_outer(bar=1,bar=2)
显然不起作用。
It's possible to overcome the issue by specifying bar
values as positional arguments, like func_outer(1,2)
, but I'd like to specify them as keyword arguments for both functions.可以通过将bar
值指定为位置参数来解决该问题,例如func_outer(1,2)
,但我想将它们指定为两个函数的关键字参数。
Is there a solution entirely at the caller's side (ie. without altering the functions)?是否有完全在调用方的解决方案(即不改变功能)?
You cannot pass two arguments with the same name to a function.您不能将具有相同名称的两个参数传递给函数。 Thus, you will not be able to have the key "bar"
in kwargs
.因此,您将无法在kwargs
中拥有键"bar"
。
Thus you cannot pass this argument without modifying the two functions.因此,您不能在不修改这两个函数的情况下传递此参数。
This is the kind of code that pops up in a decorator.这是在装饰器中弹出的那种代码。 In this kind of case, you may want to make the outer function currified .在这种情况下,您可能希望使外部函数currified 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.