Book Image

Mastering Python High Performance

Book Image

Mastering Python High Performance

Overview of this book

Table of Contents (15 chapters)

Usage of default arguments

Another optimization technique, one that is contrary to memoization, is not particularly generic. Instead, it is directly tied to how the Python interpreter works.

Default arguments can be used to determine values once at function creation time, instead of at run time.


This can only be done for functions or objects that will not be changed during program execution.

Let's look at an example of how this optimization can be applied. The following code shows two versions of the same function, which does some random trigonometric calculation:

import math 

#original function
def degree_sin(deg):
    return math.sin(deg * math.pi / 180.0)

#optimized function, the factor variable is calculated during function creation time, 
#and so is the lookup of the math.sin method.
def degree_sin(deg, factor=math.pi/180.0, sin=math.sin):
    return sin(deg * factor)


This optimization can be problematic if not correctly documented. Since it uses attributes to precompute terms that...