Specifying the list of base classes in Python programmatically

88 views Asked by At

I need to base the decision of which classes to derive from based on a flag.

For instance:

if SOME_FLAG:
   class A(B,C):
      ...definitions...
else:
   class A(B):
      ...definitions...

The question is how to avoid duplicating the ...definitions...

I tried using argument lists like one would do for normal functions, but it does not work for classes:

base_classes = [B,C] if SOME_FLAG else [B]
class A(*base_classes):
   ...definitions...

But this syntax is invalid.

(I know there are tricks for dynamically adding superclasses, but this case is different: it's a definition-time customization, not a full-blown dynamic redefinition of base classes)

1

There are 1 answers

0
kindall On BEST ANSWER

The easiest way is probably to conditionally define an intermediate class, then derive class A from that.

X = B
if SOME_FLAG:
   class X(B, C): pass

class A(X):
    # definitions

It's also possible to write a metaclass that accepts a sequence for the parent classes, though that seems like overkill:

def meta(name, bases, dict):
    if len(bases) == 1 and isinstance(bases[0], (tuple, list)):
        bases = bases[0]
    return type(name, bases, dict)

parents = (B, C) if SOME_FLAG else B

# Python 3
class A(parents, metaclass=meta):
    # definitions

# Python 2
class A(parents):
    __metaclass__ = meta
    # definitions