Skip to content

Using generic self in a generic class #3363

Closed
@cyang1

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)

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