I’ll explain the first addition by demonstrating a problem for you. Consider this object-oriented code where I have a
Cat class and a
Tiger class that inherits from it. The
Cat class has a method called
.noise(), which the
Tiger class overrides.
changing it to
.make_noise()? Most of the time when you do this, the intent is to make the same sort of changes to any inheriting classes as well. Now, if I have an instance of
Tiger, if I call
.make_noise(), I’m going to get
By having this kind of marker, the type checker can now flag the previous problem case. If I rename
.noise() inside of the
Cat class, mypy or tools like it can now point out that the
.noise() method in
Tiger is no longer overriding anything.
01:25 This is actually an idea stolen from other languages. In fact, the PEP that suggested it listed a half dozen others that can do the same thing. The only downside here is it makes the code a bit more verbose, but typing tends to do that.
The other addition to typing in Python 3.12 is a simplified syntax for typing generics. The old, and still supported, way of typing a generic is to use the
TypeVar concept from the
The use of the square brackets before the parentheses here indicate that the function uses a generic type. Whatever you put in the square brackets becomes your placeholder, which you then use for the type of the arguments and return value of the function. Not only is this cleaner syntax, but you no longer need to import anything from the
This is kind of similar to some of the improvements in 3.11, where you could use the built-in types as type indicators, saving you from having to import capital-L
List from the
typing module, allowing you to just use
list, the built-in, as a type specifier.
02:55 These features go a little deeper than this. They can can apply to classes in some other situations as well. If typing’s your thing and you want to learn all about the changes, go take a look at this tutorial.
Become a Member to join the conversation.