A Beginner’s Guide to Importing in Python

Learn to use the ‘import’, ‘from’, and ‘as’ commands

Jonathan Hsu
Code 85
Published in
3 min readApr 17, 2020

--

Importing modules is a critical skill when learning Python. To keep the language lightweight and fast, only a small core is available by default in any given Python script — you as the author are expected to then import whatever else is needed.

There are three main commands when adding modules to your Python code: import, from, and as.

We’ll go over each of these, but first let’s define what it is we’re actually importing.

What Can You Import?

The terminology can get confusing, especially when learning from multiple sources, so here’s a quick list of what can be imported and what they’re called.

  • Module: simply a file with a .py extension.
  • Package: a directory containing an __init__.py file and normally other modules.
  • Built-in Module: A module that is natively installed with Python.
  • Object: Anything inside a module/package that can be referenced such as a class, function, or variable.

Don’t get too caught up in the terminology. Just know that we’ll predominately be importing built-in modules or downloaded packages. Since object is such a multipurpose term, I’ll refer to them as components.

To download and install packages, use pip. This command line tool installs publicly available Python packages. For the examples below, we’ll only use built-in modules to ensure you can follow along.

How To Import in Python

Okay, now for the good stuff.

As mentioned earlier, there are three commands that can be used when loading modules into your code. Of the three, only import is absolutely required; the other two are optional depending on circumstance.

We’ll start with the simplest command, importing an entire module.

import mathprint(math.ceil(3.4)) # 4
print(math.floor(3.4)) # 3

Just the command import and the module name? Super easy. Remember, if you’re importing a module that is not native to Python core installation…

--

--