From the course: Faster Python Code

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Local caching of names

Local caching of names - Python Tutorial

From the course: Faster Python Code

Start my 1-month free trial

Local caching of names

- [Instructor] Knowing how Python operates will give you more tools for optimization. Let's take a look at some language features and tools that might give your code a boost. Let's say we want to normalize a list of numbers. So, we have a configuration at line three for the factor and the threshold. And then in line nine, we have a normalize. We'd go over the numbers and if they're above the threshold, we divide them by the factor. And then return. In line 23, we just regenerate a list of numbers, so we can test. Let's run the code. So, ipython and then run norm.py. Let's time it, timeit normalize of numbers. So, 198 microsecond. At first, it doesn't look like there's much delay but let's look at how Python compiles this function. So, we import the dis module and we do dis.dis of normalize. We see that twice we have LOAD_GLOBAL and after it, LOAD_ATTR. So, Python is looking for the name config in the global and then looking for the attribute threshold inside. The same here, we have…

Contents