简体   繁体   English

Python 多行字符串是否在 memory 中占用一些空间?

[英]Do Python multi-line strings take some space in the memory?

Guido van Rossum tweeted : Guido van Rossum 在 推特上写道:

Python tip: You can use multi-line strings as multi-line comments. Python 提示:您可以使用多行字符串作为多行注释。 Unless used as docstrings, they generate no code: :-)除非用作文档字符串,否则它们不会生成任何代码::-)

Does the below multi-line string, when not used as a docstring , take some space in memory?下面的多行字符串在不用作docstring时是否会在 memory 中占用一些空间?

'''
Hello, folks!
This is a multi-line string.
'''

It's straightforward to confirm that if you write a string by itself without assigning it to a variable or using it as part of another statement or expression, then that string (1) does not generate any CPython bytecode, and (2) does not appear in the code object's tuple of constants:很容易确认,如果您自己编写字符串而不将其分配给变量或将其用作另一个语句或表达式的一部分,则该字符串 (1) 不会生成任何 CPython 字节码,并且 (2) 不会出现在代码对象的常量元组:

>>> code = 'x = 1; "bar"; x = 2;'
>>> from dis import dis
>>> dis(code)
  1           0 LOAD_CONST               0 (1)
              2 STORE_NAME               0 (x)
              4 LOAD_CONST               1 (2)
              6 STORE_NAME               0 (x)
              8 LOAD_CONST               2 (None)
             10 RETURN_VALUE
>>> compile(code, '<string>', 'exec').co_consts
(1, 2, None)

So the string is discarded at compile-time just like a comment would be, and therefore cannot be present in memory at runtime.因此字符串在编译时被丢弃,就像注释一样,因此在运行时不能出现在 memory 中。 Note that this applies to all literal values, not just multi-line strings.请注意,这适用于所有文字值,而不仅仅是多行字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM