Skip to content

generic subclasss and typevar with constraint #7362

Open
@ZeeD

Description

@ZeeD

Not sure if this is a "bug" or I didn't understand generics, but

import typing

T = typing.TypeVar('T', str, int)


class Base(typing.Generic[T]):

    def __init__(self, bar: T):
        self.bar: T = bar


class Child(Base[T]):

    def __init__(self, bar: T):
        super().__init__(bar)

mypy 0.720 (on windows) says

> mypy.exe test\__init__.py
test\__init__.py:15: error: Argument 1 to "__init__" of "Base" has incompatible type "str"; expected "T"
test\__init__.py:15: error: Argument 1 to "__init__" of "Base" has incompatible type "int"; expected "T"

but if I change the T definition to T = typing.TypeVar('T') the errors go away

What I want is to specify that

  • the "Base" constructor has a parameter that could be an int or a str
  • the "Child" constructor has the same "signature" of the "Base" one (well, this is a simplified example, I want something more...)

is this a bug? di I misinterpreted the TypeVar usage?

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions