从函数签名中删除所有绑定参数。

huangapple go评论59阅读模式
英文:

Remove all bound arguments from function signature?

问题

Here's the translation of the code part you provided:

从 inspect 模块导入 signature
从 functools 模块导入 partial

def remove_default_args(func, **kwargs):
    func = partial(func, **kwargs)
    sg = signature(func)
    unbound_parameters = 

func.__signature__ = sg.replace(parameters=unbound_parameters) return func

Let me know if you need any further assistance with this code.

英文:

Say, we have a function foo, which takes another function bar as an argument and does something based on bar's signature, and, sadly, throws an error when bar has default arguments. I want to use foo with functions, say, bar1,bar2,...bar100, all of which have default arguments. All of the aforementioned functions are from an outer library which I cannot change. There are too many bars to rewrite each of them as a lambda statement. The only way is to remove all bound arguments from these functions. And there's exec, but I'm not that desperate yet.

I know there's a module called inspect in python which works with function signatures, I came up with the following code:

from inspect import signature
from functools import partial

def remove_default_args(func, **kwargs):
    func = partial(func, **kwargs)
    sg = signature(func)
    unbound_parameters = 

func.__signature__ = sg.replace(parameters=unbound_parameters) return func

Is there any better way to do this, without inspect? I ask since I know inspect is generally frowned upon, as it only changes the metadata.

答案1

得分: 1

Default argument values are stored in the __defaults__ and __kwdefaults__ attributes, which are writable. You can simply set them "back" to None to remove all defaults.

>>> def foo(x=3, *, y=5):
...    pass
...
>>> foo()
>>> foo.__defaults__, foo.__kwdefaults__
((3,), {'y': 5})
>>> foo.__defaults__ = None
>>> foo.__kwdefaults__ = None
>>> foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo() missing 1 required positional argument: 'x'
英文:

Default argument values are stored in the __defaults__ and __kwdefaults__ attributes, which are writable. You can simply set them "back" to None to remove all defaults.

&gt;&gt;&gt; def foo(x=3, *, y=5):
...    pass
...
&gt;&gt;&gt; foo()
&gt;&gt;&gt; foo.__defaults__, foo.__kwdefaults__
((3,), {&#39;y&#39;: 5})
&gt;&gt;&gt; foo.__defaults__ = None
&gt;&gt;&gt; foo.__kwdefaults__ = None
&gt;&gt;&gt; foo()
Traceback (most recent call last):
  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;
TypeError: foo() missing 1 required positional argument: &#39;x&#39;

huangapple
  • 本文由 发表于 2023年5月11日 01:58:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76221368.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定