Skip to content

Using generic self in a generic class #3363

Closed

Description

@cyang1

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)

Activity

  1. ilevkivskyi commented on May 16, 2017

    @ilevkivskyi
    Member

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

  2. ilevkivskyi commented on May 16, 2017

    @ilevkivskyi
    Member

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

  3. ilevkivskyi commented on Jun 11, 2019

    @ilevkivskyi
    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

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