Search code examples
pythonpycharmpython-typing

Can you annotate return type when value is instance of cls?


Given a class with a helper method for initialization:

class TrivialClass:
    def __init__(self, str_arg: str):
        self.string_attribute = str_arg

    @classmethod
    def from_int(cls, int_arg: int) -> ?:
        str_arg = str(int_arg)
        return cls(str_arg)

Is it possible to annotate the return type of the from_int method?

I'v tried both cls and TrivialClass but PyCharm flags them as unresolved references which sounds reasonable at that point in time.


Solution

  • In Python 3.11 there is a nicer way to do this using the new Self type:

    from typing import Self
    
    class TrivialClass:
        def __init__(self, str_arg: str):
            self.string_attribute = str_arg
    
        @classmethod
        def from_int(cls, int_arg: int) -> Self:
            str_arg = str(int_arg)
            return cls(str_arg)
    

    This also works correctly with sub classes as well.

    class TrivialSubClass(TrivialClasss):
        ...
    
    TrivialSubclass.from_int(42)
    

    The IDE shows return type TrivialSubClass and not TrivialClass.

    This is described in PEP 673.