Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python __doc__ returning None [closed]

Just recently I have been getting very a bizarre issue, which I have found no resolve to. For example, if I run the following code in the interpreter

>>> def test():
...     'docstring'
...     ...
... 
>>> print(test.__doc__)

I get 'docstring,' no surprise there. Now if I run this in a *.py file, I get None.

I have tried multiple files with the same results; but why does the interpreter return the docstring and not any files? Any help would most certainly be appreciated.

Note: I have tried triple quotes, double and single, and any other variation I can muster, with no luck.

Solved: Not sure how exactly, but the command I was using was 'broken' in that shell instance. Working fine now

like image 225
Cubli Avatar asked Apr 29 '26 09:04

Cubli


1 Answers

The docstrings are stripped if you run the interpreter with the -OO switch:

-OO Discard docstrings in addition to the -O optimizations.

This can be also controlled by the PYTHONOPTIMIZE environment variable:

PYTHONOPTIMIZE

If this is set to a non-empty string it is equivalent to specifying the -O option. If set to an integer, it is equivalent to specifying -O multiple times.

Thus you could get this effect if you had a Python wrapper that specified -OO, or PYTHONOPTIMIZE was set to say 2.


However, this setting should also apply to the interactive interpreter:

% PYTHONOPTIMIZE=2 python3
Python 3.4.3 (default, Oct 14 2015, 20:28:29) 
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def foo():
...     'bar'
... 
>>> foo.__doc__
>>> 

You can test the optimization settings at runtime via sys.flags:

% PYTHONOPTIMIZE=2 python3
Python 3.4.3 (default, Oct 14 2015, 20:28:29) 
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.flags.optimize
2

If this number is greater than or equal to 2, then that is why your docstrings are gone.

like image 162