subclass __module__ set to metaclass module when manually creating new class with type()

前端 未结 1 1841
天涯浪人
天涯浪人 2021-01-19 23:15

In the following example, the newly created subclass ends up being the metaclass __module__ rather than the parent classes\' module. I\'ve only seen this happe

相关标签:
1条回答
  • 2021-01-20 00:02

    If no __module__ key is present in the mapping passed to type.__new__, type.__new__ determines __module__ based on the module where the call to type.__new__ occurs, by looking for __name__ in the globals of the top Python stack frame.

    When you run newclass = type('newclass', (test,), {}), the type constructor delegates to abc.ABCMeta, which then calls type.__new__ from inside the abc module, so type thinks that __module__ should probably be abc.

    When you write the class statement

    class subtest(test):
        pass
    

    The compiled bytecode for the class statement automatically includes a __module__ = __name__ assignment, which uses the current module's __name__ instead of abc.__name__.

    If you want to control the value of __module__ for a class created by calling type directly, you can set the key in the original mapping, or assign to the class's __module__ after creation:

    newclass = type('newclass', (test,), {'__module__': __name__})
    
    # or
    
    newclass = type('newclass', (test,), {})
    newclass.__module__ = __name__
    
    0 讨论(0)
提交回复
热议问题