What are the “best practices” for using import in a Python module?

The import statement, just like any other statement or keyword in Python should be used and added to the code properly following the best practices. Let’s see them one by on −

Multiple Imports

Multiple Imports should usually be on separate lines. For example −

import numpy import pandas import matplotlib

Always on the Top

Imports are always put at the top of the file i.e.

  • After any module comments and docstrings
  • Before module globals and constants.

For example −

# import the numpy module import numpy

Import Modules in an Order

A good practice is toimport modules in the following order −

  • Standard library modules – e.g. sys, os, getopt, re
  • Third-party library modules – e.g. ZODB, PIL.Image, etc.
  • Locally developed modules

Absolute Imports

Absolute imports are recommended, as they are usually more readable and tend to be better performed if the import system is incorrectly configured. For example −

import mypkg.sibling from mypkg import sibling from mypkg.sibling import example

Wildcard imports (from import *) should be avoided

Avoid the Wildcard imports since they make it unclear which names are present in the namespace, confusing both readers and many automated tools.

Circular Import

To avoid problems with circular imports, it is sometimes necessary to move imports to a function or class. Gordon McMillan says −

“Circular imports are fine where both modules use the “import <module>” form of import. They fail when the 2nd module wants to grab a name out of the first (“from module import name”) and the import is at the top level. That’s because names in the 1st are not yet available, because the first module is busy importing the 2nd.”

The import can easily be moved into that function, if the second module is only used in one function. By the time the import is called, the first module will have finished initializing, and the second module can do its import.

If some of the modules are platform-specific, it may also be necessary to move imports out of the top level of code. In that case, it may not even be possible to import all of the modules at the top of the file. Import the exact modules in the corresponding platform-specific code is a good option.

Updated on: 19-Sep-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started