Skip to content

Commit bf967b0

Browse files
committed
String can be tricky: Remove outdated snippet
Related to satwikkansal#120
1 parent 80a969a commit bf967b0

File tree

1 file changed

+4
-5
lines changed

1 file changed

+4
-5
lines changed

README.md

+4-5
Original file line numberDiff line numberDiff line change
@@ -179,13 +179,12 @@ True
179179
>>> b = "wtf!"
180180
>>> a is b
181181
False
182-
183-
>>> a = "wtf!"; b = "wtf!";
184-
>>> a is b
185-
True
186182
```
187183
188184
3\.
185+
186+
**Output (< Python3.7 )**
187+
189188
```py
190189
>>> 'a' * 20 is 'aaaaaaaaaaaaaaaaaaaa'
191190
True
@@ -203,8 +202,8 @@ Makes sense, right?
203202
* Strings are interned at compile time (`'wtf'` will be interned but `''.join(['w', 't', 'f']` will not be interned)
204203
* Strings that are not composed of ASCII letters, digits or underscores, are not interned. This explains why `'wtf!'` was not interned due to `!`. Cpython implementation of this rule can be found [here](https://github.com/python/cpython/blob/3.6/Objects/codeobject.c#L19)
205204
<img src="images/string-intern/string_intern.png" alt="">
206-
+ When `a` and `b` are set to `"wtf!"` in the same line, the Python interpreter creates a new object, then references the second variable at the same time. If you do it on separate lines, it doesn't "know" that there's already `wtf!` as an object (because `"wtf!"` is not implicitly interned as per the facts mentioned above). It's a compiler optimization and specifically applies to the interactive environment.
207205
+ Constant folding is a technique for [peephole optimization](https://en.wikipedia.org/wiki/Peephole_optimization) in Python. This means the expression `'a'*20` is replaced by `'aaaaaaaaaaaaaaaaaaaa'` during compilation to reduce few clock cycles during runtime. Constant folding only occurs for strings having length less than 20. (Why? Imagine the size of `.pyc` file generated as a result of the expression `'a'*10**10`). [Here's](https://github.com/python/cpython/blob/3.6/Python/peephole.c#L288) the implementation source for the same.
206+
+ Note: In Python 3.7, Constant folding was moved out from peephole optimizer to the new AST optimizer with some change in logic as well, so the third snippet doesn't work for Python 3.7. You can read more about the change [here](https://bugs.python.org/issue11549).
208207
209208
---
210209

0 commit comments

Comments
 (0)