The Python Oracle

Python inheritance, metaclasses and type() function

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Cool Puzzler LoFi

--

Chapters
00:00 Question
00:44 Accepted answer (Score 6)
01:54 Thank you

--

Full question
https://stackoverflow.com/questions/1419...

Accepted answer links:
[Base metaclass overriding __new__ generates classes with a wrong __module__]: https://stackoverflow.com/questions/1120...
[Weird inheritance with metaclasses]: https://stackoverflow.com/questions/1212...
[new method]: http://hg.python.org/cpython/file/900917...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #class #pythonimport #abc

#avk47



ACCEPTED ANSWER

Score 6


The problem stems from the fact that ABCMeta overrides __new__ and calls its superclass constructor (type()) there. type() derives the __module__ for the new class from its calling context1; in this case, the type call appears to come from the abc module. Hence, the new class has __module__ set to abc (since type() 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:

MyClass2 = type('MyClass2', (PackageClass, ), {})
MyClass2.__module__ = __name__

I would also recommend filing a bug report.

Related: Base metaclass overriding __new__ generates classes with a wrong __module__, Weird inheritance with metaclasses

1: type is a type object defined in C. Its new method uses the current global __name__ as the __module__, unless it calls a metaclass constructor.