加载模块时,Python文档字符串和注释是否存储在内存中? [英] Are Python docstrings and comments stored in memory when a module is loaded?
问题描述
加载模块时,Python文档字符串和注释是否存储在内存中?
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?
通常每个Python对象都有一个__doc__
方法.这些文档字符串是从文件读取还是以其他方式处理?
Usually every Python object has a __doc__
method. Are those docstrings read from the file, or processed otherwise?
我已经在论坛,Google和邮件列表中进行过搜索,但是没有找到任何相关信息.
I've done searches here in the forums, Google and Mailing-Lists, but I haven't found any relevant information.
您了解得更多吗?
推荐答案
默认情况下,文档字符串存在于.pyc
字节码文件中,并从中加载(没有注释).如果使用python -OO
(-OO
标志代表强烈优化",而-O
代表适度优化"),则获取并使用.pyo
文件而不是.pyc
文件,通过省略文档字符串进行了优化(除了-O
完成的优化(删除了assert
语句之外)),例如,考虑文件foo.py
具有:
By default, docstrings are present in the .pyc
bytecode file, and are loaded from them (comments are not). If you use python -OO
(the -OO
flag stands for "optimize intensely", as opposed to -O
which stands for "optimize mildly), you get and use .pyo
files instead of .pyc
files, and those are optimized by omitting the docstrings (in addition to the optimizations done by -O
, which remove assert
statements). E.g., consider a file foo.py
that has:
"""This is the documentation for my module foo."""
def bar(x):
"""This is the documentation for my function foo.bar."""
return x + 1
您可以进行以下Shell会话...:
you could have the following 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
,所以即使使用-OO
后,.pyo
文件也为327字节,因为.pyo
文件仍然存在并且Python并未重建/覆盖它,它只是使用现有的.删除现有的.pyo
(或等效的touch foo.py
,以便Python知道.pyo
是过时的")意味着Python对其进行了重建(在这种情况下,在磁盘上节省了123个字节,并节省了一点时间)导入模块时会增加一点-但所有.__doc__
条目都会消失,并由None
代替).
Note that, since we used -O
first, the .pyo
file was 327 bytes -- even after using -OO
, because the .pyo
file was still around and Python didn't rebuild/overwrite it, it just used the existing one. Removing the existing .pyo
(or, equivalently, touch foo.py
so that Python knows the .pyo
is "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 by None
).
这篇关于加载模块时,Python文档字符串和注释是否存储在内存中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!