Import Tips

Learn how to import anything more efficiently in Python.

We'll cover the following

Import wisely

Modules are the building blocks of the Python ecosystem. A typical Python program imports dozens of modules, but we should always try to minimize how many modules we import.

If nothing in a file depends on some module, that module shouldn’t be imported. Importing a module takes time that we could better use for something else. Also, any import statement introduces a dependency. If the module goes unused, it’s a false dependency. If the unnecessary module is removed from the system, such as when it becomes obsolete, the importing code won’t run even if the module wasn’t used in the actual code.

Python is efficient at recognizing whether a module has already been imported. If it was, the system ignores the import statement that attempts to import it again. It still takes time to parse the statement and check the module status, however. It’s a good reason not to import a module within a function, especially if we plan to call the function in a loop.

Finally, Python Enhancement Proposal 8 (PEP 8), essentially the Python style guide, recommends that “imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.” The reason for this recommendation is so that our code reader can evaluate the module dependencies at once, without going through the entire file.

That’s where readability meets performance.

Get hands-on with 1200+ tech skills courses.