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?
In Alex Martelli’s response to Making a Python script Object-Oriented , he mentions that
Share
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
execstatement 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.