[Python-ideas] @Override decorator
Steven D'Aprano
steve at pearwood.info
Mon Jul 18 23:58:58 EDT 2016
On Mon, Jul 18, 2016 at 09:44:45AM -0700, Shrey Desai wrote:
> Why I would think an override decorator might be useful:
> For other people reading the code, it would be great to distinguish
> between methods that are unique to a class and methods that are
> inherited from a parent class. Not all methods inherited might be
> overridden, so keeping track of which inherited methods are overridden
> and which are not would be nice.
I fail to see that this is a sufficiently great problem to require a
decorator. Occasionally I've added a comment to a method "Overriding
mixin" or "Overriding class XXX" for example, but mostly I don't even
bother. It's either obvious or unimportant or both. And when I do find
myself writing such a comment, that's a good sign that my class
hierarchy is too hard to understand and needs to be refactored.
> With the advent of static typing from mypy:
> Having the decorator could corroborate the fact that the given method
> overrides the parent method correctly (correct name + parameter list).
There is no requirement that the subclass method uses the same parameter
names, or even signature, as the superclass method.
> When the parent class changes, such as the name or parameter list of
> an abstract method, the children classes should be updated as well.
> mypy could easily target the methods that need to be altered with the
> correct method signature.
> If you don’t have an override decorator and overrode a parent method,
> then there could be some error complaining about this. This would be
> extremely useful to prevent accidental errors.
I don't see it being very useful. Perhaps for people who have learned
bad habits from Java and write deep class hierarchies, but we shouldn't
encourage such anti-patterns. If people wish to write their own
@override decorator, they should go right ahead, but I don't think it
belongs in the standard library.
--
Steve
More information about the Python-ideas
mailing list