are docstrings for variables a bad idea?

Ziga Seilnacht ziga.seilnacht at gmail.com
Fri Apr 21 10:32:30 EDT 2006


jelle wrote:
> Hi Michele,
>
> Thanks for pointing that out, cool!
>
> I would argue -even- that is too much programming effort.
> Like method docstring, variables docstrings should be effortless to
> write.

I don't know what exactly do you mean with variable docstrings, but
if you just want to add docstrings to instance's data attributes, you
can use something like this:

"""
This module is useful for documenting data attributes. Example:

>>> class C(object):
...     foo = attr('a common attribute in examples')
...     bar = attr('this one has a name for nicer errors', 'bar')
...     baz = attr('and this one has a default value', default=1)
...     def __init__(self, foo=None, bar=None, baz=None):
...         if foo is not None:
...             self.foo = foo
...         if bar is not None:
...             self.bar = bar
...         if baz is not None:
...             self.baz = baz
...
>>> C.foo
attr(doc='a common attribute in examples', name='', default=NoDefault)
>>> C.foo.__doc__
'a common attribute in examples'
>>> C.bar.__doc__
'this one has a name for nicer errors'
>>> C.baz.__doc__
'and this one has a default value'
>>> c = C()
>>> c.foo
Traceback (most recent call last):
  ...
AttributeError: 'C' object has no attribute ''
>>> c.bar
Traceback (most recent call last):
  ...
AttributeError: 'C' object has no attribute 'bar'
>>> c.baz
1
>>> d = C(1, 2, 3)
>>> d.foo
1
>>> d.bar
2
>>> d.baz
3

"""

class Marker(object):

    def __init__(self, representation):
        self.representation = representation

    def __repr__(self):
        return self.representation


_NoDefault = Marker('NoDefault')


class attr(object):

    def __init__(self, doc='', name='', default=_NoDefault):
        self.__doc__ = doc
        self.name = name
        self.default = default

    def __repr__(self):
        s = "attr(doc=%r, name=%r, default=%r)"
        return s % (self.__doc__, self.name, self.default)

    def __get__(self, obj, objtype):
        if obj is None:
            return self
        if self.default is _NoDefault:
            msg = "%r object has no attribute %r"
            raise AttributeError(msg % (objtype.__name__, self.name))
        return self.default


if __name__ == '__main__':
    import doctest
    doctest.testmod()




More information about the Python-list mailing list