I want to allow type hinting using Python 3 to accept instances which are children of a given class. I’m using the enforce module to check the function typing. E.g.:
import abc class A(metaclass=abc.ABCMeta) pass class B(A) def __init__(self,a) self.a = a pass x = B(3) @enforce.runtime_validation def function(x:A) print(x.a)
but it seems like python 3 doesn’t allow for this syntax, returning:
Argument ‘x’ was not of type < class ‘A’ >. Actual type was B.
Any help?
Advertisement
Answer
By default enforce applies invariant type checking. The type has to match directly – or an error is thrown.
In order for an instance of a subclass to be accepted, the mode can be changed to covariant by adding :
enforce.config({'mode ': 'covariant'})
at a point in the code that is executed before any type checking is done (i.e. near the start).
Other modes are available as described in the documentation.
For further informations see : https://github.com/RussBaz/enforce