Skip to content

Instantly share code, notes, and snippets.

@d1manson
Created March 5, 2015 17:01
Show Gist options
  • Save d1manson/636e173487cad2e23fc5 to your computer and use it in GitHub Desktop.
Save d1manson/636e173487cad2e23fc5 to your computer and use it in GitHub Desktop.
decorator for appending docstring of one or more objects to a function
import inspect
def append_docstring(*others):
"""
Appends one or more other objects' docstrings to the decorated function.
Title, location and args info is provided in addition to basic docstring.
TODO: Compare the location of `other` to `foo` and only show the
neccessary suffix. Also, try and get the args/kwargs and
type printed nicely like spyder does.
"""
def decorator(foo):
foo_doc = inspect.getdoc(foo)
if foo_doc is None:
foo_doc = "[no docstring]"
for other in others:
other_loc = inspect.getfile(other)
other_doc = inspect.getdoc(other)
if other_doc is None:
other_doc = "[no docstring]"
try:
other_argspec = inspect.formatargspec(*inspect.getargspec(other))
other_argspec = other_argspec[1:-1] # remove parens
if other_argspec.startswith('self, '):
other_argspec = other_argspec[len('self, '):]
other_argspec = "Arguments: ``" + other_argspec + "``\n\n"
except:
other_argspec = ""
foo_doc += "\n\n" + \
"Related: " + other.__name__ + "\n========\n\n"+ \
"Location: ``" + other_loc + "``\n\n" + other_argspec + \
other_doc
foo.__doc__ = foo_doc
return foo
return decorator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment