Are Python docstrings and comments stored in memory when a module is loaded?
我想知道这是不是真的,因为我通常会很好地记录我的代码;这会影响内存使用吗?
通常每个 Python 对象都有一个 __doc__
方法。这些文档字符串是从文件中读取的,还是以其他方式处理的?
我在论坛、Google 和邮件列表中进行了搜索,但没有找到任何相关信息。
你知道得更多吗?
最佳答案
默认情况下,文档字符串存在于 .pyc
字节码文件中,并从中加载(注释不是)。如果您使用 python -OO
(-OO
标志代表“强烈优化”,而 -O
代表“温和优化” ),你得到并使用 .pyo
文件而不是 .pyc
文件,这些文件通过省略文档字符串进行了优化(除了 -O 完成的优化
,它删除了 assert
语句)。例如,考虑一个文件 foo.py
具有:
"""This is the documentation for my module foo."""
def bar(x):
"""This is the documentation for my function foo.bar."""
return x + 1
您可以拥有以下 shell session ...:
$ python -c'import foo; print foo.bar(22); print foo.__doc__'
23
This is the documentation for my module foo.
$ ls -l foo.pyc
-rw-r--r-- 1 aleax eng 327 Dec 30 16:17 foo.pyc
$ python -O -c'import foo; print foo.bar(22); print foo.__doc__'
23
This is the documentation for my module foo.
$ ls -l foo.pyo
-rw-r--r-- 1 aleax eng 327 Dec 30 16:17 foo.pyo
$ python -OO -c'import foo; print foo.bar(22); print foo.__doc__'
23
This is the documentation for my module foo.
$ ls -l foo.pyo
-rw-r--r-- 1 aleax eng 327 Dec 30 16:17 foo.pyo
$ rm foo.pyo
$ python -OO -c'import foo; print foo.bar(22); print foo.__doc__'
23
None
$ ls -l foo.pyo
-rw-r--r-- 1 aleax eng 204 Dec 30 16:17 foo.pyo
请注意,由于我们首先使用了 -O
,因此 .pyo
文件为 327 字节——即使在使用 -OO
之后,因为.pyo
文件仍然存在,Python 没有重建/覆盖它,它只是使用现有的文件。删除现有的 .pyo
(或者,等效地,touch foo.py
以便 Python 知道 .pyo
是“过时的”)意味着Python 重建它(并且,在这种情况下,在磁盘上节省 123 个字节,并且在导入模块时多一点——但是所有 .__doc__
条目都消失并被替换为 None
)。
关于python - 加载模块时,Python 文档字符串和注释是否存储在内存中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1983177/