[Python] Python narrow class type variable in method

Discussão em 'Python' iniciado por Stack, Abril 8, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to emulate Rust's

    impl<T> Trait for Struct<T> where T: Bound


    (assuming Struct does not bound its type variable, as is generally recommended)

    My idea of doing this in Python is as follows:

    from dataclasses import dataclass

    @dataclass
    class A[T]:
    data: T

    def m[C: int](self: "A[C]") -> int:
    return self.data * 2

    a1 = A(1)
    a2 = A("hi")

    a1.m()
    a2.m()


    Pylance correctly flags a2.m() as an error, so this apparently works. Is this the best I can do in Python? In particular I'm not thrilled about the "A[C]" annotation since this might cause issues when subtyping A.

    Continue reading...

Compartilhe esta Página