Created
February 18, 2019 17:02
-
-
Save vlad-bezden/6394d8ec9a5881db35cfc496db0e9563 to your computer and use it in GitHub Desktop.
An example of how to annotate cls return type class in inheritance using mypy in order to escape error `AttributeError: type object 'A' has no attribute 'bazz'`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
An example of how to annotate cls return type class in inheritance using mypy | |
in order to escape error `AttributeError: type object 'A' has no attribute 'bazz'` | |
Here is what we done: | |
* The type variable TA is used to denote that return values might be an | |
instances of subclasses of A. | |
* Specify that A is an upper bound for TA. | |
Specifying bound means that TA will only be A or one of its subclasses. | |
This is needed to properly restrict the types that are allowed. | |
* The typing.Type[] construct is the typing equivalent of type(). | |
We need it to note that the class method expects a class | |
and returns an instance of that class. | |
""" | |
from __future__ import annotations | |
from typing import TypeVar, Type | |
TA = TypeVar("TA", bound="A") | |
class A: | |
def __init__(self, param: str) -> None: | |
self.param = param | |
def bar(self) -> str: | |
return "bar" | |
@classmethod | |
def bazz(cls: Type[TA]) -> TA: | |
return cls("bazz") | |
class B(A): | |
def foo(self) -> str: | |
return "foo" | |
a = A.bazz() | |
print(a.param) | |
print(a.bar()) | |
b = B.bazz() | |
print(b.param) | |
print(b.foo()) | |
print(b.bar()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment