I can’t understand why the following code behaves a particular way, which is described below:
from abc import ABCMeta
class PackageClass(object):
__metaclass__ = ABCMeta
class MyClass1(PackageClass):
pass
MyClass2 = type('MyClass2', (PackageClass, ), {})
print MyClass1
print MyClass2
>>> <class '__main__.MyClass1'>
>>> <class 'abc.MyClass2'>
Why does repr(MyClass2) says abc.MyClass2 (which is by the way not true)?
Thank you!
The problem stems from the fact that
ABCMetaoverrides__new__and calls its superclass constructor (type()) there.type()derives the__module__for the new class from its calling context1; in this case, thetypecall appears to come from theabcmodule. Hence, the new class has__module__set toabc(sincetype()has no way of knowing that the actual class construction took place in__main__).The easy way around is to just set
__module__yourself after creating the type:I would also recommend filing a bug report.
Related: Base metaclass overriding __new__ generates classes with a wrong __module__, Weird inheritance with metaclasses
1:
typeis a type object defined in C. Its new method uses the current global__name__as the__module__, unless it calls a metaclass constructor.