Import at module level or function level?

Which style is preferable?

Style A:

def foo(): import some_module some_module.something 

Style B:

 import some_module def foo(): some_module.something 

Suppose some_module not used elsewhere in the code, only inside this function.

+7
source share
2 answers

Indeed, as already noted, it is usually best to follow the recommendations of PEP 8 and do your import at the top. However, there are some exceptions. The key to understanding them is your built-in question in the second paragraph: "At what stage does the import take place ..."

Import is actually an executable statement. When a module is imported, all executable statements in the module are executed. "def" is also an executable expression; executing it causes a specific name to be associated with (already compiled) code. Therefore, if you have:

 def f(): import something return None 

in the module that you import, the (compiled) import and return statements are associated with the name "f" at this point. When you run f (), the import statement will be executed there.

If you delay the import of “very large” or “heavy” and then you never run the function (in this case f), the import will never happen. This saves time (and some space). Of course, as soon as you actually call f (), an import occurs (if this has already happened, as soon as Python uses the result of the cache, but it still has to check), so you lose your time advantage.

Therefore, as a rule, “import everything from above” until you do a lot of profiling and find that importing “hugething” spends a lot of time on 90% of your runs, little time in 10% of them.

+15
source

PEP 8 recommends that all imports be performed at the top of the module. All names, including those associated with modules, are executed in local, non-local, global, and built-in areas in this order.

+6
source

All Articles