__metaclass__ in Python 3

Python 3 changed how you specify a metaclass, __metaclass__ is no longer checked. Use metaclass=… in the class signature: class Table(object, metaclass=MetaTable): Demo: >>> class MetaTable(type): … def __getattr__(cls, key): … temp = key.split(“__”) … name = temp[0] … alias = None … if len(temp) > 1: … alias = temp[1] … return cls(name, alias) … Read more

Auto-register class methods using decorator

Here’s a little love for class decorators. I think the syntax is slightly simpler than that required for metaclasses. def class_register(cls): cls._propdict = {} for methodname in dir(cls): method = getattr(cls, methodname) if hasattr(method, ‘_prop’): cls._propdict.update( {cls.__name__ + ‘.’ + methodname: method._prop}) return cls def register(*args): def wrapper(func): func._prop = args return func return wrapper … 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

python abstractmethod with another baseclass breaks abstract functionality

Surprisingly, the test that prevents instantiating abstract classes happens in object.__new__, rather than anything defined by the abc module itself: static PyObject * object_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { … if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) { … PyErr_Format(PyExc_TypeError, “Can’t instantiate abstract class %s ” “with abstract methods %U”, type->tp_name, joined); (Almost?) all built-in types that … Read more

Dynamic Class Creation in SQLAlchemy

You can dynamically create MyObject using the 3-argument call to type: type(name, bases, dict) Return a new type object. This is essentially a dynamic form of the class statement… For example: mydict={‘__tablename__’:stored[‘tablename’], ‘__table_args__’:{‘autoload’:True},} MyObj=type(stored[‘objectname’],(Base,),mydict) print(MyObj) # <class ‘__main__.MyObject’> print(MyObj.__base__) # <class ‘__main__.Base’> print(MyObj.__tablename__) # my_internal_table_name print(MyObj.__table_args__) # {‘autoload’: True}

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