python - import at module level or at function level? -
which style preferable?
style a:
def foo(): import some_module some_module.something
style b:
import some_module def foo(): some_module.something
assume some_module
not used elsewhere in code, inside function.
indeed, noted, it's best follow pep 8 recommendation , imports @ top. there exceptions though. key understanding them lies in embedded question in second paragraph: "at stage import ... happen?"
import executable statement. when import module, executable statements in module run. "def" executable statement; execution causes defined name associated (already-compiled) code. if have:
def f(): import return none
in module import, (compiled) import , return statements associated name "f" @ point. when run f(), import statement there runs.
if defer importing "very big" or "heavy", , never run function (in case f), import never happens. saves time (and space well). of course, once call f(), import happens (if has happened once python uses cached result, still has check) lose time advantage.
hence, rule of thumb, "import @ top" until after have done lot of profiling , discovered importing "hugething" wasting lot of time in 90% of runs, vs saving little time in 10% of them.
Comments
Post a Comment