Add typing.override decorator #101561
Labels
3.12
bugs and 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.overridedecorator should, at runtime, attempt to set the__override__attribute on its argument toTrueand then return the argument. If it cannot set the__override__flag it should return its argument unchanged.Pitch
The purpose of
typing.overrideis 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
footonew_fooinParentinvalidated the overridefooofChild. But type checkers have no way of knowing this, because they only see a snapshot of the code.If we mark
Child.fooas 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: