What is the best practice - global imports or local imports

I am developing an application in django, and I have a doubt that importing a library at the global level has any effect on memory or performance than importing at the local level (for each function). If it is imported for each function or view, then the necessary modules themselves are imported, saving space? Or are there any negatives?

+6
source share
3 answers

You probably noticed that almost all of the Python code imports at the top of the file. The reason is that the import overhead is minimal, and the likelihood that you will be importing code at some point in the process life cycle, so you can also get rid of it.

The only good reason to import at the function level is to avoid circular dependencies.

Change Your comments indicate that you did not understand how web applications typically work, at least in Python. They do not start a new process for each request and do not import code from scratch. Rather, the server creates process instances if necessary, and each of them serves many requests until it is finally killed. Therefore, again it is likely that during this life all imports will ultimately be necessary.

+12
source

When the script is executed, it will store the modules in memory, I'm sure you understand that.

If you import a local area, the module will be imported every time the client calls this function. But if the module is imported globally, this will not be necessary!

So, in this case, global imports win.

0
source

Import overhead

From Python Performance Tips :

It is often useful to place them inside functions in order to limit their visibility and / or reduce the initial launch time. Although the Python interpreter is optimized so as not to import the same module multiple times, re-executing the import statement can seriously affect performance in some circumstances.

0
source

Source: https://habr.com/ru/post/959222/


All Articles