Reputation: 2863
In python 3 I can use list expansion to dynamically inherit from multiple superclasses:
class Super1(object):
x = 1
class Super2(object):
y = 1
classes = [Super1, Super2]
class B(*classes):
pass
This lets me allow for runtime decisions about which mixin classes to add to the list of superclasses.
Unfortunately, the *
expansion of the superclass list is a syntax error in python2. Is there a generally accepted way of choosing the list of superclasses at runtime
Upvotes: 2
Views: 46
Reputation: 2863
The answer provided by @blhsing is correct, but I actually wanted something that was 2/3 compatible. I took the cue of using type
directly and did something more like this:
class Super1(object):
x = 1
class Super2(object):
y = 1
classes = [Super1, Super2]
B = type('B', tuple(classes), {})
Which works equally well in 2/3
Upvotes: 2
Reputation: 107134
You can use a metaclass to populate B
's base classes instead:
classes = Super1, Super2
class B:
__metaclass__ = lambda name, _, attrs: type(name, classes, attrs)
print(B.__bases__)
This outputs:
(<class '__main__.Super1'>, <class '__main__.Super2'>)
Upvotes: 1