Nishant
Nishant

Reputation: 21934

How to convert a Python file docstring's to HTML

Is there a simple way to convert a .py to an HTML by displaying its function API's and docstring's? I read up on Sphinx - but that seems to be for a big project. I am just trying to find a way to create an HTML from a .py file with just its function definition and docstring.

Upvotes: 2

Views: 3173

Answers (2)

Igonato
Igonato

Reputation: 10806

You can do it without any tools. First you need to get data. Here is very basic example:

"""My module"""

def foo():
    """Some function"""
    pass

def bar():
    """Another function"""
    pass

class Spam(object):
    """Some object"""
    pass

if __name__ == '__main__':
    import types

    defs = set(locals().keys()).difference(set(__builtins__.keys())) 

    if __doc__:
        print 'Module:'
        print __doc__, '\n'

    for name in defs:
        object_ = locals()[name]
        if type(object_) is types.FunctionType:
            print "Function %s:" % object_.__name__
            print object_.__doc__, '\n'
        elif type(object_) is type:
            print "Class %s:" % object_.__name__
            print object_.__doc__, '\n'

And output will be:

Module:
My module 

Function bar:
Another function 

Class Spam:
Some object 

Function foo:
Some function 

To get html you can use a template engine, for example Mako. Make a template and pass data from __doc__ to it and that should do the job.

EDIT: Here is way to get signature from a function:

>>> def foo(spam, eggs):
...     bar = spam + eggs
...     return bar
>>> varnames = foo.func_code.co_varnames
>>> argcount = foo.func_code.co_argcount
>>> '%s(%s)' % (foo.__name__, ', '.join(varnames[:argcount]))
0: 'foo(spam, eggs)'

Upvotes: 2

Mp0int
Mp0int

Reputation: 18737

My hand written api documentation handler do something like that.

import inspect
inspect.getmembers(MyClass, predicate=inspect.ismethod)

will return you a list of all available methods. First objest is the string representation of the method name, so you can use simple filter functions to filter out some of them. My api filters out methods started with _ (which are inner methods and must not be reachable from api) like

    filter(lambda x: not x.startswith('_'), [x[0] for x in inspect.getmembers(MyClass, predicate=inspect.ismethod)])

Second object is instance method of related method. you can use it to call __doc__ to get docstring or any other method you can call with a method instance

for item in inspect.getmembers(MyClass, predicate=inspect.ismethod):
    print item[0]
    print item[1].__doc__

Upvotes: 1

Related Questions