I'm trying to use function annotations in the hope that my editor will be better at refactoring. I however am stumbling over the following problem:
I have an abstract base class Algorithm.
self.foo = 'bar'
def get_foo(foo_algorithm: subclassof(Algorithm)):
def get_foo(foo_algorithm: Algorithm): return foo_algoritm.foo
and automatically any instance of a subclass will be acceptable (
isinstance(foo_algorithm, Algorithm) must be true, which applies to all subclasses of a baseclass).
If you can only accept classes, then use
Type[Algorithm] as the type hint:
def get_foo(foo_algorithm: Type[Algorithm]): return foo_algoritm().foo
See the The type of class objects section of PEP 484 -- Type Hints:
Sometimes you want to talk about class objects, in particular class objects that inherit from a given class. This can be spelled as
Cis a class. To clarify: while
C(when used as an annotation) refers to instances of class
Type[C]refers to subclasses of
Here I called the class object, since
.foo is an instance attribute according to your code example; a class derived from
Algorithm would not have such an attribute itself.