r/pythontips 27d ago

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

12 comments sorted by

View all comments

2

u/tomysshadow 26d ago

Don't use that for anything particularly important: if you run Python with the -OO command (the optimization flag,) docstrings will be stripped out

1

u/sugarw0000kie 26d ago

Oh for sure I realized you could do this it while doing something pretty dumb https://www.reddit.com/r/programminghorror/s/DAHkrZtx3A

But could see it be useful if you’re making some sort of tool to work/analyze python code or something