Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is a better practice - global import or local import

I am developing an app in django and I had a doubt if importing a library at the global level has any impact over the memory or performance than importing at the local ( per-function) level. If it is imported per function or view, the modules that are needed alone are imported saving space right? Or are there any negatives in doing so?

like image 846
Aswin Murugesh Avatar asked Dec 03 '13 08:12

Aswin Murugesh


2 Answers

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.

like image 121
Daniel Roseman Avatar answered Oct 19 '22 22:10

Daniel Roseman


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.

like image 33
Anton Tarasenko Avatar answered Oct 19 '22 20:10

Anton Tarasenko