pythontype-hintingvscode-python

How to use a class attribute as the type hint for a method inside the class?


class Foo:
    method_type: type

    def method(self) -> ???:
        # code



# Example use:


class FooStr(Foo):
    method_type = str

foo_str = FooStr().method() # should be str according to vscode's intellisense


class FooInt(Foo):
    method_type = int

foo_int = FooInt().method() # similarly, this should be int

Note that simply replacing the ??? with method_type doesn't work as far as I've tested it.

How would I go about doing this?


Solution

  • A class attribute is a runtime value and Python doesn't really support types dependent on values. Python also doesn't have type members. So in conclusion, no this isn't possible. You'd need to use a generic

    T = TypeVar("T")
    
    class Foo(Generic[T]):
        def method(self) -> T:
            ...
    
    class FooStr(Foo[str]):
        ...
    
    class FooInt(Foo[int]):
        ...
    

    which is similar, if not quite the same.

    If you want to know more about the difference, here's a discussion about it in Scala.