Skip to content

Type variable return value from class methods #3438

Closed
@orenbenkiki

Description

@orenbenkiki

mypy gets confused about the type of a type variable return value from a class method:

from typing import TypeVar
from typing import Generic

P=TypeVar('P')

class G(Generic[P]):

    @classmethod
    def c(cls) -> 'P':
        assert False

    def s(self) -> 'P':
        assert False

class C:
    pass

class GC(G[C]):
    pass

c = C()
c = GC().s() # OK
c = GC.c() # error: Incompatible types in assignment (expression has type "P", variable has type "C")

This is causing a huge PITA in my code...

Actually, in my code I would really want to make c a @classproperty, that is, be able to write GC.c instead of GC.c(). I can implement a @classproperty decorator by myself, of course, but that would mean giving up on any hope whatsoever of mypy being able to type-check my code. Of course, in an ideal world, one would just be able to say both @property and @classmethod, but they don't compose... Sigh.

I expected the simple @classmethod to work, though. I assume this is a bug? Is there a workaround?

BTW - I am using mypy 0.501 and Python 3.6.0, if that matters...

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions