Add support for generic classes
It would be great to be able to do runtime type checking of generic classes, e.g.:
from typing import Generic, TypeVar
T = TypeVar('T')
class A(Generic[T]):
@typechecked
def __init__(self, obj: T):
self.obj = obj
class IntA(A[int]):
pass
a = IntA(7) # good!
a = IntA('foo') # bad!
I sketched out something like this already: https://gist.github.com/chadrik/54d7b3d051839f90983676a47368526b
You mean
a = IntA(7) # good!
a = IntA('foo') # bad!
don't you?
d'oh, yes. lemme fix that.
I would be interested to get this feature implemented in pytypes. Unfortunately I don't have time to work on this right now and it is not a trivial thing to implement. Should the self-object be the carrier of T's value? Or the class? Does self carry T's value to supermethod? I don't say these questions could not be properly and consistently answered. I just suggest to give it some thought, e.g. how would you suggest these calls to behave:
from typing import Generic, TypeVar
T = TypeVar('T')
class A(Generic[T]):
@typechecked
def method(self, obj: T):
# whatever
class IntA(A[int]):
def method(self, obj: T):
# whatever
obj_IntA = IntA()
obj_IntA.method(7) # good!
A.method(obj_IntA, 'text') # bad (?)
A.method(obj_IntA, 7) # good (?)
A[str].method(obj_IntA, 'text') # bad?
A[str].method(obj_IntA, 7) # bad?
A[int].method(obj_IntA, 7) # good?
As of https://github.com/Stewori/pytypes/commit/c1c207bc75b8aaade78f44c785d045391caebc4a the described functionality is provided by pytypes.
@chadrik It would be good if you could check whether it works like you would expect. I am going to file a new pytypes release soon, so now would be ideal time to make eventual adjustments.
Bump on this -- @agronholm how feasible would it be to add support for generic classes?
It could be, but likely won't be implemented any time soon. I have my hands full with the other features coming in v3.0, and then other projects that urgently require my attention.
Hello @agronholm
Do you think you'll implement this feature in the future ?
I already use typeguard, which is awesome to encourage my team maintaining type hinting in our projects. But we are starting to use Generic types, and it's a shame that they aren't supported by typeguard
Thanks