A module is a Python file that can hold functions, classes, constants, and runnable code.
Imports let one file reuse names from another file, which keeps programs organized as they grow.
Good module design keeps side effects small, gives files clear names, and avoids circular imports.
A module is a Python file (.py) containing functions, classes, and variables that you can reuse in other files. Python has a huge standard library of built-in modules, plus thousands of third-party packages.
import math # import entire module
import math as m # import with alias
from math import sqrt, pi # import specific names
from math import * # import everything (avoid this)
# Using the module
print(math.sqrt(16)) # 4.0
print(m.pi) # 3.141592653589793
print(sqrt(25)) # 5.0
print(pi) # 3.141592653589793
# Common standard library modules
import os
import sys
import json
import datetime
import random
import re
import collections
import itertools
import functools
# mathutils.py
PI = 3.14159
def circle_area(radius: float) -> float:
"""Return the area of a circle."""
return PI * radius ** 2
def circle_perimeter(radius: float) -> float:
"""Return the perimeter of a circle."""
return 2 * PI * radius
def is_prime(number: int) -> bool:
"""Return whether number is prime."""
if number < 2:
return False
for divisor in range(2, int(number ** 0.5) + 1):
if number % divisor == 0:
return False
return True
# main.py - in the same directory
import mathutils
from mathutils import is_prime
print(mathutils.circle_area(5)) # 78.53975
print(mathutils.circle_perimeter(5)) # 31.4159
print(is_prime(17)) # True
print(is_prime(20)) # False
Every module has a __name__ variable. When run directly, it equals "__main__". When imported, it equals the module's filename.
def greet(name):
return f"Hello, {name}!"
def main():
print(greet("World"))
# This block only runs when the file is executed directly
# NOT when it's imported by another module
if __name__ == "__main__":
main()
A package is a directory containing multiple modules and an __init__.py file.
mypackage/
|-- __init__.py # makes it a package
|-- math_utils.py
|-- string_utils.py
`-- io/
|-- __init__.py
`-- file_reader.py
# Importing from a package
from mypackage import math_utils
from mypackage.string_utils import capitalize
from mypackage.io.file_reader import read_csv
import os
import random
import json
from collections import Counter, defaultdict
# os - file system operations
print(os.getcwd()) # current directory
print(os.path.join("folder", "file")) # folder/file
os.makedirs("new_dir", exist_ok=True)
# random - random numbers
print(random.randint(1, 10)) # random int 1-10
print(random.choice(["a", "b", "c"])) # random item
items = [1, 2, 3, 4, 5]
random.shuffle(items)
print(items)
# json - encode/decode JSON
data = {"name": "Alice", "age": 25}
json_str = json.dumps(data, indent=2)
print(json_str)
parsed = json.loads(json_str)
print(parsed["name"]) # Alice
# collections.Counter
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
count = Counter(words)
print(count) # Counter({'apple': 3, 'banana': 2, 'cherry': 1})
print(count.most_common(2)) # [('apple', 3), ('banana', 2)]
# collections.defaultdict
dd = defaultdict(list)
dd["fruits"].append("apple")
dd["fruits"].append("banana")
print(dd) # defaultdict(<class 'list'>, {'fruits': ['apple', 'banana']})
0 of 2 checked
Try this next
0 of 2 completed
A module is usually one .py file. A package is a folder of modules that Python can import as a group.
Python executes a module the first time it imports it. Keep direct script actions behind if __name__ == "__main__".
Move shared code to a third module, reduce import-time work, or import inside a function only when needed.
Explore 500+ free tutorials across 20+ languages and frameworks.