typeguard icon indicating copy to clipboard operation
typeguard copied to clipboard

Add support for generic classes

Open chadrik opened this issue 8 years ago • 7 comments

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

chadrik avatar Aug 08 '17 22:08 chadrik

You mean

a = IntA(7)  # good!
a = IntA('foo')  # bad!

don't you?

Stewori avatar Aug 15 '17 21:08 Stewori

d'oh, yes. lemme fix that.

chadrik avatar Aug 15 '17 22:08 chadrik

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?

Stewori avatar Aug 16 '17 21:08 Stewori

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.

Stewori avatar Oct 26 '17 14:10 Stewori

Bump on this -- @agronholm how feasible would it be to add support for generic classes?

supersergiy avatar Feb 22 '23 00:02 supersergiy

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.

agronholm avatar Feb 22 '23 11:02 agronholm

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

hoorelbeke-jimmy avatar Apr 25 '24 15:04 hoorelbeke-jimmy