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.:
JavaScript
x
14
14
1
import abc
2
class A(metaclass=abc.ABCMeta)
3
pass
4
class B(A)
5
def __init__(self,a)
6
self.a = a
7
pass
8
x = B(3)
9
10
@enforce.runtime_validation
11
def function(x:A)
12
print(x.a)
13
14
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 :
JavaScript
1
2
1
enforce.config({'mode ': 'covariant'})
2
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