python - Can you annotate return type when value is instance of cls? -
given class helper method 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 possible annotate return type of from_int
method?
i'v tried both cls
, trivialclass
pycharm flags them unresolved references sounds reasonable @ point in time.
use generic type indicate you'll returning instance of cls
:
from typing import type, typevar t = typevar('t', bound='trivialclass') class trivialclass: # ... @classmethod def from_int(cls: type[t], int_arg: int) -> t: # ... return cls(...)
any subclass overriding class method returning instance of parent class (trivialclass
or subclass still ancestor) detected error, because factory method defined returning instance of type of cls
.
the bound
argument specifies t
has (subclass of) trivialclass
; because class doesn't yet exist when define generic, need use forward reference (a string name).
see annotating instance , class methods section of pep 484.
note: first revision of answer advocated using forward reference naming class return value, issue 1212 made possible use generics instead, better solution.
Comments
Post a Comment