8000 Using generic self in a generic class · Issue #3363 · python/mypy · GitHub
[go: up one dir, main page]

Skip to content

Using generic self in a generic class #3363

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
cyang1 opened this issue May 15, 2017 · 3 comments
Closed

Using generic self in a generic class #3363

cyang1 opened this issue May 15, 2017 · 3 comments

Comments

@cyang1
Copy link
cyang1 commented May 15, 2017

The recommended method for writing a factory method is to type the cls argument as Type[T] (http://mypy.readthedocs.io/en/latest/generics.html#generic-methods-and-generic-self). However, this doesn't seem to be able to handle the case where the factory class itself is generic.

In the example below, if we just specify bound=FactoryBase on the _FactoryBase typevar, mypy gives error: Argument 1 to "make" of "FactoryBase" has incompatible type "int"; expected "T".

from typing import (
    Any,
    Generic,
    TypeVar,
    Type,
)

T = TypeVar('T')
_FactoryBase = TypeVar('_FactoryBase', ???)

class FactoryBase(Generic[T]):
    def __init__(self, obj):
        # type: (T) -> None
        pass

    @classmethod
    def make(cls, obj):
        # type: (Type[_FactoryBase], T) -> _FactoryBase
        return cls(obj)

class Factory(FactoryBase[int]):
    pass

Factory.make(2)
@ilevkivskyi
Copy link
Member

It looks like this is a duplicate of #2354 (although I am not 100% sure).

@ilevkivskyi
Copy link
Member

Maybe it makes to copy this example (i.e. with @classmethod) to the original issue an close this one?

@ilevkivskyi
Copy link
Member

FWIW the original example (with bound=FactoryBase) works correctly on master.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants
0