LESSON · 1 OF 5

import, from, and as

import, from, and as

A module is a file of Python code that someone else wrote, full of functions and values you can use. The import statement pulls a module into your script so you can reach what's inside it. Python ships with hundreds of modules, and this is how you get at them.

import the whole module

The plain form loads a module and gives you access through its name:

python
import os

print(os.getcwd())

After import os, everything the os module provides is available under the os. prefix. os.getcwd() calls the getcwd function that lives inside os. The prefix makes it obvious where the function came from, which helps when a script imports several modules.

from ... import a specific name

When you only want one or two things from a module, import them directly so you can use them without the prefix:

python
from os import getcwd

print(getcwd())

Now getcwd is available on its own. This reads well when you use a name often, but too many bare imports make it hard to tell which module each one came from.

as gives it a shorter name

as renames what you import, usually to shorten a long module name or avoid a clash:

python
import subprocess as sp

sp.run(["ls"])

You'll see this constantly in real code, where libraries have a conventional short alias.

Where imports go

Put imports at the top of your script, before any other code. Python runs them once, and every function below can use what they brought in.

What this node covers

  • import module loads a module, used through the module. prefix.
  • from module import name pulls one name in without the prefix.
  • import module as alias renames it.
Spin up a fresh environment and practice live.
python-devops · fresh machine · ready in under a minute