Peter Otten added the comment: Here's a variant that builds on your code, but makes for a nicer API. Single-line docstrings can be passed along with the attribute name, and with namedtuple.with_docstrings(... all info required to build the class ...) from a user perspective the factory looks like a class method:
from functools import partial from collections import namedtuple def _with_docstrings(cls, typename, field_names_with_doc, *, verbose=False, rename=False, doc=None): field_names = [] field_docs = [] if isinstance(field_names_with_doc, str): field_names_with_doc = [ line for line in field_names_with_doc.splitlines() if line.strip()] for item in field_names_with_doc: if isinstance(item, str): item = item.split(None, 1) if len(item) == 1: [fieldname] = item fielddoc = None else: fieldname, fielddoc = item field_names.append(fieldname) field_docs.append(fielddoc) nt = cls(typename, field_names, verbose=verbose, rename=rename) for fieldname, fielddoc in zip(field_names, field_docs): if fielddoc is not None: new_property = property(getattr(nt, fieldname), doc=fielddoc) setattr(nt, fieldname, new_property) if doc is not None: nt.__doc__ = doc return nt namedtuple.with_docstrings = partial(_with_docstrings, namedtuple) if __name__ == "__main__": Point = namedtuple.with_docstrings("Point", "x abscissa\ny ordinate") Address = namedtuple.with_docstrings( "Address", """ name Surname first_name First name city email Email address """) Whatever = namedtuple.with_docstrings( "Whatever", [("foo", "doc for\n foo"), ("bar", "doc for bar"), "baz"], doc="""The Whatever class. Example for a namedtuple with multiline docstrings for its attributes.""") ---------- nosy: +peter.otten _______________________________________ Python tracker <rep...@bugs.python.org> <http://bugs.python.org/issue16669> _______________________________________ _______________________________________________ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com