const.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435
  1. """
  2. Copyright (C) 2013-2014 Eygene A. Ryabinkin and contributors
  3. Collection of classes that implement const-like behaviour
  4. for various objects.
  5. """
  6. import copy
  7. class ConstProxy:
  8. """Implements read-only access to a given object
  9. that can be attached to each instance only once."""
  10. def __init__(self):
  11. self.__dict__['__source'] = None
  12. def __getattr__(self, name):
  13. src = self.__dict__['__source']
  14. if src is None:
  15. raise ValueError("using non-initialized ConstProxy() object")
  16. return copy.deepcopy(getattr(src, name))
  17. def __setattr__(self, name, value):
  18. raise AttributeError("tried to set '%s' to '%s' for constant object" %
  19. (name, value))
  20. def __delattr__(self, name):
  21. raise RuntimeError("tried to delete field '%s' from constant object" %
  22. name)
  23. def set_source(self, source):
  24. """ Sets source object for this instance. """
  25. if self.__dict__['__source'] is not None:
  26. raise ValueError("source object is already set")
  27. self.__dict__['__source'] = source