python - 加载模块时,Python 文档字符串和注释是否存储在内存中?

标签 python comments memory-management docstring

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/

相关文章:

python - 如何在 DataFrame 的字符串列中应用正则表达式替换?

python - Python 列表中的额外元素

python - Django - 保存时永远不要更新列

comments - 在 Notepad++ 中隐藏评论

c++ - 如何在 C++ 中跟踪内存分配(尤其是新建/删除)

python - 使用条件参数Python从CSV文件中删除行

php - 按点赞数列出评论

css - 同位素网格和内联 ajax 注释

c++ - 删除指针数组会使调用者的应用程序崩溃

c - 通过直接写入下面的发送缓冲区来保存堆栈