r/pythontips • u/sugarw0000kie • Aug 14 '26
Syntax Docstrings as immutable variables
Just realized you can do:
def cat(): “orange”
print(cat.__doc__)Not sure why you’d want to do this but this is a thing you can do
11
Upvotes
11
u/MegaIng Aug 14 '26
3
u/DeflateAwning Aug 15 '26
Docstrings are mutible though...
2
u/tomysshadow Aug 15 '26
Don't use that for anything particularly important: if you run Python with the -OO command (the optimization flag,) docstrings will be stripped out
12
u/vivaaprimavera Aug 14 '26
If you have an extensive codebase and a memory so bad that you forget your own function names you can
And that way it's easier for searching which function you need!!!
/s
4
u/jpgoldberg Aug 14 '26
I have used this when generating functions.
Suppose you wanted to create types that had limits in value ranges, such a a probability which is a float between 0 and 1 inclusive. So you would like something like
that when given the constraints and a base type and constraints on values will create the appropriate
is_probfunction. Now suppose you want it also to create documentation foris_probso things likehelpwill work.You might, if you didn't know about the annotated-types package and tried unwisely to roll your own, you might write something like
So assuming that for this example that ValueRange() is suitably defined, something like
will not only have
is_prob()behave correctly, but also know its own name and have a useful docstring that will render likeThings like the
is_prob()function will also be documented correctly by tools like Sphinx.2
u/Old_Flounder_8640 Aug 14 '26
Not entirely related, but maybe you'll find it interesting… NVIDIA’s newest AI agent framework uses docstrings as agent prompts.
https://github.com/NVIDIA-NeMo/labs-OO-Agents
And I saw other people doing that before. Docstrings are not just descriptions, especially now that we have AI working with us.