Import At Module Level Or At Function Level?
Solution 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:
deff():
import something
returnNone
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.
Solution 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.
Post a Comment for "Import At Module Level Or At Function Level?"