質問

From the 2.7.2 docs, Section 6, Modules:

Passing two -O flags to the Python interpreter (-OO) will cause the bytecode compiler to perform optimizations that could in some rare cases result in malfunctioning programs. Currently only __doc__ strings are removed from the bytecode, resulting in more compact .pyo files.

This got my attention:

Since some programs may rely on having these available, you should only use this option if you know what you’re doing.

Are there any cases where removing a script's docstrings might logically break some dependency or other aspect of a code's functionality, disregarding any syntactic errors?

EDIT

Why would removing comments break a help statement? It doesnt seem to do so in the interpreter.

>>> help('import_pi')

Help on module import_pi:

NAME
    import_pi

FILE
    /home/droogans/py/import_pi.py

FUNCTIONS
    print_pi()

DATA
    pi = 3.1415926535897931


>>> import import_pi()
>>> import_pi.__doc__
>>>
>>> print import_pi.print_pi.__doc__
Convert a string or number to a floating point number, if possible.
役に立ちましたか?

解決

For example ply is a module that does lexing and parsing which uses docstrings to describe the grammar. Stripping docstrings would break the code.

他のヒント

The -OO option only affects whether a doc string is stored -- it does not affect parsing. For example the following code works with and without optimizations enabled:

def f():
    'Empty docstring'

assert f() is None

The programs that will break with the docstring optimization enabled are ones that rely on the contents of the docstring. Paul Hankin mentioned Ply which is tool that uses docstrings for its dispatch logic. Another example is the doctest module which uses the contents of docstrings for tests.

Here's a simple example of code that won't work with the -OO optimization enabled:

def f():
    '30 + 40'
    return eval(f.__doc__)

print f()

Note help() will still work with the -OO optimization enabled, but it will only find the function name, arguments, and module, but not the docstring:

>>> help(f)
Help on function f in module __main__:

f()
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top