2

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

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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'>)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.