There are some pretty obvious technical problems; the question is whether or not they matter for your use case.
Here are some major uses for docstrings that your idiom will not help with:
help(a)
: Type help(a)
in an interactive terminal, and you get the docstring for MyClass
, not the docstring for a
.
- Auto-generated documentation: Unless you write your own documentation generator, it's not going to understand that you've done anything special with your
a
value. Many doc generators do have some way to specify help for module and class constants, but I'm not aware of any that will recognize your idiom.
- IDE help: Many IDEs will not only auto-complete an expression, but show the relevant docstring in a tooltip. They all do this statically, and without some special-case code designed around your idiom (which they're unlikely to have, given that it's an unusual idiom), they're almost certain to fetch the docstring for the class, not the object.
Here are some where it might help:
- Source readability: As a human reading your source, I can tell the intent from the
a.__doc__ = …
right near the construction of a
. Then again, I could tell the same intent just as easily from a Sphinx comment on the constant.
- Debugging:
pdb
doesn't really do much with docstrings, but some GUI debuggers wrapped around it do, and most of them are probably going to show a.__doc__
.
- Custom dynamic use of docstrings: Obviously any code that you write that does something with
a.__doc__
is going to get the instance docstring if you want it to, and therefore can do whatever it wants with it. However, keep in mind that if you want to define your own "protocol", you should use your own name, not one reserved for the implementation.
Notice that most of the same is true for using a descriptor for the docstring:
>>> class C:
... @property
... def __doc__(self):
... return('C doc')
>>> c = C()
If you type c.__doc__
, you'll get 'C doc'
, but help(c)
will treat it as an object with no docstring.
It's worth noting that making help
work is one of the reasons some dynamic proxy libraries generate new classes on the fly—that is, a proxy to underlying type Spam
has some new type like _SpamProxy
, instead of the same GenericProxy
type used for proxies to Ham
s and Eggs
eses. The former allows help(myspam)
to show dynamically-generated information about Spam
. But I don't know how important a reason it is; often you already need dynamic classes to, e.g., make special method lookup work, at which point adding dynamic docstrings comes for free.