Triple inheritance causes metaclass conflict… Sometimes

The error message indicates that you have two conflicting metaclasses somewhere in your hierarchy. You need to examine each of your classes and the QT classes to figure out where the conflict is. Here’s some simple example code that sets up the same situation: class MetaA(type): pass class MetaB(type): pass class A: __metaclass__ = MetaA …

Read more

How to read class attributes in the same order as declared?

In the current version of Python, the class ordering is preserved. See PEP520 for details. In older versions of the language (3.5 and below, but not 2.x), you can provide a metaclass which uses an OrderedDict for the class namespace. import collections class OrderedClassMembers(type): @classmethod def __prepare__(self, name, bases): return collections.OrderedDict() def __new__(self, name, bases, …

Read more

Metaclass multiple inheritance inconsistency

It’s not a custom-metaclass problem (though it’s diagnosed at metaclass stage): >>> class Normal(object): pass … >>> class MyObject(object, Normal): pass … Traceback (most recent call last): File “<stdin>”, line 1, in <module> TypeError: Error when calling the metaclass bases Cannot create a consistent method resolution order (MRO) for bases object, Normal and the problem’s …

Read more

How to auto register a class when it’s defined

Yes, meta classes can do this. A meta class’ __new__ method returns the class, so just register that class before returning it. class MetaClass(type): def __new__(cls, clsname, bases, attrs): newclass = super(MetaClass, cls).__new__(cls, clsname, bases, attrs) register(newclass) # here is your register function return newclass class MyClass(object): __metaclass__ = MetaClass The previous example works in …

Read more

Using abc.ABCMeta in a way it is compatible both with Python 2.7 and Python 3.5

You could use six.add_metaclass or six.with_metaclass: import abc, six @six.add_metaclass(abc.ABCMeta) class SomeAbstractClass(): @abc.abstractmethod def do_something(self): pass six is a Python 2 and 3 compatibility library. You can install it by running pip install six or by downloading the latest version of six.py to your project directory. For those of you who prefer future over six, …

Read more