Last active
January 8, 2022 18:21
-
-
Save offlinehacker/5928482 to your computer and use it in GitHub Desktop.
Merges result of function or attribute from child class with result of function or attribute from the base class.
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 merge_with_base(object): | |
""" | |
Merges result of function or attribute from child class with result of | |
function or attribute from the base class. | |
:param type: Use this base class instead of first base class found and | |
not with mixins | |
.. note:: | |
Currently it only works with one base class | |
>>> class parent(object): | |
... def test(self, param): | |
... return param + [False] | |
... | |
>>> class child(parent): | |
... @merge_with_base() | |
... def test(self, param): | |
... return param + [False] | |
>>> child().test(["test"]) | |
['test', False, 'test', False] | |
It also works with properties: | |
>>> class parent(object): | |
... @property | |
... def test(self): | |
... return [False] | |
... | |
>>> class child(parent): | |
... @property | |
... @merge_with_base() | |
... def test(self): | |
... return [True] | |
>>> child().test | |
[False, True] | |
""" | |
def __init__(self, type=None): | |
self.type = type | |
def __call__(self, obj): | |
@wraps(obj) | |
def merger(*args, **kwargs): | |
base = args[0].__class__.__bases__[0] or self.type | |
f = getattr(args[0].__class__.__bases__[0], obj.func_name, None) | |
args = (super(base, args[0]),) + args[1:] | |
if ismethod(f): | |
ret = f.im_func(*args, **kwargs) | |
elif isinstance(f, property): | |
ret = f.fget(*args, **kwargs) | |
else: | |
ret = None | |
return ret + obj(*args, **kwargs) if ret else obj(*args, **kwargs) | |
return merger | |
if __name__ == "__main__": | |
import doctest | |
doctest.testmod() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment