将关键字参数传递给内部函数时,当外部函数具有带有相同名称的关键字参数

发布于 2025-01-28 00:50:50 字数 518 浏览 4 评论 0原文

我有两个大致定义的函数:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

吹梦到西洲 2025-02-04 00:50:50

不,没有一个,

您无法将两个带有相同名称的参数传递给函数。因此,您将无法在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" in kwargs.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文