I was reading about Default Parameter Values in Python on Effbot.
There is a section later in the article where the author talks about Valid uses for mutable defaults and cites the following example:
and, for highly optimized code, local rebinding of global names:
import math
def this_one_must_be_fast(x, sin=math.sin, cos=math.cos):
...
I haven't been able to locate how this causes fast/highly optimised execution of code. Can somebody enlighten on this with a well informed (and preferably with citations) answer?
CPython access to local variable is index-based (involving the LOAD_FAST
opcode).
On the other hands, globals are accessed through name lookup in a dictionary (using opcode LOAD_GLOBAL
). For module variables, it's a two step process. Using a first look-up (LOAD_GLOBAL
) to push the module object, and then using a second look-up (LOAD_ATTR
) to locate the appropriate member.
Even if dictionary lookup is highly optimized, it can't beat indirect access.
import math
def f():
math.sin(1)
4 0 LOAD_GLOBAL 0 (math) ***
3 LOAD_ATTR 1 (sin) ***
6 LOAD_CONST 1 (1)
9 CALL_FUNCTION 1
12 POP_TOP
13 LOAD_CONST 0 (None)
16 RETURN_VALUE
from math import sin
def f():
sin(1)
4 0 LOAD_GLOBAL 0 (sin) ***
3 LOAD_CONST 1 (1)
6 CALL_FUNCTION 1
9 POP_TOP
10 LOAD_CONST 0 (None)
13 RETURN_VALUE
def f(sin=math.sin):
sin(1)
7 0 LOAD_FAST 0 (sin) ***
3 LOAD_CONST 1 (1)
6 CALL_FUNCTION 1
9 POP_TOP
10 LOAD_CONST 0 (None)
13 RETURN_VALUE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With