Created
April 13, 2019 16:16
-
-
Save isidentical/ef529f48e0708cd539340874fbb968e6 to your computer and use it in GitHub Desktop.
This file contains 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 collections.abc | |
MUTABLE_TYPES = tuple( | |
filter( | |
lambda item: isinstance(item, type) and item.__name__.startswith("Mutable"), | |
collections.abc.__dict__.values(), | |
) | |
) | |
class Parent: | |
items = [] | |
test = {} | |
def __init_subclass__(cls): | |
mutable_attrs = filter( | |
lambda attr: not attr[0].startswith("__") and isinstance(attr[1], MUTABLE_TYPES), | |
vars(Parent).items() | |
) | |
for attr, _ in mutable_attrs: | |
setattr(cls, attr, getattr(Parent, attr).copy()) | |
class Child(Parent): | |
pass | |
Parent.items.append(1) | |
Child.items.append(2) | |
assert Parent.items == [1] | |
assert Child.items == [2] | |
assert Child.items is not Parent.items | |
assert Child.test is not Parent.test |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment