Created
February 16, 2023 10:49
-
-
Save juanarrivillaga/e6df50853ae5d94764d392edc215c578 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import types | |
import copy | |
def clone_class(klass): | |
def _exec_body(ns): | |
ns_no_slots = { | |
k:v for k,v in vars(klass).items() | |
if not isinstance(v, types.MemberDescriptorType) | |
} | |
ns |= copy.deepcopy(ns_no_slots) | |
return ns | |
return types.new_class( | |
name=klass.__name__, | |
bases=klass.__bases__, | |
kwds={"metaclass": type(klass)}, | |
exec_body=_exec_body, | |
) | |
if __name__ == "__main__: | |
class Meta(type): | |
def meta_magic(cls): | |
print("magical!") | |
class Foo(metaclass=Meta): | |
__slots__ = ('x','y') | |
@property | |
def size(self): | |
return 42 | |
class Bar(Foo): | |
state = [] | |
__slots__ = ('z',) | |
def __init__(self, x=1, y=2, z=3): | |
self.x = x | |
self.y = y | |
self.z = z | |
@property | |
def closed(self): | |
return False | |
BarClone = clone_class(Bar) | |
bar = BarClone() | |
BarClone.state.append('foo') | |
print(BarClone.state, Bar.state) | |
BarClone.meta_magic() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment