Hey everyone!
I have a project where I use compile()
. Out of curiosity I wonder if it specialises when used.
For better context here is minimal example how I use it:
# "init"
src_code_str = 'expected_value = x * 1000 + 946666800'
formula = compile(src_code_str, 'formula.py', 'exec', optimize=2)
# usage
x = get_int_from_somewhere()
exec(formula)
... # use expected_value
smontanaro
(Skip Montanaro)
2
If you warm it up, yes:
>>> dis.dis(formula, adaptive=True, show_caches=True)
0 0 RESUME 0
1 2 LOAD_NAME 0 (x)
4 LOAD_CONST 0 (1000)
6 BINARY_OP 5 (*)
8 CACHE 0
10 LOAD_CONST 1 (946666800)
12 BINARY_OP 0 (+)
14 CACHE 0
16 STORE_NAME 1 (expected_value)
18 LOAD_CONST 2 (None)
20 RETURN_VALUE
>>> import random
>>> for i in range(100):
... x = random.random()
... exec(formula)
...
>>> dis.dis(formula, adaptive=True, show_caches=True)
0 0 RESUME_QUICK 0
1 2 LOAD_NAME 0 (x)
4 LOAD_CONST 0 (1000)
6 BINARY_OP_ADAPTIVE 5 (*)
8 CACHE 0 (counter: 438)
10 LOAD_CONST 1 (946666800)
12 BINARY_OP_ADAPTIVE 0 (+)
14 CACHE 0 (counter: 438)
16 STORE_NAME 1 (expected_value)
18 LOAD_CONST 2 (None)
20 RETURN_VALUE
1 Like
Thank you! Seems I forgot to use adaptive=True
when tested it myself.