如何在PyCharm中隐藏装饰器注入的函数参数提示?
解决PyCharm参数提示隐藏注入参数的问题
方法1:调整函数签名(推荐)
既然hello_string是装饰器注入的固定参数,完全可以把它从被装饰函数的参数列表里移出去,改成在装饰器内部处理,这样PyCharm的提示自然就只显示需要用户传入的参数:
from functools import wraps def decorator(func): @wraps(func) def wrapper(*args, **kwargs): hello_string = 'hello' # 调用原函数时只传用户提供的参数,注入参数通过关键字传入 return func(*args, **kwargs, hello_string=hello_string) return wrapper @decorator def func(a: int, b: int, hello_string: str): # 业务代码示例 print(hello_string, a, b) # 调用时PyCharm只会提示a和b参数 func(1, 2)
更简洁的写法是把注入参数作为闭包变量,原函数直接使用:
from functools import wraps def decorator(func): hello_string = 'hello' @wraps(func) def wrapper(*args, **kwargs): return func(*args, **kwargs, hello=hello_string) return wrapper @decorator def func(a: int, b: int, hello: str): print(hello, a, b)
方法2:用类型协议覆盖签名(兼容原有函数结构)
如果不想改动原函数的参数结构,可以通过typing.Protocol定义一个只包含用户需要传入参数的协议,让装饰器返回符合该协议的函数,PyCharm会根据协议提示参数:
from functools import wraps from typing import Protocol, Callable # 定义仅包含用户需传入参数的调用协议 class UserFunc(Protocol): def __call__(self, a: int, b: int) -> None: ... def decorator(func: Callable[[str, int, int], None]) -> UserFunc: @wraps(func) def wrapper(*args, **kwargs): return func('hello', *args, **kwargs) return wrapper # type: ignore @decorator def func(hello_string: str, a: int, b: int): print(hello_string, a, b) # 此时PyCharm会按照UserFunc的签名提示a和b func(1, 2)
关于装饰器的适用性
装饰器完全适合这类参数注入场景,尤其是需要复用注入逻辑的时候,写法比上下文管理器简洁得多——上下文管理器更适合处理有生命周期的资源(如文件、连接的打开/关闭),参数注入用装饰器是更优雅的选择,你的方案没问题。
内容的提问来源于stack exchange,提问作者INTODAN
相关产品推荐
相关产品推荐

