Search code examples
pythonpycharmpython-typing

Python inspector ignores property return hint when using TypeVar


from abc import ABC, abstractmethod
from typing import TypeVar

T = TypeVar('T', bound='Abs')


class A:
    val: int = 10


class Abs(ABC):
    @property
    @abstractmethod
    def a(self) -> A:
        ...


class MyClass(Abs):
    _a: A = A()

    @property
    def a(self) -> A:
        return self._a


def foo(obj: T):
    print(obj.a.val)

In this example the code inspector highlights obj.a.val with Unresolved attribute reference 'val' for class 'property'.

Is that me incorrectly using the TypeVar, or maybe the problem is with PyCharm inspector? Is it possible in the first place to infer that a has val for sure?


Solution

  • Your code is fine. The inspector is handling it wrong. mypy accepts your code without complaint, and your code behaves correctly at runtime too.