3 ms·
Python itself warns you nowadays too, it will print out <dis>:1: SyntaxWarning: "is" with a literal. Did you mean "=="? Some more weird/fun stuff about th
by squeaky-clean 4y ago
Python itself warns you nowadays too, it will print out
<dis>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
Some more weird/fun stuff about that: If you throw that code into one file instead of a repl, `x is 257` will be True. If you instead instantiate `x = 257` in a different file, and import it, `x is 257` be False again. In a repl if you run them on the same line it ends up as True!
>>> x = 257
>>> print(x is 257)
False
>>> y = 257; print(y is 257)
True
If they're in the same file (or same line in a repl), the integer literals are loaded into the `co_consts` object during the initial parse to bytecode, and so they refer to the same object. This only works for integer literals and simple statements that can be optimized to literals by python (e.g. it also works for `x = 257+1; print(x is 258)`
>>> dis.dis('y = 257+1; print(y is 258)')
1 0 LOAD_CONST 0 (258)
2 STORE_NAME 0 (y)
4 LOAD_NAME 1 (print)
6 LOAD_NAME 0 (y)
8 LOAD_CONST 0 (258)
10 IS_OP 0
12 CALL_FUNCTION 1
14 POP_TOP
16 LOAD_CONST 1 (None)
18 RETURN_VALUE