2

I know it is possible to add docstring for namedtuples by subclassing it, e.g.

from collections import namedtuple
NT = namedtuple('NT', ['f1', 'f2', 'f3'])
class NTWithDoc(NT):
    """ DOCSTRING """
    __slots__ = ()

Now I wish to add docstring for f1, f2, and f3. Is there a way of doing that? Our company is using Python2, don't think people will let me use 3.

xis
  • 24,330
  • 9
  • 43
  • 59

1 Answers1

2

I'm not sure if there is a good way to do this on python2.x. On python3.x, you can swap out the __doc__ directly:

$ python3
Python 3.6.0a2 (v3.6.0a2:378893423552, Jun 13 2016, 14:44:21) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from collections import namedtuple
>>> NT = namedtuple('NT', ['f1', 'f2', 'f3'])
>>> NT.f1.__doc__
'Alias for field number 0'
>>> NT.f1.__doc__ = 'Hello'

Unfortunately, python2.x gives you an error at this point:

>>> NT.f1.__doc__ = 'Hello World.'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: readonly attribute

On python2.x, you can get it by re-defining all of the properties:

>>> from collections import namedtuple
>>> NT = namedtuple('NT', ['f1', 'f2', 'f3'])
>>> class NTWithDoc(NT):
...     """docstring."""
...     __slots__ = ()
...     f1 = property(NT.f1.fget, None, None, 'docstring!')
... 
>>> help(NTWithDoc)

>>> a = NTWithDoc(1, 2, 3)
>>> a.f1
1

But this feels like a lot of trouble to go to get the docstrings :-).

mgilson
  • 300,191
  • 65
  • 633
  • 696