One of the new features of Python 3.10 is TypeAlias. The example given is as follows.
It can be written as.
This makes StrCache more of a type alias than a string variable that clearly looks like Cache[str]
(which it is).
This article is not about TypeAlias per se, but rather about Cache[str]
, which shows that Python seems to support Java-like generics, like Python’s built-in support for List[str] or list[str].
So let’s see how Python can implement a Cache[str]
Cache that can only hold strings, but not other types.
|
|
We are still using Python’s typing module, so the above code is still in the realm of class type hints, which is not a constraint on the Python interpreter and only affects checking tools like mypy.
using the above class.
The command python test.py
works fine and the output is as follows.
But in IntelliJ IDEA, the fifth line above, the cache.put('b', 123)
line, prompts:
|
|
If you use mypy
to detect.
In addition to Generic, TypeVar used above, typing module has more type constraints like Mapping, Iterator, Sequence and more Java-like generic functions.
Generic subtypes
Generic functions
There are more uses than can be listed here. The need to write your own implementation code using generics is not really big, unless you do a third-party generic library that will use generic writing, which makes it clearer for others to use.