These two questions concern using import
inside a function vs. at the top of a module. I do not need to be convinced to put my imports at the top, there are good reasons to do that. However, to better understand the technical issues I would like to ask a followup.
Can you get the best of both worlds performance-wise by using a closure and only importing on first run of the function?
Specifically, suppose you have code such as:
import sys
def get_version():
return sys.version
You want the import to only happen if the function ever gets called, so you move it inside:
def get_version():
import sys
return sys.version
But now it is slow if it does get called a lot, so you try something more complex:
def _get_version():
import sys
def nested():
return sys.version
global get_version
get_version = nested
return nested()
get_version = _get_version
Now at least a basic performace test indicates that this last option is slightly slower than the first (taking ~110% as long), but much faster than the second (taking ~20% as long).
First, does this actually work? Do my measurements accurately depict that the second example does more work or is it an artifact of how I measured things.
Second, is there a slowdown from the closure – beyond the first time the function is run?