Last active
December 17, 2015 00:38
-
-
Save nathania/5522363 to your computer and use it in GitHub Desktop.
Python decorator (factory function) to add a frequently-used docstring to a function. Existing docstrings are not overwritten.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def add_docstring(*args): # decorator factory function | |
""" | |
Constructs and appends a docstring to the decorated function's existing docstring. | |
When several functions share the same docstring(s), can be used to improve code readability. | |
Also makes life easier should the documentation ever need to be updated. | |
To understand decorators: simeonfranklin.com/blog/2012/jul/1/python-decorators-in-12-steps/ | |
'join' a list of strings ('+' building is quadratic time): memonic.com/user/pneff/folder/python/id/1bufp | |
""" | |
from os import linesep | |
appended_docstring = [] # docstring_decorator can access variables local to its enclosing scope | |
# even when executed outside of that scope (http://tinyurl.com/anacc9n) | |
if 'return_double' in args: | |
appended_docstring.append('@return: (x, y)') | |
elif 'return_triple' in args: | |
appended_docstring.append('@return: (x, y, z)') | |
if 'raise_TypeError' in args: | |
appended_docstring.extend([linesep, '@raise TypeError: DFT_dim must be an integer']) | |
appended_docstring = appended_docstring.strip() | |
def docstring_decorator(func): # actual decorator; its only argument is the decorated function | |
existing_docstring = [func.__doc__.strip(), linesep, linesep] if func.__doc__ else [] | |
func.__doc__ = ' '.join(existing_docstring.extend(appended_docstring)) | |
return func | |
return docstring_decorator # @add_docstring(*args) evaluates to the appropriate @docstring_decorator | |
@add_docstring('return_double') | |
def update_coords(*args, **kwargs): | |
# do stuff | |
return (x, y) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment