Add typing.override decorator #101561
Labels
3.12
only security fixes
stdlib
Python modules in the Lib dir
topic-typing
type-feature
A feature request or enhancement
Feature or enhancement
See PEP 698 for details.
The
typing.override
decorator should, at runtime, attempt to set the__override__
attribute on its argument toTrue
and then return the argument. If it cannot set the__override__
flag it should return its argument unchanged.Pitch
The purpose of
typing.override
is to inform static type checkers that we expect this method to override some attribute of an ancestor class. By having this decorator in place, a developer can ensure that static type checkers will warn them if a base class method name changes.To quote the PEP consider a code change where we rename a parent class method.
The original code looks like this:
And after our rename it looks like this:
In the code snippet above, renaming
foo
tonew_foo
inParent
invalidated the overridefoo
ofChild
. But type checkers have no way of knowing this, because they only see a snapshot of the code.If we mark
Child.foo
as an override, then static type checkers will catch the mistake when we rename onlyParent.foo
:Previous discussion
PEP 698 has details about the proposal itself.
Discussion on this proposal has happened on typing-sig and on [discuss.python.org)[https://discuss.python.org/t/pep-698-a-typing-override-decorator/20839].
Linked PRs
The text was updated successfully, but these errors were encountered: