Skip to content Skip to sidebar Skip to footer

Merging Class Members

Given a class structure like this: class A: dependencies = ['x', 'y'] class B(A): dependencies = ['z'] class C(A): dependencies = ['n', 'm'] class D(C): dependen

Solution 1:

Walk the mro and grab the dependencies is what I'd do:

@classmethoddefget_dep(cls):
    return [d for c in cls.mro()[:-1] for d ingetattr(c, 'dependencies')]

with cls.mro()[:-1] being used to exclude object.

This returns:

>>> A.get_dep()
['x', 'y']
>>> B.get_dep()
['z', 'x', 'y']
>>> C.get_dep()
['n', 'm', 'x', 'y']
>>> D.get_dep()
['o', 'n', 'm', 'x', 'y']

Solution 2:

Walk the MRO manually:

@classmethoddefget_all_dependencies(cls):
    deps = []
    for c in cls.__mro__:
        # Manual dict lookup to not pick up inherited attributes
        deps += c.__dict__.get('dependencies', [])
    return deps

If you want to deduplicate dependencies that appear repeatedly in the MRO, you can:

from collections import OrderedDict

@classmethoddefget_all_dependencies(cls):
    returnlist(OrderedDict.fromkeys(dep for c in cls.__mro__
                                         for dep in c.__dict__.get('dependencies', [])))

Solution 3:

You can certainly do this if you define "get_all_dependencies" on each class and, instead of cls.dependencies, you reference the class that you're on (ie. super(B, self).get_all_dependences() + B.dependencies)

Post a Comment for "Merging Class Members"