如何跟踪传递给元类的关键字?

How to keep track of keywords passed to metaclass?

我有一个接受关键字参数的元class:

class M(type):
    def __new__(cls, *args, **kwargs):
        print(*kwargs.items())
        super().__new__(cls, *args)

它按预期工作:

class A(metaclass=M, test='X'): pass

生成对象 A 和打印输出

('test', 'X')

我想使用 this:

之类的方式复制 A
def copy_class(cls, name=None):
    if name is None:
        name = cls.__name__
    return type(cls)(name, cls.__bases__, dict(cls.__dict__))

A_copy = copy_class(A, 'A_copy')

但是,关键字不存在。当 type(cls) 需要 额外的参数或者当它们不存在时产生不同的副作用时,这尤其是一个问题。

我知道我可以 M 将关键字存储在 class 对象中的某处,但这不是一个很好的解决方案,因为我的复制方法非常 class -依赖。

是否有内置方法来检索在 Python 中创建 class 的关键字?

Python 不会为您保存关键字参数。这很容易证明:

>>> class DoesntSaveKeywords(type):
...     def __new__(cls, name, bases, dict, **kwargs):
...         return super().__new__(cls, name, bases, dict)
... 
>>> class PrintsOnDel:
...     def __del__(self):
...         print('__del__')
... 
>>> class Foo(metaclass=DoesntSaveKeywords, keyword=PrintsOnDel()):
...     pass
... 
__del__

此外,我认为尝试像这样复制 class 的基本想法没有意义。不能保证 class 的 __dict__ 看起来像最初传递给 metaclass 构造函数的内容,或者再次调用 metaclass 构造函数会远程执行任何操作合理。