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.
torek
source share