Steven Bethard wrote: > class C(object): > def foo(self): > """Foo things""" > ... > > class D(object): > def foo(self): > """Foo things""" > ... > > It bothers me that I'm basically writing the same docstrings multiple > times. I guess what I really want to do is just write the docstrings > for the interface I'm describing, and only supply docstrings in the > classes when they need to differ from the interface docstrings. > > Is there a good way to do this? If it's necessary, I can have C and D > inherit from another class...
Use a common interface type and a metaclass which copies method docstrings from base classes: ------------------------------------------------------------------------------ #!/usr/bin/env python import inspect class DocstringMetaclass(type): """Copy method docstrings.""" def __init__(cls, *args): super(DocstringMetaclass, cls).__init__(*args) for name, method in cls.__dict__.iteritems(): # method is a function, not a method, so we use isfunction(). if not inspect.isfunction(method) or method.__doc__ is not None: continue for c in cls.mro(): if hasattr(c, name): m = getattr(c, name) if inspect.ismethod(m) and m.__doc__ is not None: method.__doc__ = m.__doc__ break class Interface(object): __metaclass__ = DocstringMetaclass def foo(self): """Foo things""" def bar(self): """Bar things""" def baz(self): """Baz things in a C manner""" class Implementation(Interface): def foo(self): pass def bar(self): pass def baz(self): pass print Implementation.foo.__doc__ print Implementation.bar.__doc__ print Implementation.baz.__doc__ ------------------------------------------------------------------------------ Output: Foo things Bar things Baz things in a C manner -- Felix Wiemann -- http://www.ososo.de/ -- http://mail.python.org/mailman/listinfo/python-list