在 PyCharm 中的函数参数提示中隐藏装饰器注入的参数

问题描述 投票:0回答:1

我有一个函数,它有一个由装饰器注入的参数,如下所示:

def decorator(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        return func('hello', *args, **kwargs)
    return wrapper

@decorator
def func(hello_string: str, a: int, b: int):
    <some code>

然后你这样调用该函数:

func(1,2)

我希望 Pycharm 不向我显示 hello_string 作为参数的存在,我想向用户仅显示调用函数时需要放入函数中的参数(a 和 b)。

enter image description here

有没有办法做到这一点,或者装饰器对于这种类型的注入不是一个好的解决方案? 我也尝试在函数内部使用上下文管理器,但它们会导致整个函数缩进,并且使用多个上下文管理器使方法看起来很混乱,而使用多个装饰器则干净。

谢谢

python pycharm decorator
1个回答
0
投票

我不知道 PyCharm 会用这个做什么,但是指示

decorator
返回一个基于原始函数具有不同签名的函数的方法是使用
ParamSpec

from typing import Callable, Concatenate, ParamSpec, TypeVar
P = ParamSpec('P')
RV = TypeVar('RV')

def decorator(func: Callable[Concatenate[str, P], RV) -> Callable[P, RV]:
    @wraps(func)
    def wrapper(*args: P.args, **kwargs: P.kwargs) -> RV:
        return func('hello', *args, **kwargs)
    return wrapper

@decorator
def func(hello_string: str, a: int, b: int):
    <some code>

decorator
的类型提示表示
func
是一个具有
str
值参数和零个或多个任意参数的函数,返回一些任意值,并且
decorator
返回具有相同任意参数的可调用函数并返回值作为参数,减去初始
str
值参数。

© www.soinside.com 2019 - 2024. All rights reserved.