英文:
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 bar
s 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.
>>> 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'
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论