Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2019
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.98 KB | None | 0 0
  1. import collections.abc
  2. from itertools import chain
  3.  
  4. MUTABLE_TYPES = tuple(
  5. filter(
  6. lambda item: isinstance(item, type) and item.__name__.startswith("Mutable"),
  7. collections.abc.__dict__.values(),
  8. )
  9. )
  10.  
  11.  
  12. class ClassAttributeFactory(type):
  13. def __prepare__(name, bases, **factory):
  14. if bases:
  15. mutable_attrs = chain.from_iterable(
  16. filter(
  17. lambda attr: not attr[0].startswith("__")
  18. and isinstance(attr[1], MUTABLE_TYPES),
  19. vars(base).items(),
  20. )
  21. for base in bases
  22. )
  23. return {attr: value.copy() for attr, value in mutable_attrs}
  24.  
  25. return {}
  26.  
  27.  
  28. class Parent(metaclass=ClassAttributeFactory):
  29. items = []
  30. test = {}
  31.  
  32.  
  33. class Child(Parent):
  34. pass
  35.  
  36.  
  37. Parent.items.append(1)
  38. Child.items.append(2)
  39. assert Parent.items == [1]
  40. assert Child.items == [2]
  41. assert Child.items is not Parent.items
  42. assert Child.test is not Parent.test
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement