Modules and imports

Topic 1 of 3 in Modules and packages7 min readBeginnerFree course

Overview

As programs grow, one long file becomes hard to manage. Modules let you split code across files and reuse it — and they’re also how you use Python’s standard library and the hundreds of thousands of packages other people have written. Every time you’ve written import math, you’ve used a module.

A module is just a .py file

Any Python file is a module. Suppose you have:

Python
# textutils.py
VOWELS = "aeiou"

def count_vowels(text):
    return sum(1 for ch in text.lower() if ch in VOWELS)

Another file in the same folder can use it:

Python
# main.py
import textutils

print(textutils.count_vowels("banana"))   # 3
print(textutils.VOWELS)                   # aeiou

import textutils runs textutils.py and creates a module object named textutils; everything defined at its top level becomes an attribute: textutils.count_vowels, textutils.VOWELS.

Import styles

Python
import math                         # use as math.sqrt(2)
from math import sqrt, pi           # use as sqrt(2), pi
import statistics as stats          # use as stats.mean(...)
from datetime import date as Date   # rename a single name
Style Pros Cons
import module clear where every name comes from longer to type
from module import name short can clash with your own names
import module as alias short, still clear readers must know the alias (common ones: np, pd)

Avoid from module import *. It dumps every name into your file, so readers can’t tell where anything comes from, and names can silently overwrite each other.

Put imports at the top of the file, standard library first, then installed packages, then your own modules.

How Python finds a module

How import finds a module. main.py contains import math, from pathlib import Path, import helpers and import requests. Python looks in: 1, the script’s own folder — helpers.py next to main.py; 2, the standard library — math, pathlib, json, random…; 3, installed packages in site-packages — requests, pytest…. Found nowhere? ModuleNotFoundError: No module named ‘requests’ — fix with pip install requests in your venv. A module runs once, the first time it is imported; later imports reuse it. Never name your own file after a module you import (random.py, json.py…) — yours would be found first.

Python searches, in order:

  1. the folder of the script you ran;
  2. the standard library;
  3. installed packages (the site-packages folder of the current environment).

If it finds nothing:

Text
ModuleNotFoundError: No module named 'requests'

— usually meaning the package isn’t installed in the environment you’re running (Virtual environments and packages).

The shadowing trap

Because your own folder comes first, a file called random.py in your project hides the real random module. Then import random imports your file, and you get baffling errors like AttributeError: module 'random' has no attribute 'randint'. Recent Python versions add a hint — “consider renaming … since it has the same name as the standard library module” — but the fix is the same: never name your files random.py, json.py, math.py, email.py, test.py and so on.

Modules run once

The first import of a module runs its code; later imports anywhere in the program reuse the same module object. So module-level code should mostly define things (functions, classes, constants) rather than do things.

if __name__ == "__main__":

Every module has a variable __name__. When you run a file directly, Python sets its __name__ to "__main__"; when the file is imported, __name__ is the module’s name.

That lets one file be both a reusable module and a runnable script:

Python
# textutils.py
def count_vowels(text):
    ...

if __name__ == "__main__":
    # only when run as: python textutils.py
    print(count_vowels("banana"))

python textutils.py runs the block; import textutils doesn’t. A common layout for scripts is:

Python
def main():
    ...

if __name__ == "__main__":
    main()

Packages

A package is a folder of modules. Imports use dotted names:

Text
shop/
├── __init__.py
├── cart.py
└── payments/
    ├── __init__.py
    └── card.py
Python
from shop.cart import Cart
from shop.payments import card
import shop.payments.card

The __init__.py file marks the folder as a regular package (it’s often empty, but code in it runs when the package is imported). Inside a package, modules can import each other with relative imports: from .cart import Cart or from ..utils import slugify.

You can run a module inside a package with python -m shop.cart. The -m flag runs a module by name — which is also how you’ll run tools: python -m pip, python -m venv, python -m pytest.

Exploring a module

Python
import textutils
dir(textutils)            # list the names it defines
help(textutils)           # its docstrings
textutils.__file__        # where the file is

Remember: one file = one module; import at the top; never shadow standard-library names; and guard script code with if __name__ == "__main__":.

Exercise

Build your own module

Create two files in the same folder. textutils.py contains a constant VOWELS = "aeiou", a function count_vowels(text) and a function shout(text) that returns the text upper-cased with ! added; at the bottom, an if __name__ == "__main__": block prints a quick self-test. main.py imports the module in two different styles and prints count_vowels("Programming in Python"), shout("hello") and the module’s __name__. Run both files and notice that the self-test only appears when you run textutils.py directly.

Python
# ---- textutils.py ----
VOWELS = "aeiou"


def count_vowels(text):
    ...


def shout(text):
    ...


# ---- main.py ----
# import textutils, and also import shout directly

Summary

  • Every .py file is a module; import name runs it once and gives access to its contents as name.thing.
  • from module import thing imports specific names; import module as alias shortens long names; avoid from module import *.
  • Python searches the script’s folder, then the standard library, then installed packages — so never name your file after a module you use.
  • if __name__ == "__main__": runs code only when the file is executed directly, not when it’s imported.
  • A package is a folder of modules; import from it with dotted names like from shop.cart import Cart.