You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

35 lines
1.0 KiB

4 years ago
  1. cdef class reify:
  2. """Use as a class method decorator. It operates almost exactly like
  3. the Python `@property` decorator, but it puts the result of the
  4. method it decorates into the instance dict after the first call,
  5. effectively replacing the function it decorates with an instance
  6. variable. It is, in Python parlance, a data descriptor.
  7. """
  8. cdef object wrapped
  9. cdef object name
  10. def __init__(self, wrapped):
  11. self.wrapped = wrapped
  12. self.name = wrapped.__name__
  13. @property
  14. def __doc__(self):
  15. return self.wrapped.__doc__
  16. def __get__(self, inst, owner):
  17. try:
  18. try:
  19. return inst._cache[self.name]
  20. except KeyError:
  21. val = self.wrapped(inst)
  22. inst._cache[self.name] = val
  23. return val
  24. except AttributeError:
  25. if inst is None:
  26. return self
  27. raise
  28. def __set__(self, inst, value):
  29. raise AttributeError("reified property is read-only")