Python modules and imports: stop writing every damn thing yourself
Updated · every example run on Python 3.9 to 3.15
So far, nearly every line your programs ran was a line you typed (that from pathlib import Path last lesson was a sneak preview). That's noble, and also a shitty way to live. Python ships with a standard library of hundreds of modules, already written, already tested, already fixed by people who found the bugs before you did. Square roots, statistics, dates, files, random numbers: somebody did it, and the code is sitting on your disk right now.
A module is just a .py file. import is how one file borrows code from another. Once you know that, you can borrow from Python, from yourself, and, with pip, from strangers on the internet.
import, from and as
There are three ways to say "I want that". Here they are on one cat:
import math
from statistics import mean
import statistics as stats
cat_weights = [4200, 4500, 4100, 4400, 4350] # grams, weighed daily, cat furious
print(math.sqrt(16))
print(math.ceil(4.2))
print(mean(cat_weights))
print(stats.median(cat_weights))4.0
5
4310
4350import math gives you one name, math, and you reach inside it with a dot: math.sqrt, math.ceil. The prefix is a feature. Six months from now, math.sqrt tells you exactly where that function came from.
from statistics import mean copies just the name mean into your file, so you call it without a prefix. Handy, but it lands in the same namespace as your own variables: write mean = 0 later and Python's mean is gone from your file, no warning.
import statistics as stats imports the whole module under a shorter name. You'll see this everywhere in the wild, like import numpy as np, which is a convention, not a law. One form to avoid: from math import *, which dumps every public name the module has into your file, and then nobody, including you, can tell where anything came from.
Your own module
Any .py file in the same folder is a module you can import. Its name is the file name without .py:
# shopping.py: money tools for the shopping list
TAX_RATE = 0.08
def total(prices):
return sum(prices)
def with_tax(amount):
return round(amount * (1 + TAX_RATE), 2)import shopping
prices = [3.50, 12.00, 4.25]
subtotal = shopping.total(prices)
print("Subtotal:", subtotal)
print("With tax:", shopping.with_tax(subtotal))
print("Tax rate:", shopping.TAX_RATE)Subtotal: 19.75
With tax: 21.33
Tax rate: 0.08That's all a module is. Functions, variables, anything defined at the top level of shopping.py is reachable as shopping.something. When you import shopping, Python looks in the folder of the script you ran, then in the standard library, then in installed packages.
Three house rules. A module name has to be a valid variable name, so shopping-list.py can't be imported (the hyphen reads as a minus sign); use shopping_list.py. A __pycache__ folder will appear next to your files: that is Python saving a compiled copy to load faster next time, so ignore it. And if two of your modules import each other, you have built a loop, and a from import inside that loop can end in ImportError: cannot import name (circular import).
Who is main?
Here's the thing nobody tells you: import runs the whole file, top to bottom, the first time you import it. Every module also gets a variable called __name__ that says how it's being used. Watch both at once:
def to_fahrenheit(celsius):
return celsius * 9 / 5 + 32
print("temperature.py says its name is", __name__)
if __name__ == "__main__":
print("Running as a program: 20 C is", to_fahrenheit(20), "F")import temperature
print("main.py says its name is", __name__)
print("A healthy cat in F:", temperature.to_fahrenheit(38.5))temperature.py says its name is temperature
main.py says its name is __main__
A healthy cat in F: 101.3The first line of output came from temperature.py, during the import, because a top-level print runs whenever the file runs. Inside an imported module, __name__ is the module's own name, temperature. The file you handed to python3 gets the name __main__ instead. That's why the last line of temperature.py did nothing: the if was false, so its demo stayed quiet.
Run the module itself
Now run the same temperature.py as the program:
def to_fahrenheit(celsius):
return celsius * 9 / 5 + 32
print("temperature.py says its name is", __name__)
if __name__ == "__main__":
print("Running as a program: 20 C is", to_fahrenheit(20), "F")python3 temperature.py
temperature.py says its name is __main__
Running as a program: 20 C is 68.0 FThis time __name__ is "__main__" and the guarded line runs. That's the whole trick behind if __name__ == "__main__":. Code under it runs when the file is the program, and stays out of the way when another file imports it for its functions. Put your demo, your quick tests or the program's start there, and the module stays safe to import. Without the guard, every import temperature would print a demo nobody asked for.
Don't name your file random.py
Python checks your folder before the standard library. That's what made import shopping work, and it is also a trap. Say you're practicing random numbers, so you name your file, reasonably, random.py:
# my practice file about random numbers
print("Hello from my own random.py")import random
print(random.randint(1, 6))Hello from my own random.py
Traceback (most recent call last):
File "/home/me/project/main.py", line 3, in <module>
print(random.randint(1, 6))
^^^^^^^^^^^^^^
AttributeError: module 'random' has no attribute 'randint' (consider renaming '/home/me/project/random.py' since it has the same name as the standard library module named 'random' and prevents importing that standard library module)| Python | Prints |
|---|---|
| 3.9–3.12 | AttributeError: module 'random' has no attribute 'randint' |
| 3.13–3.15 | AttributeError: module 'random' has no attribute 'randint' (consider renaming '/home/me/project/random.py' since it has the same name as the standard library module named 'random' and prevents importing that standard library module) |
Run on CPython 3.9.6, 3.10.22, 3.11.17, 3.12.15, 3.13.17, 3.14.9 and 3.15.1, on November 11, 2026.
Python found your random.py first, ran it (hence the hello) and never looked at the real one. Your file has no randint, so you get AttributeError: module 'random' has no attribute 'randint'. Up to 3.12 that's all the error says, which has made grown adults cry. From 3.13 on, Python adds to the message: it names your file and suggests renaming it, because it shadows the standard library module. The fix is the same everywhere: rename the damn file. A leftover random.cpython-*.pyc in __pycache__ is harmless, because Python ignores a cached copy once its source is gone.
Even math.py can bite. Some builds compile math into the interpreter itself, and a built-in module is found before Python even looks in your folder, so your file loses; on other builds your file wins, exactly like here. No need to find out which kind you have: just don't name your files after standard modules.
Modules you don't have: pip and venv
The standard library is big but not infinite. Plenty of famous modules, like requests for talking to websites, are separate downloads:
import requests
print("requests version", requests.__version__)Traceback (most recent call last):
File "/home/me/project/main.py", line 1, in <module>
import requests
ModuleNotFoundError: No module named 'requests'ModuleNotFoundError: No module named means Python looked everywhere it knows and found nothing. The fix is pip, Python's package installer, which downloads packages from PyPI, the Python Package Index. But don't install into your system's Python. Make a virtual environment first: a folder with its own Python and its own packages, one per project. In the project folder:
python3 -m venv .venv
source .venv/bin/activate
python -m pip install requests
python main.py
On Windows, the second line is .venv\Scripts\activate. While it's active, your prompt shows (.venv) and python means the environment's Python; deactivate leaves it. On Debian or Ubuntu, the first line may need the python3-venv package installed first.
Why bother? Because one project wants version 2 of something and another wants version 3, and a single shared Python can only hold one of them. And because Homebrew, uv and recent Debian and Ubuntu releases refuse global installs anyway, with error: externally-managed-environment. To remember what a project needs, save the list with python -m pip freeze > requirements.txt, and rebuild it anywhere with python -m pip install -r requirements.txt. Don't commit the .venv folder itself. It's big as hell, and it's tied to the machine that made it.
Try it yourself
Write a module convert.py with a function kg_to_lb(kg) (one kilogram is 2.20462 pounds) and a __main__ guard that prints kg_to_lb(1) as a demo. Then write main.py that imports it and prints your cat's 4.5 kg in pounds, rounded to one decimal. Running main.py should not print the demo.
Show the answer
# convert.py
def kg_to_lb(kg):
return kg * 2.20462
if __name__ == "__main__":
print("1 kg is", kg_to_lb(1), "lb")
# main.py
import convert
print(round(convert.kg_to_lb(4.5), 1), "lb of cat")
python3 main.py prints 9.9 lb of cat, and python3 convert.py prints the demo instead.
Questions
What is the difference between import and from import in Python?
import math brings in the module, and you write math.sqrt. from math import sqrt brings in just that name, and you write sqrt. Both run the module the same way; only the name you get differs.
What does if name == "main" mean in Python?
__name__ is "__main__" only in the file you ran with python3. Code under that if runs when the file is the program and is skipped when another file imports it.
Why do I get ModuleNotFoundError after pip install?
Almost always because pip installed the package into a different Python than the one running your script. Activate your virtual environment, and install with python -m pip install, so the same python both installs and runs.
Do I need a virtual environment for every project?
For anything that installs packages, yes, one per project. It costs one command, and it keeps one project's packages from breaking another's.
Sources
- Modules, Python documentation
- main: top-level code environment, Python documentation
- venv: creation of virtual environments, Python documentation
- Installing Python modules, Python documentation
- What's New in Python 3.13: improved error messages, Python documentation
Read on November 11, 2026.