有没有一种方法为带有 **kwargs 的函数提供签名参考(例如,用于 IDE)?
例如:
def foo(**kwargs):
# call some third-party library with kwargs signature
我希望为大多数最新的IDE提供自动完成功能。
那么,在Python中如何描述签名呢?
这可能不完全符合您的要求,但它可能会有所帮助
。
from other_package import my_function
def wrapped_help_text(wrapped_func):
"""Decorator to pass through the documentation from a wrapped function.
"""
def decorator(wrapper_func):
"""The decorator.
Parameters
----------
wrapped_func : callable
The wrapped function.
"""
wrapper_func.__doc__ = ('This method wraps the following method:\n\n' +
pydoc.text.document(wrapped_func))
return wrapper_func
return decorator
@wrapped_help_text(my_function)
def wrapper(**kwargs):
"""
Parameters
----------
**kwargs
See other_package.my_function()
"""
my_function(**kwargs)
有了这个,现在你可以调用内置的help
函数来查看包装函数的文档字符串。
function.__signature__
。尽管如此,这是运行时行为。因此,如果IDE仅查看AST,则无法正常工作。但实际导入模块的任何内容,例如在Python REPL中执行help()
或在模块上运行pydoc
,将正常工作。signature.Signature
对象或修改签名后再进行分配。import inspect
def wrapped(foo: str, a: int = 10) -> bool:
return True
def wrapping(*args, **kwargs) -> bool:
return wrapped(*args, **kwargs)
wrapping.__signature__ = inspect.signature(wrapped)
**kwargs
之外,没有任何简单的方法来做到这一点。这也有点取决于IDE如何获取函数签名——它是解析AST还是实际导入模块? - mgilson