I have several modules that are within a Python package:
# my_package contents
__init__.py
module1.py
module2.py
Within my __init__.py, I’m importing these modules so that they will be accessible once the package is imported by my users.
# __init__.py
import module1
import module2
My question is: how do I programatically access the docstrings for each of my defined functions within each of these modules? I’ve seen others use a form of this:
getattr(module, key). __doc__
but I can’t get it to work for me. Any ideas?
EDIT: A little more background… we’re trying to extract content (one of the important things is the docstrings) from our python packages with the intent of using that as content for documentation. My boss has something already set up that we’re trying to feed into.
Ideally, I’d like to have a package.module.function docstring result
EDIT2: Here’s what is currently not working:
#my package is named 'tpp'
import tpp
for script in dir(tpp):
if not "__" in script: #not a builtin...
docstrings1 = getattr( tpp, script).__doc__
docstrings2 = " ".join(docstrings1.split())#clean out any newline chars
print script, docstrings
EDIT3: To get a picture of where the docstrings are and how we’ve organized things:
import inspect
import tpp
inspect.getdoc(tpp)
#returns None
inspect.getdoc(tpp.module1)
#returns None
inspect.getdoc(tpp.module1.function1)
#'DOCSTRING TEXT FOUND!'
**Ultimately, I’d like to get a list like [‘module1’, ‘function1’, ‘DOCSTRING TEXT FOUND!’]
Maybe you want something like this:
but I don’t guarantee that this will get all the docstrings. You may need to recursively go into items that you retrieve with getattr.
Here’s a recursive version (which probably will get way more than you want) and will choke on circular dependencies: