[Python] Map one type to another and make type checker understand

Discussão em 'Python' iniciado por Stack, Julho 15, 2025.

  1. Stack

    Stack Membro Participativo

    I have the following piece of code:

    from typing import Any

    class RawA:
    pass

    class A:
    pass

    class RawB:
    pass

    class B:
    pass

    # Example of a kind of mapping (that doesn't work)
    mapping = {
    RawA: A,
    RawB: B
    }


    def unraw[TRaw: Any](obj: TRaw) -> Any # -> the unraw type
    ...


    Now how would I create some sort of mapping (of course a dictionary like here won't work) that the type checker then uses to find the appropriate return type?

    For example, if I pass an instance of RawA into my function, the type checker understands the return value will be an instance of the type RawA is mapped to, in this case A.

    I know could just exhaust all possibilities via overloads, but that is way to cumbersome and error prone for my case.

    Continue reading...

Compartilhe esta Página