The Python interpreter compiles programs into bytecode first, and the bytecode includes instructions that load a constant from the constant pool. As an example,
>>> def f():
... x = 2222; y=2222
... return x is y
...
>>> f()
True
>>> f.func_code.co_consts
(None, 2222)
This last line is showing the constant pool, which is just a standard Python tuple.
I believe the REPL compiles each input in a new toplevel module context, so each input gets its own constant pool.
Functions get their own constant pools, which explains the following behavior:
>>> if True:
... def f():return 2222
... def g():return 2222
...
>>> f() is g()
False
I'm glad you and squeaky-clean wrote these comments. When I was experimenting in the Python REPL, I was confused by the last line here:
>>> 100 is 100
True
>>> (10 ** 2) is (10 ** 2)
True
>>> (10 ** 3) is (10 ** 3)
False
>>> 1000 is 1000
True
I used the disassembler, but I completely missed that although `1000 is 1000` and `(10 3) is (10 3)` both get optimized to nearly identical bytecode they load different constants. I wrote it up in a new post and thanked you both. https://kate.io/blog/2017/08/24/python-constants-in-bytecode...
Yep yep, and only when no operations are done to it, otherwise it will end up storing the same constant multiple times and referring to each separately. For example
I believe the REPL compiles each input in a new toplevel module context, so each input gets its own constant pool.
Functions get their own constant pools, which explains the following behavior: