[Python-ideas] Dynamic getting of __doc__ of a function

Chris Angelico rosuav at gmail.com
Sun Oct 7 11:26:06 EDT 2018


On Mon, Oct 8, 2018 at 2:14 AM Steven D'Aprano <steve at pearwood.info> wrote:
> That might work for Marko's use-case, but the problem is more general
> and I'd like to consider the broader picture. Currently instance __doc__
> attributes are sometimes ignored by help(). Given these:
>
> py> class X:
> ...     pass
> ...
> py> a = X()
> py> b = X()
> py> a.__doc__ = "Hello"
> py> b.__doc__ = "Goodbye"
>
> I would expect to see the per-instance docstrings, but in 3.6 at least,
> help(a) and help(b) both give the unhelpful:
>
>
> Help on X in module __main__ object:

Each of them is actually giving help(X). So having that respect *any*
per-instance information first means changing it so help(inst) is
different from help(cls).

> As per my earlier post, making the docstrings a property fails from
> help(). So I think there's some improvement here:
>
> - fix help() so it picks up per-instance docstrings, not just the
>   class docstring;
>
> - including the case where the docstring is a property.

Which are really the same thing - having help() care about the actual
instance, not the type.

Currently, it works if you put a property on the metaclass:

>>> class mX(type):
...  @property
...  def __doc__(self):
...   return "Docstring"
...
>>> class X(metaclass=mX): pass
...
>>> help(X())
class X(builtins.object)
 |  Docstring
 |  ...

Maybe what we really need here is a convenient way to create class properties.

class X:
    @classproperty
    def __doc__(cls):
        return "Docstring"

I know this has been discussed before, though I can't find a
discussion thread right now.

ChrisA


More information about the Python-ideas mailing list