Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python typing: how to name a new type?

I wanted to give a name to a dict type, something like:

MyDictType = Dict[int, SomeClass]

and so I found about NewType, but it seems to only accepts runtime types:
the code MyDictType = NewType('MyDictType', Dict[int, SomeClass]
creates the warning Expected type 'Type[_T]', got '_VT' instead

So what is the correct way to do this?

*I'm using Python 3.7 . Please let me know if there's a better solution in newer versions.

like image 659
chikchakchok Avatar asked Dec 21 '25 08:12

chikchakchok


1 Answers

You can do

from typing import NewType

MyDictType = NewType("MyDictType", Dict[int, SomeClass])

NewType was added in 3.5.2, but behaviour changed in 3.10. Here're the docs for 3.10: https://docs.python.org/3/library/typing.html#typing.NewType

like image 152
Anna Avatar answered Dec 23 '25 00:12

Anna



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!