Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@ramalho
Created July 9, 2014 15:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ramalho/7ceaf014d125749f0b0c to your computer and use it in GitHub Desktop.
Save ramalho/7ceaf014d125749f0b0c to your computer and use it in GitHub Desktop.
Constant folding in Python: think about why the bytecodes generated for f() and g() are different

>>> import dis >>> def f(x): ... return 1+2+3+4+x ... >>> f(5) 15 >>> dis.dis(f) 2 0 LOAD_CONST 7 (10) 3 LOAD_FAST 0 (x) 6 BINARY_ADD 7 RETURN_VALUE >>> def g(x): ... return x+1+2+3+4 ... >>> dis.dis(g) 2 0 LOAD_FAST 0 (x) 3 LOAD_CONST 1 (1) 6 BINARY_ADD 7 LOAD_CONST 2 (2) 10 BINARY_ADD 11 LOAD_CONST 3 (3) 14 BINARY_ADD 15 LOAD_CONST 4 (4) 18 BINARY_ADD 19 RETURN_VALUE

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment