Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading