Let's break it down.
The style guide used by most people, the document called PEP-8, recommends that imports be in the module header.
BUT you have to keep in mind that they are recommendations for style and not iron and fire - the most important thing is to understand what happens, and then you check what is best at each point of your project.
Will the module only be imported when the method is called?
If the same module is not imported into any other module or place, yes, it will only be imported when the method is called for the first time.
So, is the module re-imported every time the method is called?
No! After a module is imported into Python, it is kept in an internal record (the sys.modules
dictionary), and new import directives for the same module only create new variables, in the local context, pointing to the module that has already been read. That is, in subsequent calls to the same method, the "cost" of import is the same cost of creating a new variable, that is, almost nothing.
The best practice is for you to decide. Because of the style guide I put almost all the imports in the header of the modules. But not always. It can be a fairly large package to import that will not be necessary in any program execution, for example: a function that exports a graphic and for that matplotlib imports. Moving the import into a method in this case would make the program start to be faster, with the counterpart of a delay (always less than 1s in general) when the feature is used the first time.
As a rule, if your program is a service that functions as a server, it is best to import everything at the beginning, ensuring a minimum wait time on all requests. If it is an interactive program, it might be interesting to opt for a faster start and to make some imports later.
In some projects the test files get very large, I also choose to import the functions / classes being tested directly inside the test functions, just to be more visible what I am testing. (But a reorganization could simply break everything down into smaller files, for example.)
And finally, sometimes, due to the very operation of your system, it is necessary to a late import of some modules. It is the case of applications in Flask, for example - in which it is convenient for module __init__
to have references to the views, but on the other hand, the view files need to have a reference to the object app
defined in the __init__
. This is generally solved by importing the views in __init__
closer to the end of the file, but could be within a function as well.