docstring.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. # -*- coding: utf-8 -*-
  2. def docstring_property(class_doc):
  3. """Property attribute for docstrings.
  4. Took from: https://gist.github.com/bfroehle/4041015
  5. >>> class A(object):
  6. ... '''Main docstring'''
  7. ... def __init__(self, x):
  8. ... self.x = x
  9. ... @docstring_property(__doc__)
  10. ... def __doc__(self):
  11. ... return "My value of x is %s." % self.x
  12. >>> A.__doc__
  13. 'Main docstring'
  14. >>> a = A(10)
  15. >>> a.__doc__
  16. 'My value of x is 10.'
  17. """
  18. def wrapper(fget):
  19. return DocstringProperty(class_doc, fget)
  20. return wrapper
  21. class DocstringProperty(object):
  22. """Property for the `__doc__` attribute.
  23. Different than `property` in the following two ways:
  24. * When the attribute is accessed from the main class, it returns the value
  25. of `class_doc`, *not* the property itself. This is necessary so Sphinx
  26. and other documentation tools can access the class docstring.
  27. * Only supports getting the attribute; setting and deleting raise an
  28. `AttributeError`.
  29. """
  30. def __init__(self, class_doc, fget):
  31. self.class_doc = class_doc
  32. self.fget = fget
  33. def __get__(self, obj, type=None):
  34. if obj is None:
  35. return self.class_doc
  36. else:
  37. return self.fget(obj)
  38. def __set__(self, obj, value):
  39. raise AttributeError("can't set attribute")
  40. def __delete__(self, obj):
  41. raise AttributeError("can't delete attribute")