Introduction To Imports

Discussion about how to import modules or packages in Python.

We'll cover the following

One of the first things we learn as a beginner Python programmer is how to import other modules or packages. However, we’ve noticed that even people who have used Python casually for multiple years don’t always know how flexible Python’s importing infrastructure is. In this chapter, we will cover the following topics:

  • Regular imports
  • Using from
  • Relative imports
  • Optional imports
  • Local imports
  • import Pitfalls

Let’s talk about regular imports.

Regular import

A regular import, and quite possibly the most popular goes like this:

import sys

All we need to do is use the word import and then specify which module or package we want to actually import. The nice thing about import though is that it can also import multiple packages at once:

import os, sys, time

While this is a space-saver, it goes against the Python Style Guide’s recommendations of putting each import on its own line.

Sometimes when we import a module, we want to rename it. Python supports this quite easily:

Get hands-on with 1200+ tech skills courses.