How does local rebinding of global names in Python make code faster/optimized?
Question: I was reading about [**Default Parameter Values in
Python**](http://effbot.org/zone/default-values.htm) on Effbot.

There is a section later in the article where the author talks about [**Valid
uses for mutable defaults**](http://effbot.org/zone/default-values.htm#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?


Answer: CPython access to local variable is _index_ -based (involving the
[`LOAD_FAST`](https://docs.python.org/2/library/dis.html#opcode-LOAD_FAST)
opcode).

On the other hands, globals are accessed through _name lookup_ in a dictionary
(using opcode
[`LOAD_GLOBAL`](https://docs.python.org/2/library/dis.html#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  
    

