[Django]-Which is a better practice – global import or local import


You surely must have noticed that almost all Python code does the imports at the top of the file. There’s a reason for that: the overhead of importing is minimal, and the likelihood is that you will be importing the code at some point during the process lifetime anyway, so you may as well get it out of the way.

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

Edit Your comments indicate you haven’t understood how web apps generally work, at least in Python. They don’t start a new process for each request and import the code from scratch. Rather, the server instantiates processes as required, and each one serves many requests until it is finally killed. So again it is likely that during that lifetime, all the imports will end up being needed.


Import Statement Overhead

From Python Performance Tips:

It’s often useful to place them inside functions to restrict their visibility and/or reduce initial startup time. Although Python’s interpreter is optimized to not import the same module multiple times, repeatedly executing an import statement can seriously affect performance in some circumstances.


When the script is run, it will store the modules in memory, i’m sure you understand that.

If you’re importing on a local scope, the module will be imported each time the client calls the function. But if the module is imported at a global level, there will be no need for that!

So, in this case: global import wins.


Leave a comment