Search code examples
pythonmypypython-typing

Python generics for Scala programmers


I come from the Scala world where the type system allows for very powerful abstractions.

What I'm trying right now is very simple, yet the Python mechanisms are confusing me a lot: I want to create a type alias that swaps the type params of a dict.

In Scala I can do:

type Pam[A,B] = Map[B,A]

But I've tried the same in Python and can't make it work:

B= TypeVar('B') 
A= TypeVar('A')
Tcid = dict[B,A]
def test()->Tcid[int,str]:
    return {
        "asd":1 ## MyPy complains
    }

I've swapped the definition order of typevars B and A, in the dict, everywhere, but it just doesn't work.

How can I tell MyPy/Python when creating type aliases, in which order to apply them?


Solution

  • I don't know how to do this in older versions of Python, but in 3.12 (using new syntax specified via PEP-695) it's very straightforward:

    type Tcid[A,B] = dict[B,A]
    

    Note that as of this writing, PEP-695 is only partially supported in mypy (and even that largely in a "don't crash in presence of valid syntax" kind of way), whereas pyright implements it fully.