Why is my metaclass implementation failing with TypeError about not being able to instantiate NoneType

I have the following Python code:

class MetaData(object):
    _md = {}

class _ClassMeta(type):
    def __new__(cls, clsname, bases, dct):
        ncls = super(_ClassMeta, cls).__new__(cls, clsname, bases, dct)
        MetaData._md[clsname] = ncls

class Meta(object):
    __metaclass__ = _ClassMeta

class Test(Meta):
    pass

      

When I try to execute it, I get this:

TypeError: Error when calling the metaclass bases
    cannot create 'NoneType' instances

      

in line with class Test(Meta):

I don't understand why. Obviously the metaclass function __new__

was named differently for the Meta class, but not for the derived test class.

For those asking why, I'm looking into registering and modifying a runtime class within ORMs such as Django and SqlAlchemy. This may not be how I am finally building my code, but I would still like to have an answer to the question why I am getting a TypeError.

+3


source to share


1 answer


Your problem is pretty simple: the method __new__

has to create an instance and return it. You don't return anything, so it returns None

.

Since it is a metaclass __new__

, this means that it is called to create an object of the class Meta

. So you just defined Meta

as None

and not as a type class _ClassMeta

. This is a perfectly correct thing, so there is no error, but as soon as you try to do something with it, for example Meta()

, you will get an exception from NoneType

that cannot be thrown or similar.



And that includes subclassing. You cannot subclass None

because it is not a type.

+6


source







All Articles