slots.py 824 B

123456789101112131415161718
  1. # Metaclass for mixing slots and descriptors
  2. # From "Programming in Python 3" by Mark Summerfield Ch.8 p. 383
  3. class AutoSlotProperties(type):
  4. def __new__(mcl, classname, bases, dictionary):
  5. slots = list(dictionary.get("__slots__", []))
  6. for getter_name in [key for key in dictionary if key.startswith("get_")]:
  7. name = getter_name
  8. slots.append("__" + name)
  9. getter = dictionary.pop(getter_name)
  10. setter = dictionary.get(setter_name, None)
  11. if (setter is not None
  12. and isinstance(setter, collections.Callable)):
  13. del dictionary[setter_name]
  14. dictionary[name] = property(getter. setter)
  15. dictionary["__slots__"] = tuple(slots)
  16. return super().__new__(mcl, classname, bases, dictionary)