Guidelines on importing modules in Python

Photo by EJ Li on Unsplash

Guidelines on importing modules in Python

Notes gathered from the Guidelines

Table of contents

No heading

No headings in the article.

Library support extends our tools to create pieces of software. Because of this, we no longer need to write everything from scratch. To access this set of tools, we need to import modules from Python packages. A Python package is a collection of modules that contain a set of functionalities we may deem useful for our projects.

There are many ways to import a package in Python. I compiled some notes I gathered from The PEP Standard as Google Python Style Guide for pointers to import modules in Python.


  • Imports should usually be on separate lines.

    import os
    import sys
    # not `import os, sys`
    
    • from imports may declare multiple items at once:

      from typing import Union, Optional
      
  • Imports should be grouped in the following order:

    1. Standard library imports.
    2. Related third-party imports.
    3. Local application/library-specific imports.
  • Imports are always declared at the top of the file.

  • Absolute imports are recommended.

    • They are more readable and tend to be better behaved.
    • Explicit relative import is an acceptable alternative to absolute imports, especially when dealing with complex package layouts where using absolute imports would be unnecessarily verbose.
  • Avoid wildcard imports.

    • It clutters the namespace of your code and makes it unclear which names are intended to be present.
    • It makes your code confusing and difficult to maintain.
# this will import the namespace of all items contained in the package
from [package/module] import *
# this will import a specified set of items contained in the package
from [package/module] import [item]
  • Use import statements for packages and modules only, not for individual classes or functions.
      def function(x:list) -> float:
          import numpy as np
          ...
    

References:

  1. Rossum, G.V., Warsaw, B & Coghlan, N. (2001). PEP 8 – Style Guide for Python Code. python.org/dev/peps/pep-0008.
  2. Nzomo, M. (2018). Absolute vs Relative Imports in Python. realpython.com/absolute-vs-relative-python-...
  3. Google (n.d.). Google Python Style Guide. google.github.io/styleguide/pyguide.html.