[Python] Issue with Handling Union Types in Generic Class Properties

Discussão em 'Python' iniciado por Stack, Agosto 3, 2025.

  1. Stack

    Stack Membro Participativo

    In Python 3.13.3

    from typing import Self


    class Detail1:
    x: int

    def update(self, other: Self) -> None:
    self.x += other.x

    class Detail2:
    y: str

    def update(self, other: Self) -> None:
    self.y += other.y

    DetailUnion = Detail1 | Detail2


    class Foo[Detail: DetailUnion]:

    detail: Detail

    def foo(self, other: Self) -> None:
    self.detail.update(other.detail) # A type error here.


    In the last line, I got an error from my Pylance:

    Argument of type "Detail@Foo" cannot be assigned to parameter "other" of type "Detail1*" in function "update"
    Type "Detail1* | Detail2*" is not assignable to type "Detail1*"
    "Detail2*" is not assignable to "Detail1*" Pylance(reportArgumentType)

    Argument of type "Detail@Foo" cannot be assigned to parameter "other" of type "Detail2*" in function "update"
    Type "Detail1* | Detail2*" is not assignable to type "Detail2*"
    "Detail1*" is not assignable to "Detail2*" Pylance(reportArgumentType)


    It seems that the error came from the union type. But due to some issue, I have to use union in my project.

    In my eyes, other should share the same type as self in the method def foo, thus self.detail and other.detail are also of the same type. However, Pylance regarded other.detail as the union type DetailUnion. Therefore, it cannot be assigned to the argument in detail.update.

    I tried like 'Foo[Detail]' instead of Self for the type annotations, but they still didn't work.

    I hope to change only in the Foo class, leaving Detail1 and DetailUnion the same.

    How should I deal with this?

    Continue reading...

Compartilhe esta Página