import at module level or at function level?

2020-02-09 01:58发布

问题:

Which style is preferable?

Style A:

def foo():
    import some_module
    some_module.something

Style B:

import some_module

def foo():
    some_module.something

Assume that some_module is not used elsewhere in the code, only inside this function.

回答1:

Indeed, as already noted, it's usually best to follow the PEP 8 recommendation and do your imports at the top. There are some exceptions though. The key to understanding them lies in your embedded question in your second paragraph: "at what stage does the import ... happen?"

Import is actually an executable statement. When you import a module, all the executable statements in the module run. "def" is also an executable statement; its execution causes the defined name to be associated with the (already-compiled) code. So if you have:

def f():
    import something
    return None

in a module that you import, the (compiled) import and return statements get associated with the name "f" at that point. When you run f(), the import statement there runs.

If you defer importing something that is "very big" or "heavy", and then you never run the function (in this case f), the import never happens. This saves time (and some space as well). Of course, once you actually call f(), the import happens (if it has already happened once Python uses the cached result, but it still has to check) so you lose your time advantage.

Hence, as a rule of thumb, "import everything at the top" until after you have done a lot of profiling and discovered that importing "hugething" is wasting a lot of time in 90% of your runs, vs saving a little time in 10% of them.



回答2:

PEP 8 recommends that all imports happen at the top of the module. All names, including those bound to modules, are searched for in the local, non-local, global, and built-in scopes, in that order.