Best way to do attribute docstrings?

Ken Kuhlman kskuhlman at gmail.com
Fri Sep 7 22:06:07 CEST 2007


What's the best method for annotating attributes with a docstring?
I'm looking to be able to introspect my class & get the comments back
out.

The technique I'm using is a little hoaky, but works.. basically I
create subclasses of the builtin types that I want to be able to use &
then instantiate them in my attribute assignments.   This gives me an
object that I can tweak the __doc__ attribute on.   An example of what
my code looks like is included below.

I saw that PEP 224 [1] was trying to meet this need, but got rejected
because the proposed syntax wasn't clear enough.

Thanks!
-Ken

[1] http://www.python.org/dev/peps/pep-0224/


attr_doc.py::

# Subclass str so we can modify instance's attributes (like __doc__)
class _(str): pass

# Boolean gave me extra fits that I don't understand, but this
technique works
class MyBool(int):
    def __str__(self):
        return `self.__int__() > 0`
    def __repr__(self):
        return self.__str__()

def bool_func(val):
    def blah():
       return MyBool(val)
    return blah
true = bool_func(True)
false = bool_func(False)


class Animal(object):
    four_legs = true()
    four_legs.__doc__ = "Animal has four legs"

    favorite_food = _('cheese')
    favorite_food.__doc__ = "Animal's favorite food"

    has_fur = true()
    has_fur.__doc__ = "Animal has fur"

print Animal.four_legs.__doc__, '::', Animal.four_legs
print Animal.favorite_food.__doc__, '::', Animal.favorite_food
print Animal.has_fur.__doc__, '::', Animal.has_fur

------
This gives the expected results:

Animal has four legs :: True
Animal's favorite food :: cheese
Animal has fur :: True




More information about the Python-list mailing list