1. Create overrides (for when a method is overridden from a subclass) and implements (to indicate that some method conforms to an interface, even if not actually overriding a method) decorators as follows:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def overrides(method): | |
def wrapper(func): | |
if func.__name__ != method.__name__: | |
msg = "Wrong @override: %r expected, but overwriting %r." | |
msg = msg % (func.__name__, method.__name__) | |
raise AssertionError(msg) | |
if func.__doc__ is None: | |
func.__doc__ = method.__doc__ | |
return func | |
return wrapper | |
def implements(method): | |
def wrapper(func): | |
if func.__name__ != method.__name__: | |
msg = "Wrong @implements: %r expected, but implementing %r." | |
msg = msg % (func.__name__, method.__name__) | |
raise AssertionError(msg) | |
if func.__doc__ is None: | |
func.__doc__ = method.__doc__ | |
return func | |
return wrapper | |
2. Create templates (in PyDev) as follows:
Name: overrides
Description: @overrides
Pattern: @overrides(${superclass}.${next_class_or_method})
Name: implements
Description: @implements
@implements(${interface_class}.${next_class_or_method})
3. Use it in your code:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class A(object): | |
def method(self): | |
pass | |
class B(A): | |
@overrides(A.method) | |
def method(self): | |
pass | |
@implements(file.write) | |
def write(self): | |
pass |
To use it, just start typing 'overrides' before a 'def method' and apply the completion (and it should complete the class/method properly on overrides -- for the implements, the name of the implementing class will still be needed later on).
2 comments:
Would Python Abstract Base Classes help with this?
I think they're complimentary (in the same way that in java interfaces are complimentary to the @Override).
An example where the ABC would fail is if a method is removed and the implementor still implements it, even if it's not needed anymore.
Also, just by looking at the class implementing the ABC, it's hard to know which are the actual implemented methods.
Post a Comment