Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is putting the module level code into a function and then calling the function is faster in Python?

In Alex Martelli's response to Making a Python script Object-Oriented, he mentions that putting module level code into a function and then calling the function is faster in Python. Can someone explain why and whether it's true for all implementations of Python?

like image 711
inman320 Avatar asked Nov 08 '11 16:11

inman320


People also ask

Why does Python code run faster in a function?

The reason these built-in functions are fast is that python's built-in functions, such as min, max, all, map, etc., are implemented in the C language. You should use these built-in functions instead of writing manual functions that will help you execute your code faster.

How do I make my Python program run faster?

Take Advantage of Numpy Numpy is a highly optimized library built with C. It is almost always faster to offload math to Numpy rather than relying on the Python interpreter. Numpy also has ultra-efficient data structures designed to hold matrix data that have less overhead than Python's built-in data structures.

Which is the faster way to change data inputs for a Python script?

Faster way in basic Python We might use the sum function instead of the for loop in our example. This function sums the values inside the specified range of integers. It takes 2.54 seconds to run the code above. That's a lot quicker than the last loop!

What is module level function in Python?

A Python module is a file containing Python definitions and statements. A module can define functions, classes, and variables. A module can also include runnable code. Grouping related code into a module makes the code easier to understand and use. It also makes the code logically organized.


1 Answers

This is mostly due to variable look-up. Looking up a variable in the global scope requires a dictionary look-up. In contrast, the compiler determines local names statically and references them by index, so no dictionary look up is required.

Note that in Python 2.x the presence of an exec statement inside a function will deactivate this optimisation, since names can't be determined statically any more. In Python 3.x, exec() is a regular function, and as such it isn't allowed to change the variables in the local scope.

like image 132
Sven Marnach Avatar answered Sep 22 '22 12:09

Sven Marnach