Ad – 728Γ—90
πŸ”§ Intermediate

Python Modules – import, from, as, and Built-in Modules

A module is a Python file containing code β€” functions, classes, and variables β€” that can be imported and reused in other programs. Modules prevent code duplication, organise large projects, and give you access to Python's massive standard library.

⏱️ 20 min read🎯 IntermediateπŸ“… Updated 2026

Importing Modules

Use import to load a module. Access its contents with dot notation.

Python
import math
import random

print(math.pi)           # 3.141592653589793
print(math.sqrt(25))     # 5.0
print(random.randint(1, 10))  # Random number 1-10
β–Ά Output
3.141592653589793 5.0 7

from … import – Import Specific Names

Import only what you need. No module prefix required after.

Python
from math import sqrt, pi, ceil
from random import choice, shuffle

print(sqrt(16))   # 4.0 β€” no "math." prefix needed
print(ceil(4.2))  # 5

fruits = ["apple", "banana", "cherry"]
shuffle(fruits)
print(choice(fruits))
β–Ά Output
4.0 5 apple

Aliasing with as

Give modules or names shorter aliases.

Python
import numpy as np          # Convention: np
import pandas as pd          # Convention: pd
from datetime import datetime as dt

# Now use the alias
print(dt.now().year)
β–Ά Output
2024
Ad – 336Γ—280

Creating Your Own Module

Any .py file is a module. Create mymath.py then import it.

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

def multiply(a, b):
    return a * b

PI = 3.14159

# --- in main.py ---
import mymath

print(mymath.add(3, 4))       # 7
print(mymath.PI)              # 3.14159
β–Ά Output
7 3.14159

Essential Standard Library Modules

Python ships with a huge standard library. Key modules: os (file system), sys (interpreter), datetime (dates), json (JSON), re (regex), pathlib (paths), collections (specialised containers), itertools (iterators), functools (higher-order functions).

Python
import os
import sys
from pathlib import Path

print(os.getcwd())           # Current directory
print(sys.version)           # Python version
print(Path.home())           # Home directory

The __name__ == "__main__" Guard

Prevents module-level code from running when the file is imported.

Python
# utils.py
def helper():
    return "I help!"

if __name__ == "__main__":
    # This runs only when utils.py is run directly
    # NOT when it is imported
    print(helper())
πŸ’‘
Tip

Always use this guard in scripts that also provide importable functions.