Skip to content

Instantly share code, notes, and snippets.

@vlad-bezden
Created February 18, 2019 17:02
Show Gist options
  • Save vlad-bezden/6394d8ec9a5881db35cfc496db0e9563 to your computer and use it in GitHub Desktop.
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'`
"""
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