默认情况下,Python 文档字符串会无限期地保存,因为它们可以通过函数或模块的 __doc__ 属性访问。例如,在 test.py 中使用以下内容:
"""This is a test module."""
def f():
"""This is a test function."""
pass
然后:
$ python
Python 2.5.1 (r251:54863, Oct 30 2007, 13:54:11)
[GCC 4.1.2 20070925 (Red Hat 4.1.2-33)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import test
>>> test.__doc__
'This is a test module.'
>>> test.f.__doc__
'This is a test function.'
>>>
解释器的-OO 选项显然会导致它从生成的.pyo 文件中删除文档字符串,但它没有达到我期望的效果:
$ python -OO
Python 2.5.1 (r251:54863, Oct 30 2007, 13:54:11)
[GCC 4.1.2 20070925 (Red Hat 4.1.2-33)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import test
>>> test.__file__
'/tmp/test.py'
>>>
$ grep "This is a test" /tmp/test.pyo
Binary file /tmp/test.pyo matches
$ python -OO
Python 2.5.1 (r251:54863, Oct 30 2007, 13:54:11)
[GCC 4.1.2 20070925 (Red Hat 4.1.2-33)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import test
>>> test.__file__
'/tmp/test.pyo'
>>> test.__doc__
'This is a test module.'
>>>
事实上,使用-OO 生成的test.pyo 文件与不使用命令行参数生成的test.pyc 文件相同。谁能解释这种行为?