Last active
January 3, 2016 05:08
-
-
Save nickretallack/8413416 to your computer and use it in GitHub Desktop.
This is useful if you're making mixins that each add a little something to the same set of functions, and there's no guaranteed that the base class has those functions defined, or perhaps there is no base class in common and you don't want to be bothered with thinking about method resolution order between your mixins.
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 maybe_super(cls, self, method_name, base_value=None): | |
""" Call the super method if it exists. | |
Use it like this: | |
def some_method(self, *args, **kwargs): | |
result = maybe_super(MyClass, self, 'some_method')(*args, **kwargs) | |
""" | |
sup = super(cls, self) | |
method = getattr(sup, method_name, None) | |
if method: | |
return method | |
else: | |
return lambda *args, **kwargs: base_value | |
# method(*args, **kwargs) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment