docstring.py 1.4 KB

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