4 ms·
The Python interpreter compiles programs into bytecode first, and the bytecode includes instructions that load a constant from the constant pool. As an example
by kmill 9y ago
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
- squeaky-clean 9y agoYep 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 >>> def f(): ... x = 2221+1; y=2221+1 ... return x is y >>> f() False >>> f.__code__.co_consts (None, 2221, 1, 2222, 2222) >>> dis.dis(f) 2 0 LOAD_CONST 3 (2222) 2 STORE_FAST 0 (x) 4 LOAD_CONST 4 (2222) 6 STORE_FAST 1 (y) 3 8 LOAD_FAST 0 (x) 10 LOAD_FAST 1 (y) 12 COMPARE_OP 8 (is) 14 RETURN_VALUE Not too sure when stuff like this would be useful (it goes way beyond the 'avoid using is unless checking references` advice), but it sure is fun.
- katee 9y agoI'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/ https://kate.io/blog/2017/08/24/python-constants-in-bytecode...