Let's start with this:
class Example(object):
change_docstring = True
@add_to_docstring(" (additional content!)")
def example_method(self):
"""Example docstring."""
pass
What I am trying to do is allow the @add_to_docstring
decorator to append its parameter string to the docstring of the method only if the change_docstring
attribute is True
. I do not want to pass anything else into the decorator.
This solution works, but it is not exactly what I'm looking for.
def add_to_docstring(text):
def decorator(original_method):
def wrapper(self):
"""wrapper docstring."""
wrapper.__doc__ = original_method.__doc__
if self.change_docstring:
wrapper.__doc__ += text
return original_method(self)
return wrapper
return decorator
Let me explain.
The above solution only changes the docstring if example_method
is executed. The docstring does not change when the class, method, etc. is loaded.
>>> Example.example_method.__doc__
"wrapper docstring."
>>>
>>> Example().example_method()
>>> Example.example_method.__doc__
"Example docstring. (additional content!)"
This is what I would like the output of the above command to be:
>>> Example.example_method.__doc__
"Example docstring. (additional content!)"
Again, I do not want to pass anything else into the decorator.
Update
For additional clarification, this is to allow for a decorator to change the docstring of a method, and to have that change be reflected in Sphinx generated documentation. Sphinx loads everything and gathers docstrings, but it does not do anything more.
Based on the selected solution, I added a module variable in the decorators module and exposed a method to disable the docstring change feature in the decorators. In order to disable the feature universally, I then called that disable function within my Sphinx conf.py
files like so:
# import the decorators module
from some_modules import decorators
# disable the docstring change feature
decorators.disable_docstring_change()
Then the decorator can be used on any method in the project and the docstring changes will be either enabled or disabled.