Reputation: 3
Guido van Rossum tweeted:
Python tip: You can use multi-line strings as multi-line comments. 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?
'''
Hello, folks!
This is a multi-line string.
'''
Upvotes: 0
Views: 401
Reputation: 51122
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:
>>> 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. Note that this applies to all literal values, not just multi-line strings.
Upvotes: 4