How to type hint a staticmethod+abstractmethod+property using Mypy in Python?

Viewed 59

Given this code:

from abc import ABC, abstractmethod
from typing import TYPE_CHECKING

class Foo(ABC):
    
    @property
    @staticmethod
    @abstractmethod
    def name() -> str:
        pass

class Bar(Foo):
    name = "bar"

class Baz(Foo):
    name = "baz"

instances = [Bar(), Baz()]

print(instances[0].name)

if TYPE_CHECKING:
    reveal_type(instances[0].name)

Ran by the python interpreter, it prints (as expected):

bar

However, ran by mypy type checker, it prints (unexpectedly):

main.py:23: note: Revealed type is "def () -> builtins.str"

It looks like the type is wrongly inferred (see playground). Is it possible to fix that somehow?

If possible, I would like to fix it "once and for all" (like in the Foo class) because I'm accessing .name in multiple places.

0 Answers
Related