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.
Use a generic type to indicate that you'll be returning an instance of
cls
:Any subclass overriding the class method but then returning an instance of a parent class (
TrivialClass
or a subclass that is still an ancestor) would be detected as an error, because the factory method is defined as returning an instance of the type ofcls
.The
bound
argument specifies thatT
has to be a (subclass of)TrivialClass
; because the class doesn't yet exist when you define the generic, you need to use a forward reference (a string with the name).See the Annotating instance and class methods section of PEP 484.
Note: The first revision of this answer advocated using a forward reference naming the class itself as the return value, but issue 1212 made it possible to use generics instead, a better solution.
A simple way to annotate the return type is to use a string as the annotation for the return value of the class method:
This passes mypy 0.560 and no errors from python: