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

Steven D'Aprano steve at pearwood.info
Sun Oct 7 11:13:31 EDT 2018

On Mon, Oct 08, 2018 at 01:45:01AM +1100, Chris Angelico wrote:
> On Mon, Oct 8, 2018 at 1:41 AM Marko Ristin-Kaufmann
> <marko.ristin at gmail.com> wrote:
> > (If you wonder about the use case: I'd like to dynamically generate the docstrings when functions are decorated with contracts from icontract library. Condition functions need to be parsed and re-formatted, so this is something that should be done on-demand, when the user either wants to see the help() or when the sphinx documentation is automatically generated. The docs should not inflict computational overhead during the decoration since normal course of program operation does not need pretty-printed contracts.)
> >
> Have you tried just generating the docstrings at decoration time and
> applying them? By the sound of it, they won't change after that, and
> the only reason to run it later is performance... but have you
> actually measured a performance hit resulting from that?

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:

class X(builtins.object)
 |  Data descriptors defined here:
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  __weakref__
 |      list of weak references to the object (if defined)

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.


More information about the Python-ideas mailing list