This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author peter.otten
Recipients Ankur.Ankan, eric.snow, giampaolo.rodola, gvanrossum, nedbat, pconnell, peter.otten, rhettinger, serhiy.storchaka, terry.reedy
Date 2015-04-27.10:00:17
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1430128817.73.0.903929164101.issue16669@psf.upfronthosting.co.za>
In-reply-to
Content
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.""")
History
Date User Action Args
2015-04-27 10:00:17peter.ottensetrecipients: + peter.otten, gvanrossum, rhettinger, terry.reedy, giampaolo.rodola, nedbat, eric.snow, serhiy.storchaka, pconnell, Ankur.Ankan
2015-04-27 10:00:17peter.ottensetmessageid: <1430128817.73.0.903929164101.issue16669@psf.upfronthosting.co.za>
2015-04-27 10:00:17peter.ottenlinkissue16669 messages
2015-04-27 10:00:17peter.ottencreate