Are Python docstrings and comments stored in memory when a module is loaded?我想知道这是否属实,因为我通常会很好地记录我的代码;这可能会影响内存使用吗?通常每个Python对象都有一个__doc__方法.这些文档字符...

Are Python docstrings and comments stored in memory when a module is loaded?
我想知道这是否属实,因为我通常会很好地记录我的代码;这可能会影响内存使用吗?
通常每个Python对象都有一个__doc__方法.这些文档字符串是从文件中读取还是以其他方式处理?
我在论坛,谷歌和邮件列表中进行了搜索,但我没有找到任何相关信息.
你知道的更好吗?
解决方法:
默认情况下,文档字符串存在于.pyc字节码文件中,并从中加载(注释不是).如果你使用python -OO(-OO标志代表“强烈优化”,而不是-O代表“温和地优化”),你得到并使用.pyo文件而不是.pyc文件,并通过省略优化文档字符串(除了由-O完成的优化之外,还删除了断言语句).例如,考虑一个文件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会话…:
$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(或等效地,触摸foo.py,以便Python知道.pyo“已过时”)意味着Python重建它(在这种情况下,在磁盘上保存123个字节,并且稍微有点更多模块导入时 – 但所有.__ doc__条目消失并被None替换).
本文标题为:加载模块时,Python文档字符串和注释是否存储在内存中?


基础教程推荐
- 为什么python子进程输出与shell不同? 2023-11-14
- python通过pillow识别动态验证码的示例代码 2023-08-08
- 在windows 怎么安装Python2.7 的 PIL包 2023-09-03
- Python yield 关键词, 2023-08-04
- python解析.pyd文件的详细代码 2023-08-09
- Python UnicodedecodeError编码问题解决方法汇总 2022-08-30
- python-在CentOS上构建PyGTK时出现问题 2023-11-10
- Python瓶进程到达超时连接 2023-11-14
- 如何在Linux下的Python中创建主进程? 2023-11-15
- Ubuntu 18.04 切换使用Python3 2023-11-15