Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does local rebinding of global names in Python make code faster/optimized?

Tags:

python

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?

like image 559
Nandeep Mali Avatar asked Aug 28 '14 13:08

Nandeep Mali


1 Answers

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  
like image 110
Sylvain Leroux Avatar answered Oct 06 '22 01:10

Sylvain Leroux