</>
Skip to content
Python lessons (29/45)

Python — Modules

A module is just a .py file

Split code into files and pull in what you need:

# math_utils.py
def add(a, b):
    return a + b

PI = 3.14159
# app.py
import math_utils

math_utils.add(2, 3)      # 5
print(math_utils.PI)

The four import styles

import math                       # use math.sqrt(9)
import math as m                  # alias: m.sqrt(9)
from math import sqrt             # call sqrt(9) directly
from math import sqrt, pi         # multiple names
from math import *                # everything (avoid — pollutes namespace!)

Prefer import module or explicit from … import name. Star imports make "where did this come from?" unanswerable.

Your own package = a folder of modules

myapp/
├── main.py
└── shop/
    ├── __init__.py        ← marks it a package (may be empty)
    ├── cart.py
    └── pricing.py
from shop.cart import add_item
from shop import pricing

Dots walk folders. __init__.py can also re-export for shorter imports.

__name__ == "__main__" — dual-purpose files

A file that's both importable AND runnable:

# converter.py
def c_to_f(c): return c * 9 / 5 + 32

if __name__ == "__main__":
    # runs ONLY when executed directly: python converter.py
    print(c_to_f(float(input("°C? "))))

When another file imports converter, the block is skipped — no surprise prompts on import.

Standard library — batteries included

ModuleSuperpower
randomrandint, choice, shuffle
datetimedates, times, deltas
jsonparse/emit JSON
os / pathlibfiles, paths
mathfloor, ceil, sqrt, pi
collectionsCounter, defaultdict, deque
itertoolsiteration superpowers
import random
random.randint(1, 6)          # dice
random.choice(["a", "b"])

from collections import Counter
Counter("mississippi").most_common(2)   # [('s',4),('i',4)]

Third-party modules via pip

pip install requests pandas
import requests            # now available everywhere in your project

Best practice: virtual environments keep each project's packages isolated (python -m venv .venv). Full PIP lesson coming.

Gotchas

  1. Don't name files after stdlib modules — random.py shadows the real one and breaks import random
  2. Circular imports (a imports b imports a) crash — extract shared code to a third module
  3. Imports run module code ONCE per session; re-importing reuses the cached module

Mini Practice

  1. Create greet.py with a function; import it from app.py.
  2. Try all four import styles on one module.
  3. Build a two-module package folder with init.py.
  4. Add the if name guard; prove both behaviors.
  5. Counter-ify a paragraph with collections.Counter.

Next: dates →

Related Topics

Frequently Asked Questions about Modules

What is Modules in Python?

Modules is a fundamental concept in Python. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Modules?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Modules.

Why is Modules important in Python?

Modules is essential for Python development. Understanding this concept will help you write better code and solve real-world problems more effectively.