Niklas9
Niklas9

Reputation: 9386

Using a metaclass depending on configuration

I have a class that I want to set a metaclass for depending on what is configured, example:

use_metaclass = True

class B(object):  pass

class A(object):
    __metaclass__ = B

However, if the configuration (use_metaclass) is False, I would not like the metaclass to be set for A.

How can I implement this? I realize that a class is an instance of a metaclass, so I guess this has to be set in A's definition in some way rather than after A has been instantiated.

Example what I want to "accomplish" but won't work due to what's said above:

use_metaclass = True

class B(object):  pass

class A(object):
    def __init__(self):
        if use_metaclass:
            self.__metaclass__ = B

Upvotes: 0

Views: 135

Answers (1)

Blckknght
Blckknght

Reputation: 104722

You can put conditional logic in the class body if you need to:

class A(object):
    if use_metaclass:
        __metaclass__ = B

This gets evaluated at class definition time, so you need to make sure use_metaclass is set to the desired value before the class is loaded (you can't change the metaclass later).

In Python 3, where metaclasses are declared differently, you'd need to use the if/else ternary operator in the class line:

class A(metaclass=B if use_metaclass else type):
    pass

If use_metaclass is False, it will specify type as the metaclass. That's fine, since type is the default metaclass if nothing is declared (and all metaclasses in Python 3 must derive from type).

Upvotes: 1

Related Questions