首页 > 解决方案 > 带有特定参数的 Python 类型提示装饰器

问题描述

考虑一个包装器,它获取一个类实例self并在调用修饰函数之前使用它:

def some_decorator(func: Callable[[Foo], None]):
    @functools.wraps(func)
    def wrap(self: Foo) -> None:
        # Logic requiring the use of self
        func(self)
    return wrap

class Foo:
    @some_decorator
    def bar(self) -> None:
        return None

调用barasFoo().bar()应该等同于Foo.bar(Foo()),但 PyCharm 的类型检查器抱怨前者:Parameter 'self' unfilled. 从函数中删除装饰器后,类型检查器按预期工作,这两种方法被认为是等效的。

我怎样才能让类型检查器意识到两者是等价的,即使使用装饰器,并且没有问题?

请注意,我不考虑使用def wrap(*args)andfunc(*args)作为解决方案,因为它完全避免了类型检查。

标签: pythonpython-3.xpython-decoratorstype-hintingfalse-positive

解决方案


推荐阅读