Importing Modules
Use import to load a module. Access its contents with dot notation.
import math
import random
print(math.pi) # 3.141592653589793
print(math.sqrt(25)) # 5.0
print(random.randint(1, 10)) # Random number 1-10from … import – Import Specific Names
Import only what you need. No module prefix required after.
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))Aliasing with as
Give modules or names shorter aliases.
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)Creating Your Own Module
Any .py file is a module. Create mymath.py then import it.
# 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.14159Essential 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).
import os
import sys
from pathlib import Path
print(os.getcwd()) # Current directory
print(sys.version) # Python version
print(Path.home()) # Home directoryThe __name__ == "__main__" Guard
Prevents module-level code from running when the file is imported.
# 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())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:
- Import the
mathmodule and usemath.sqrt. - Use
from random import randintto import a single name. - Alias a module, e.g.
import datetime as dt. - 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
.pyfile containing reusable code. import modulebrings in the whole module;from module import nameimports specific names.- Use
asto give a module or name a shorter alias. - Any
.pyfile 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 xandfrom x import y? - What does
import x as ydo? - 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?
Related Topics
FAQ
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.
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.
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.
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.

