Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #7387

Re: how to inherit docstrings?

References <BANLkTin3FGoxwvH2VDOb4OhAWi2Ea3K-pA@mail.gmail.com> <4DF1FA8B.2020609@tim.thechases.com> <BANLkTikqr1s0OVV15Pi4Gz4KPJxtHVASfA@mail.gmail.com>
From Ian Kelly <ian.g.kelly@gmail.com>
Date 2011-06-10 11:26 -0600
Subject Re: how to inherit docstrings?
Newsgroups comp.lang.python
Message-ID <mailman.88.1307726821.11593.python-list@python.org> (permalink)

Show all headers | View raw


On Fri, Jun 10, 2011 at 10:55 AM, Eric Snow <ericsnowcurrently@gmail.com> wrote:
> The only problem, as seen in the last line, is that the __doc__ on
> instances is not inherited on instances of the class.  Object
> attribute lookup only looks to the type's __dict__ for inheritance,
> and not the types's type.  However, that should not be that hard to
> work around.

Everybody always focuses so much on properties and forgets that you
can also just write your own descriptors.

>>> class DocDescriptor(object):
...   def __get__(self, instance, owner):
...     return getattr(owner, "_mydoc", None)
...
>>> class Meta(type):
...   def __init__(cls, name, bases, d):
...     super(Meta, cls).__init__(name, bases, d)
...     cls.__doc__ = DocDescriptor()
...
>>> class X(object):
...   __metaclass__ = Meta
...
>>> X.__doc__
>>> X().__doc__
>>> X._mydoc = 'test'
>>> X.__doc__
'test'
>>> X().__doc__
'test'
>>> class Derived(X): pass
...
>>> Derived.__doc__
'test'
>>> Derived().__doc__
'test'

There you go, a metaclass that adds a __doc__ descriptor that can be
inherited (thanks to the metaclass), can be accessed from either the
class or the instance (thanks to the descriptor), and can easily be
modified to generate the doc string dynamically at call-time if
desired.

Cheers,
Ian

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: how to inherit docstrings? Ian Kelly <ian.g.kelly@gmail.com> - 2011-06-10 11:26 -0600

csiph-web