Modules in Python — import, packages, __init__
What is a Module?
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.
Importing Modules
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
Creating Your Own Module
# mathutils.py
PI = 3.14159
def circle_area(radius: float) -> float:
"""Calculate area of a circle."""
return PI * radius ** 2
def circle_perimeter(radius: float) -> float:
"""Calculate perimeter of a circle."""
return 2 * PI * radius
def is_prime(n: int) -> bool:
"""Check if a number is prime."""
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 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
The __name__ Variable
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()
Packages
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
Useful Standard Library Modules
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']})
Level Up Your Python Skills
Master Python with these hand-picked resources
10,000+ learners
Free forever
Updated 2026
Related Python Topics