Skip to content

Generic class and Union TypeVar #577

Closed
@geckyan

Description

@geckyan

Description

I've been trying to make "type-safe" ("type checkable") interfaces for custom parsing facilities, wrote generic Parser[ParsingT, ParsedT] and then MultiParser[ParsingT, Union[...]] to compose parsers. Latter gives me weird errors. I don't know whether it's a bug or my way of using generic classes has flaws. The code below will tell more... :)

Minimal code to reproduce:

from typing import Generic, TypeVar, Union

BarT = TypeVar('BarT')

class BasicFoo(Generic[BarT]):
    pass

class Foo(BasicFoo[BarT]):
    def add(self, sub_foo: BasicFoo[BarT]):
        pass

foo = Foo[Union[int, str]]()
foo.add(Foo[int]()) # Error: Argument of type 'Foo[int]' cannot be assigned to parameter 'sub_foo' of type 'BasicFoo[Union[int, str]]'. Type 'int' cannot be assigned to type 'Union[int, str]'.
foo.add(Foo[str]()) # Error: Argument of type 'Foo[str]' cannot be assigned to parameter 'sub_foo' of type 'BasicFoo[Union[int, str]]'. Type 'str' cannot be assigned to type 'Union[int, str]'.

Expected behaviour

No errors... I suppose so.

Context:

  • Python 3.8.2
  • VS Code 1.43.1 (user setup)
  • pyright 1.1.28

Metadata

Metadata

Assignees

No one assigned

    Labels

    as designedNot a bug, working as intended

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions