Docstrings and class Attributes

Steven D'Aprano steve+comp.lang.python at
Mon Aug 8 20:32:18 CEST 2011

Nick wrote:

> Is it possible to put a doc string on a class attribute? Something
> like this
> class Test (object):
>     '''classx'''
>     fred = 10
>     '''attribute'''

The short answer is, no.

The longer answer is, maybe, if you can make Test.fred be some sort of
object with a docstring:

class MyInt(int):

class Test(object):
    fred = MyInt(10)

>>> Test.fred.__doc__

But the hard part is ensuring that Test.fred doesn't get replaced:

>>> Test.fred = 11
>>> Test.fred.__doc__
'int(x[, base]) -> integer\n\nConvert a string or number ...'

Not impossible to solve, but an awful lot of trouble for very little
benefit. Just put your documentation in the class, where people expect to
find it:

class Test(object):

    Test.fred is an attribute.
    fred = 10


More information about the Python-list mailing list