Skip to main content

06.1 - Modules & Imports

Theory 20 min Intermediate

What is a Module?

A module is any Python file (.py). When you import it, Python executes it and makes its contents available.

# math_utils.py
PI = 3.14159265

def circle_area(radius):
return PI * radius ** 2

def circle_perimeter(radius):
return 2 * PI * radius
# main.py — importing the module
import math_utils

math_utils.circle_area(5) # 78.54...
math_utils.PI # 3.14159265

Import Styles

# 1. Import the whole module
import math
math.sqrt(16) # 4.0
math.pi # 3.14159...

# 2. Import specific names
from math import sqrt, pi
sqrt(16) # 4.0 (no prefix needed)

# 3. Import with alias
import numpy as np
from datetime import datetime as dt

# 4. Import all (avoid!)
from math import * # pollutes namespace
StyleWhen to use
import moduleWhen you use many things from the module
from module import nameWhen you only need a few specific names
import module as aliasFor long names (numpy as np)
from module import *Almost never — pollutes namespace

The Standard Library

Python ships with an enormous standard library — "batteries included":

ModulePurpose
osOS interface — paths, env vars, processes
sysPython runtime — argv, path, exit
pathlibObject-oriented filesystem paths
reRegular expressions
jsonJSON encode/decode
csvCSV read/write
datetimeDates and times
collectionsSpecialized containers
itertoolsIterator tools
functoolsHigher-order function tools
mathMathematical functions
randomRandom number generation
hashlibCryptographic hashes
loggingApplication logging
unittestUnit testing
argparseCLI argument parsing

How Python Finds Modules

Python searches for modules in this order:

  1. Current directory (or script's directory)
  2. Directories in PYTHONPATH environment variable
  3. Standard library
  4. Site-packages (installed packages)
import sys
print(sys.path) # Shows the search path

__all__ — Public API

__all__ defines which names are exported when someone does from module import *:

# mymodule.py
__all__ = ["public_func", "PublicClass"]

def public_func():
return "I'm public"

def _private_func(): # not in __all__
return "I'm private"

class PublicClass:
pass

if __name__ == "__main__":

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

def subtract(a, b):
return a - b

if __name__ == "__main__":
# This only runs when utils.py is executed directly
# NOT when it's imported
print(add(10, 5)) # 15
print(subtract(10, 5)) # 5

Lazy Imports and Performance

# Import heavy modules only when needed
def parse_yaml(data):
import yaml # imported only when function is called
return yaml.safe_load(data)

Key Vocabulary

TermDefinition
ModuleA .py file — the basic unit of code organization
PackageA directory containing __init__.py and multiple modules
sys.pathList of directories Python searches for modules
__name__"__main__" when run directly, module name when imported
__all__List of public names exported from a module
AliasShort name for a module: import numpy as np
Standard libraryBuilt-in modules shipped with Python

Summary

  • Every .py file is a module — import with import name or from name import x
  • Prefer import module for multiple uses, from module import func for specific items
  • Avoid from module import * — it pollutes the namespace
  • __all__ defines the public API of a module
  • if __name__ == "__main__": separates runnable code from importable code