Get dosctring without import

Peter Otten __peter__ at web.de
Fri Feb 26 05:57:16 EST 2010


Joan Miller wrote:

> When a package is imported, it gets the dosctring to store it in
> *__doc__*.
> 
> Does that funcion is built in python? because I would want use it to
> get the docstring without import a package

Something to get you started:


import ast


def walk(root, stack):
    for node in ast.iter_child_nodes(root):
        if isinstance(node, (ast.FunctionDef, ast.ClassDef)):
            yield node
        stack.append(node)
        for child in walk(node, stack):
            yield child
        del stack[-1]

def get_name(node):
    try:
        return node.name
    except AttributeError:
        return "(%s)" % node.__class__.__name__

def get_path(path):
    return ".".join(get_name(node) for node in path)

def find_docstrings(filename):
    with open(filename) as f:
        module = ast.parse(f.read())
    print filename.center(len(filename) + 2).center(80, "=")
    print ast.get_docstring(module)
    print "=" * 80
    print

    path = []
    for node in walk(module, path):
        s = ast.get_docstring(node)
        if s is not None:
            name = get_path(path + [node])
            print name.center(len(name) + 2).center(80, "-")
            print s
            print


if __name__ == "__main__":
    import sys
    args = sys.argv[1:]
    if args:
        for arg in args:
            find_docstrings(arg)
    else:
        find_docstrings("/usr/lib/python2.6/unittest.py")
        assert "unittest" not in sys.modules

To get an idea of the differences to the import-based approach try analysing 
the following script:

import random

if random.choice([True, False]):
    def f():
        "say hello"
else:
    def f():
        "kill a kitten"

def g():
    "whatever"
del g

Peter



More information about the Python-list mailing list