How to track keywords passed to metaclass?

I have a metaclass that takes 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 

leads to object A and 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, there are no keywords. This is especially a problem when type(cls) requires additional arguments or otherwise creates different side effects when they are not there.

I know that I can have M put keywords in a class object somewhere, but this is not a very good solution, because then my copy method is very dependent on the class.

Is there a built-in way to get the keywords that the class created in Python?

0
source share
1 answer

Python will not save keyword arguments for you. It is easy 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 that the basic idea of ​​trying to copy a class like this makes sense. There is no guarantee that the __dict__ class looks about the same as the one that was originally passed to the metaclass constructor, or that calling the metaclass constructor again will do something reasonably.

+1
source

Source: https://habr.com/ru/post/1275766/


All Articles