Ian Bicking: the old part of his blog

Dynamic __doc__

One thing I did in the last (0.4) release of FormEncode is add some dynamic docstrings. I've started relying more heavily on automatically-generated documentation, but there was information specific to validators that I wanted to include without the tedium or redundancy of copying it into the docstring. In particular, I wanted to display information about all of the error messages a validator can produce.

Since I was already using a __classinit__ metaclass it was easy to add code that gets run for every subclass of Validator. And I just did something like this (to paraphrase):

def __classinit__(cls, new_attrs):
    ...
    for name, value in cls._messages.items():
        cls.__doc__ += '\n``%s``: %s' % (name, value)

Before I had been thinking about putting all sorts of cleverness into the documentation generation system so it could detect these attributes, but this is much better all around, and simpler to boot. Of course, it would be nice to have indexes and whatnot, but ultimately I think those would be better implemented in the underlying documentation system (restructured text moreso than Pudge), and maybe I could just add a special role to the text.

Anyway, it made me feel clever so I thought I'd share.

Created 22 Nov '05

Comments:

That might be an interesting place to park some information. Consider testing, when you may want remember the number of times a function was called, without cluttering up the standard output. Hmm....

# Chris

Oh, ew, don't go adding programmatic meaningfulness to doc comments :-).

If you want to store that kind of info, why not just stick it in another attribute on the function (or other callable) object?

# Nathaniel Smith

That's nice. If you don't mind, I'll use this example in my upcoming "Agile documentation" talk at PyCon.

# Grig Gheorghiu

Cool!

# Ori Peleg