Skip to content

Instantly share code, notes, and snippets.

@nickretallack
Last active January 3, 2016 05:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nickretallack/8413416 to your computer and use it in GitHub Desktop.
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.
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