docstring.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import inspect
  2. from matplotlib import cbook
  3. class Substitution:
  4. """
  5. A decorator that performs %-substitution on an object's docstring.
  6. This decorator should be robust even if ``obj.__doc__`` is None (for
  7. example, if -OO was passed to the interpreter).
  8. Usage: construct a docstring.Substitution with a sequence or dictionary
  9. suitable for performing substitution; then decorate a suitable function
  10. with the constructed object, e.g.::
  11. sub_author_name = Substitution(author='Jason')
  12. @sub_author_name
  13. def some_function(x):
  14. "%(author)s wrote this function"
  15. # note that some_function.__doc__ is now "Jason wrote this function"
  16. One can also use positional arguments::
  17. sub_first_last_names = Substitution('Edgar Allen', 'Poe')
  18. @sub_first_last_names
  19. def some_function(x):
  20. "%s %s wrote the Raven"
  21. """
  22. def __init__(self, *args, **kwargs):
  23. if args and kwargs:
  24. raise TypeError("Only positional or keyword args are allowed")
  25. self.params = args or kwargs
  26. def __call__(self, func):
  27. if func.__doc__:
  28. func.__doc__ %= self.params
  29. return func
  30. def update(self, *args, **kwargs):
  31. """
  32. Update ``self.params`` (which must be a dict) with the supplied args.
  33. """
  34. self.params.update(*args, **kwargs)
  35. @classmethod
  36. @cbook.deprecated("3.3", alternative="assign to the params attribute")
  37. def from_params(cls, params):
  38. """
  39. In the case where the params is a mutable sequence (list or
  40. dictionary) and it may change before this class is called, one may
  41. explicitly use a reference to the params rather than using *args or
  42. **kwargs which will copy the values and not reference them.
  43. """
  44. result = cls()
  45. result.params = params
  46. return result
  47. def copy(source):
  48. """Copy a docstring from another source function (if present)."""
  49. def do_copy(target):
  50. if source.__doc__:
  51. target.__doc__ = source.__doc__
  52. return target
  53. return do_copy
  54. # Create a decorator that will house the various docstring snippets reused
  55. # throughout Matplotlib.
  56. interpd = Substitution()
  57. def dedent_interpd(func):
  58. """Dedent *func*'s docstring, then interpolate it with ``interpd``."""
  59. func.__doc__ = inspect.getdoc(func)
  60. return interpd(func)