将关键字参数传递给内部函数时,当外部函数具有带有相同名称的关键字参数
我有两个大致定义的函数:
def func_inner(bar=0):
print('inner bar:', bar)
def func_outer(bar=-1, *args, **kwargs):
print('outer bar:', bar)
func_inner(*args, **kwargs)
有没有办法调用func_outer
,并为其提供两个值bar
- 一个用于func_outer
,另一个要传递到func_inner
?调用func_outer(bar = 1,bar = 2)
显然不起作用。
可以通过将bar
值指定为位置参数来克服问题,例如func_outer(1,2)
,但我想将它们指定为两个函数的关键字参数。
呼叫者方面是否完全有解决方案(即不更改功能的情况)?
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
? Calling func_outer(bar=1,bar=2)
clearly does not work.
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.
Is there a solution entirely at the caller's side (ie. without altering the functions)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,没有一个,
您无法将两个带有相同名称的参数传递给函数。因此,您将无法在
kwargs
中拥有键“ bar”
。因此,如果不修改这两个函数,则不能通过此参数。
可能有一种更适合您正在做的方法的方法
,是装饰器中弹出的代码。在这种情况下,您可能需要使外部函数 criverified 。
No, there is none
You cannot pass two arguments with the same name to a function. Thus, you will not be able to have the key
"bar"
inkwargs
.Thus you cannot pass this argument without modifying the two functions.
There may be a more adapted way to what you’re doing
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.