class A(metaclass=ABCMeta): pass class B(A): pass class C(A): pass def fun(a: "A"): pass I want the function (method) to accept as an argument an instance of any of the subclasses of the abstract class. How are such things correctly indicated?
class A(metaclass=ABCMeta): pass class B(A): pass class C(A): pass def fun(a: "A"): pass I want the function (method) to accept as an argument an instance of any of the subclasses of the abstract class. How are such things correctly indicated?
I want the function (method) to accept as an argument an instance of any of the subclasses of the abstract class
fun() already accepts all heirs A in the example:
#!/usr/bin/env python3 class A: pass class B(A): pass def isA(a: A): return isinstance(a, A) print(isA(B())) print(isA(1)) displays the expected error when checking with mypy :
$ python3 . && mypy __main__.py True False __main__.py:12: error: Argument 1 to "isA" has incompatible type "int"; expected "A" It is seen that instance B did not cause an error, since B subclass of A
For normal subclasses, this works with and without A(metaclass=abc.ABCMeta) . But virtual subclasses using A.register(klass) or A.__subclasshook__ do not work with mypy==0.4.6 .
Metaclasses in general and abc.ABCMeta in particular are not yet supported, see: Unsupported Python Features .
from abc import ABCMeta class A(metaclass=ABCMeta): pass class B(A): pass class D: pass def fun(a: A): if issubclass(a.__class__, fun.__annotations__['a']): print(True, a) else: print(False, a) b = B() d = D() fun(b) fun(d) Source: https://ru.stackoverflow.com/questions/595278/
All Articles