_docstring.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. import inspect
  2. from . import _api
  3. def kwarg_doc(text):
  4. """
  5. Decorator for defining the kwdoc documentation of artist properties.
  6. This decorator can be applied to artist property setter methods.
  7. The given text is stored in a private attribute ``_kwarg_doc`` on
  8. the method. It is used to overwrite auto-generated documentation
  9. in the *kwdoc list* for artists. The kwdoc list is used to document
  10. ``**kwargs`` when they are properties of an artist. See e.g. the
  11. ``**kwargs`` section in `.Axes.text`.
  12. The text should contain the supported types, as well as the default
  13. value if applicable, e.g.:
  14. @_docstring.kwarg_doc("bool, default: :rc:`text.usetex`")
  15. def set_usetex(self, usetex):
  16. See Also
  17. --------
  18. matplotlib.artist.kwdoc
  19. """
  20. def decorator(func):
  21. func._kwarg_doc = text
  22. return func
  23. return decorator
  24. class Substitution:
  25. """
  26. A decorator that performs %-substitution on an object's docstring.
  27. This decorator should be robust even if ``obj.__doc__`` is None (for
  28. example, if -OO was passed to the interpreter).
  29. Usage: construct a docstring.Substitution with a sequence or dictionary
  30. suitable for performing substitution; then decorate a suitable function
  31. with the constructed object, e.g.::
  32. sub_author_name = Substitution(author='Jason')
  33. @sub_author_name
  34. def some_function(x):
  35. "%(author)s wrote this function"
  36. # note that some_function.__doc__ is now "Jason wrote this function"
  37. One can also use positional arguments::
  38. sub_first_last_names = Substitution('Edgar Allen', 'Poe')
  39. @sub_first_last_names
  40. def some_function(x):
  41. "%s %s wrote the Raven"
  42. """
  43. def __init__(self, *args, **kwargs):
  44. if args and kwargs:
  45. raise TypeError("Only positional or keyword args are allowed")
  46. self.params = args or kwargs
  47. def __call__(self, func):
  48. if func.__doc__:
  49. func.__doc__ = inspect.cleandoc(func.__doc__) % self.params
  50. return func
  51. class _ArtistKwdocLoader(dict):
  52. def __missing__(self, key):
  53. if not key.endswith(":kwdoc"):
  54. raise KeyError(key)
  55. name = key[:-len(":kwdoc")]
  56. from matplotlib.artist import Artist, kwdoc
  57. try:
  58. cls, = (cls for cls in _api.recursive_subclasses(Artist)
  59. if cls.__name__ == name)
  60. except ValueError as e:
  61. raise KeyError(key) from e
  62. return self.setdefault(key, kwdoc(cls))
  63. class _ArtistPropertiesSubstitution:
  64. """
  65. A class to substitute formatted placeholders in docstrings.
  66. This is realized in a single instance ``_docstring.interpd``.
  67. Use `~._ArtistPropertiesSubstition.register` to define placeholders and
  68. their substitution, e.g. ``_docstring.interpd.register(name="some value")``.
  69. Use this as a decorator to apply the substitution::
  70. @_docstring.interpd
  71. def some_func():
  72. '''Replace %(name)s.'''
  73. Decorating a class triggers substitution both on the class docstring and
  74. on the class' ``__init__`` docstring (which is a commonly required
  75. pattern for Artist subclasses).
  76. Substitutions of the form ``%(classname:kwdoc)s`` (ending with the
  77. literal ":kwdoc" suffix) trigger lookup of an Artist subclass with the
  78. given *classname*, and are substituted with the `.kwdoc` of that class.
  79. """
  80. def __init__(self):
  81. self.params = _ArtistKwdocLoader()
  82. def register(self, **kwargs):
  83. """
  84. Register substitutions.
  85. ``_docstring.interpd.register(name="some value")`` makes "name" available
  86. as a named parameter that will be replaced by "some value".
  87. """
  88. self.params.update(**kwargs)
  89. def __call__(self, obj):
  90. if obj.__doc__:
  91. obj.__doc__ = inspect.cleandoc(obj.__doc__) % self.params
  92. if isinstance(obj, type) and obj.__init__ != object.__init__:
  93. self(obj.__init__)
  94. return obj
  95. def copy(source):
  96. """Copy a docstring from another source function (if present)."""
  97. def do_copy(target):
  98. if source.__doc__:
  99. target.__doc__ = source.__doc__
  100. return target
  101. return do_copy
  102. # Create a decorator that will house the various docstring snippets reused
  103. # throughout Matplotlib.
  104. interpd = _ArtistPropertiesSubstitution()