Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork33.7k
Description
Feature or enhancement
SeePEP 698 for details.
Thetyping.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 oftyping.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:
classParent:deffoo(self,x:int)->int:returnxclassChild(Parent):deffoo(self,x:int)->int:returnx+1defparent_callsite(parent:Parent)->None:parent.foo(1)defchild_callsite(child:Child)->None:child.foo(1)
And after our rename it looks like this:
classParent:# Rename this methoddefnew_foo(self,x:int)->int:returnxclassChild(Parent):# This (unchanged) method used to override `foo` but is unrelated to `new_foo`deffoo(self,x:int)->int:returnx+1defparent_callsite(parent:Parent)->None:# If we pass a Child instance we’ll now run Parent.new_foo - likely a bugparent.new_foo(1)defchild_callsite(child:Child)->None:# We probably wanted to invoke new_foo here. Instead, we forked the methodchild.foo(1)
In the code snippet above, renamingfoo 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 markChild.foo as an override, then static type checkers will catch the mistake when we rename onlyParent.foo:
fromtypingimportoverrideclassParent:defnew_foo(self)->int:return1defbar(self,x:str)->str:returnxclassChild(Parent):@overridedeffoo(self)->int:# Type Error: foo does not override an attribute of any ancestorreturn2
Previous discussion
PEP 698 has details about the proposal itself.
Discussion on this proposal has happened ontyping-sig and on [discuss.python.org)[https://discuss.python.org/t/pep-698-a-typing-override-decorator/20839].