You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将types.new_class创建的类归属到当前运行模块而非abc模块?

Fixing Module Ownership for Dynamically Created ABC Classes

When you use types.new_class to create a class that inherits from abc.ABCMeta, the issue where the class ends up belonging to the abc module instead of your current module happens because the dynamic class creation process doesn't automatically set the __module__ attribute to your current module's name. The fix is straightforward—you just need to explicitly assign this attribute to the generated class.

Modified Code Example

import abc
import types

class Base(metaclass=abc.ABCMeta):
    @abc.abstractmethod
    def method(self, x):
        pass

def generate_a_class(name):
    def method(self, x):
        print(f"Method received {x}")
    class_body = {method.__name__: method}
    NewClass = types.new_class(
        name,
        bases=(Base,),
        # Add __module__ to the namespace pointing to the current module
        exec_body=lambda ns: ns.update({**class_body, '__module__': __name__}))
    return NewClass

# Test it out
print(generate_a_class("Implementation"))  # Outputs <class '__main__.Implementation'>

Alternative Equivalent Approach

You can also set the __module__ property right after creating the class—this works just as well:

def generate_a_class(name):
    def method(self, x):
        print(f"Method received {x}")
    class_body = {method.__name__: method}
    NewClass = types.new_class(
        name,
        bases=(Base,),
        exec_body=lambda ns: ns.update(class_body))
    # Manually assign the module after class creation
    NewClass.__module__ = __name__
    return NewClass

Why This Happens

When using abc.ABCMeta as the metaclass, types.new_class doesn't automatically populate the __module__ attribute with your current module's name. Instead, it falls back to using the module where the metaclass (abc) is defined. By explicitly setting __module__ to __name__ (the name of your current running module), you force the class to be associated with the correct module.

内容的提问来源于stack exchange,提问作者jabozzo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:06:50