Skip to content

Instantly share code, notes, and snippets.

@isidentical
Created April 13, 2019 16:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save isidentical/ef529f48e0708cd539340874fbb968e6 to your computer and use it in GitHub Desktop.
Save isidentical/ef529f48e0708cd539340874fbb968e6 to your computer and use it in GitHub Desktop.
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