Created
November 2, 2011 18:40
-
-
Save anonymous/1334476 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import inspect | |
import operator | |
# | |
# Core mechanic | |
# | |
def merge_from_ancestors(self, attribute): | |
""" | |
Merge parent, etc class' <attribute> list values into one list. | |
Walks from top to bottom; mildly pointless with lists, more useful for a | |
dict-using implementation perhaps. | |
""" | |
return reduce( | |
operator.add, | |
map( | |
lambda x: getattr(x, attribute, []), | |
list(reversed(inspect.getmro(self.__class__))) | |
), | |
[] | |
) | |
# | |
# Super explicit 1st version | |
# | |
class Merger(object): | |
def get_values(self): | |
return merge_from_ancestors(self, 'values') | |
class Parent(Merger): | |
values = ['foo', 'bar'] | |
class Child(Parent): | |
values = ['biz', 'baz'] | |
print Child().get_values() # => ['foo', 'bar', 'biz', 'baz'] | |
# | |
# Slightly fancier/more implicit | |
# | |
class Merger(object): | |
@property | |
def values(self): | |
return merge_from_ancestors(self, '_values') | |
class Parent(Merger): | |
_values = ['foo', 'bar'] | |
class Child(Parent): | |
_values = ['biz', 'baz'] | |
print Child().values # => ['foo', 'bar', 'biz', 'baz'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment