1

I want a classmethod to return correct type so i declare generic type for it. Any subclass of TrivialClass will also satisfy the type hint. However inside the from_int(), cls is going to lose access to other() method in Pycharm. What's the correct way to do it?

from typing import Type, TypeVar

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

class TrivialClass:
    # ...

    @classmethod
    def from_int(cls: Type[T], int_arg: int) -> T:
        # no suggestion for other, since cls type is Type[T]
        cls.other()
        return cls(...)

    @classmethod
    def other(cls):
        pass
TomSawyer
  • 3,711
  • 6
  • 44
  • 79
  • Why did you annotate `cls` in the first place? `mypy` and PyCharm accept it without the type annotation, because `mypy` and PyCharm know the type of the first argument of a `classmethod`. You must fix the `other()` method first, though. – Wombatz Dec 07 '19 at 12:59
  • 1
    @Wombatz i don't use mypy, only pycharm. declaring `Type[T]` to have it returns correct type of child class , if i don't do it. `from_int` will return Any type. https://stackoverflow.com/questions/39205527/can-you-annotate-return-type-when-value-is-instance-of-cls – TomSawyer Dec 07 '19 at 17:44
  • @Wombatz `Other uses are factory methods, such as copy and deserialization. For class methods, you can also define generic cls, using Type[T]:` https://mypy.readthedocs.io/en/latest/generics.html#generic-methods-and-generic-self – TomSawyer Dec 07 '19 at 17:45
  • @Wombatz because when you *subclass* this class you want `SubClass.from_int()` to be recognised as the subclass type, not the parent class. – Martijn Pieters Dec 08 '19 at 12:16

0 Answers0