2
I have seen cases where the developer does the import of a module within a function, some cases mainly in the Django documentation, why it is not very clear to me, if anyone can help me thank.
2
I have seen cases where the developer does the import of a module within a function, some cases mainly in the Django documentation, why it is not very clear to me, if anyone can help me thank.
2
There are 2 reasons the developer does this:
Performance - The import will happen only when the function is called, and if it is never called, the interpreter will not need to load the module.
Backcompatibility - Imported libraries may be required only in specific environments (example Windows vs Linux, Python 2 vs Python 3). The system can call the specific function for each environment and load the supported libraries into it.
Browser other questions tagged python python-3.x python-2.7 importing
You are not signed in. Login or sign up in order to post.
Thank you Begnini.
– ThiagoO
In fact, there is one more reason that is "avoid circular imports" - that is, the function code in module A needs to access attributes or functions that are in module B that in turn imports (directly or indirectly) module A. Thus, this prevents a reference to incomplete module B from being available during the import of module A - and, during the execution of A functions, since B is already in memory, Imports have only the same impact as a variable association (that is, they do not imply finding and compiling the disk file)
– jsbueno