Python 3.12: @override for Static Typing
One more valuable addition to Python’s Typing ecosystem in Python 3.12
Python 3.12 is officially releasing on October 2, 2023, let’s dive into one of the improvements in typing module.
Introduction of @override in Inheritance
A new decorator (@override) is introduced as part of PEP 698 focusing on reducing run time errors in Inheritance. Let’s see how to use `override` in Inheritance.
from typing import override
class Parent:
def foo(self) -> int:
return 1
class Child(Parent):
@override
def foo(self) -> int:
return 2
When Child Class overrides any methods from Parent class, You can decorate it with @override saying that the parent class method been overridden.
Is it mandatory to use @override in Child class while overriding the methods?
No! Its optional, similar to other type checking in Python.
So What’s the big deal if its not mandatory?
Let’s imagine, the methods in Parent class is renamed to new_foo from foo, since child class method is already decorated with override, this raises
In a large codebase, it is impossible to keep a track all sub class implementations, so, this feature will reduce the possibility of errors in run time when a parent class method is updated.
from typing import override
class Parent:
def new_foo(self) -> int: # renamed to new_foo from foo
return 1
class Child(Parent):
@override
def foo(self) -> int:
return 2
# Type check error: no matching signature in ancestor
Does any other language has this feature?
Of course, Below are the Popular programming languages uses this feature already,
Java
Typescript
Kotlin
Scala
Swift
C++
C#
Hope this helps, Thank you!!