Are Python docstrings and comments stored in memory when a module is loaded?
I’ve wondered if this is true, because I usually document my code well; may this affect memory usage?
Usually every Python object has a __doc__ method. Are those docstrings read from the file, or processed otherwise?
I’ve done searches here in the forums, Google and Mailing-Lists, but I haven’t found any relevant information.
Do you know better?
By default, docstrings are present in the
.pycbytecode file, and are loaded from them (comments are not). If you usepython -OO(the-OOflag stands for “optimize intensely”, as opposed to-Owhich stands for “optimize mildly), you get and use.pyofiles instead of.pycfiles, and those are optimized by omitting the docstrings (in addition to the optimizations done by-O, which removeassertstatements). E.g., consider a filefoo.pythat has:you could have the following shell session…:
Note that, since we used
-Ofirst, the.pyofile was 327 bytes — even after using-OO, because the.pyofile was still around and Python didn’t rebuild/overwrite it, it just used the existing one. Removing the existing.pyo(or, equivalently,touch foo.pyso that Python knows the.pyois “out of date”) means that Python rebuilds it (and, in this case, saves 123 bytes on disk, and a little bit more when the module’s imported — but all.__doc__entries disappear and are replaced byNone).