Advertisement
🔧 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
Advertisement

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.

How import Really Works

A module is just a .py file. The first time you import it, Python runs the whole file top to bottom, then caches the result in sys.modules. Every later import of the same name reuses that cache — the file executes only once per program.

import math          # runs math once, binds name `math`
from math import pi   # runs math (if not cached), binds only `pi`
import numpy as np    # alias

The __name__ == "__main__" guard

Because import runs the file, any top-level code fires on import too. Wrap "run only when executed directly" code in the guard so importing your module doesn't trigger it:

def main():
    print("running the app")

if __name__ == "__main__":   # True only when `python file.py`
    main()                   # skipped when imported elsewhere

Circular imports: if A imports B and B imports A, one gets a half-built module and you hit ImportError or missing attributes. Fixes: move the import inside the function that needs it, or restructure so the shared code lives in a third module both import.

🏋️ Practical Exercise

Practice importing and creating modules:

  1. Import the math module and use math.sqrt.
  2. Use from random import randint to import a single name.
  3. Alias a module, e.g. import datetime as dt.
  4. Create your own module file and import a function from it into another script.

🔥 Challenge Exercise

Create a small reusable module mymath.py with a few functions (e.g. is_prime, factorial) and a quick self-test under if __name__ == "__main__":. Import it into a separate main.py and use its functions. Demonstrate that the self-test runs when you execute mymath.py directly but NOT when it is imported. Bonus: explore three standard-library modules you have not used before.

📋 Summary

  • A module is simply a .py file containing reusable code.
  • import module brings in the whole module; from module import name imports specific names.
  • Use as to give a module or name a shorter alias.
  • Any .py file you write can be imported as a module.
  • The if __name__ == "__main__": guard lets a file act as both a script and an importable module.
  • Python searches sys.path (current dir, installed packages, standard library) to locate modules.

Interview Questions on Modules

  • What is a module in Python?
  • What is the difference between import x and from x import y?
  • What does import x as y do?
  • What is the purpose of the if __name__ == "__main__": guard?
  • How does Python find modules to import (the module search path)?
  • What is the difference between a module and a package?
  • Why is from module import * discouraged?

FAQ

What does if __name__ == "__main__": do? +

When a file runs directly, Python sets its __name__ to "__main__"; when it is imported, __name__ is the module’s name. The guard runs code (like tests or a CLI entry point) only when executed directly, not on import.

What is the difference between a module and a package? +

A module is a single .py file. A package is a directory of modules (traditionally containing an __init__.py) that groups related modules under one namespace.

Why is from module import * discouraged? +

It dumps every public name into your namespace, which can silently overwrite existing names and makes it unclear where a name came from. Import only what you need, or import the module and use its prefix.

How does Python know where to find a module? +

It searches the directories in sys.path, which includes the script’s directory, the PYTHONPATH environment variable, and installed package locations. The first match wins.