How to keep track of keywords passed to metaclass?

橙三吉。 提交于 2019-12-11 17:49:49

问题


I have a metaclass that accepts keyword arguments:

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

It works as expected:

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

results in an object A and the printout

('test', 'X')

I would like to make a copy of A using something like this:

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')

However, the keywords are not present. This is especially a problem when type(cls) requires additional arguments or otherwise produces different side-effects when they are not there.

I am aware that I can have M stash the keywords in the class object somewhere, but this is not a very good solution because then my copy method is very class-dependent.

Is there a built-in way to retrieve the keywords a class was created with in Python?


回答1:


Python will not save the keyword arguments for you. This is simple to demonstrate:

>>> 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__

Also, I don't think the underlying idea of trying to copy a class like this makes sense. There's no guarantee that the class's __dict__ looks anything like what was originally passed to the metaclass constructor, or that calling the metaclass constructor again will do anything remotely reasonable.



来源:https://stackoverflow.com/questions/49140513/how-to-keep-track-of-keywords-passed-to-metaclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!