Imagine you have the following code:
class A:
pass
NewA = ... # copy A
NewA.__init__ = decorator(A.__init__) # but don't change A's init function, just NewA's
I am looking for a way to change some of the attributes/methods in the cloned class and the rest I want them to be similar to the base class object (preferebly even through MappingProxyType so that when A changes the unchanged logic of NewA reflects the changes as well).
I came across this ancient thread, where there some suggetions which don't fully work:
- Repurposing inheritance
class NewA(A): passwhich doesn't exactly result in what I am looking for - Dynamically generating a new class using
typeand somehow having an eye out for the tons of cases that might happen (having mutable attributes/descriptors/calls to globals ...) - Using
copy.deepcopywhich is totally wrong (since class object's internal data representation is a MappingProxyType which we cannot copy/deepcopy)
Is there a way to still achive this without manually handling every corner case, especially considering the fact that the base class we intend to copy could be anything (with metaclasses and custom init_subclass parents, and a mixture of attributes mutable and what not, and potentially with __slots__)?
Here is a humble attempt to get you started. I've tested it out with a class with slots and it seems to work. I am not very sure about that aspect of it though.
Now, this seems to work with classes that have
__slots__. The one thing that might trip things up is if the metaclass has slots (which must be empty). But that would be really weird.Here is a test script:
This prints: