If Python were a toolbox, modules would be the individual compartments each holding tools for a specific job.
In this detailed guide, you’ll learn:
- What modules are and why they’re important
- How to use built-in modules
- The difference between
import
,from ... import
, andas
- How to create your own module from scratch
- Best practices and common pitfalls
🧠 What Are Modules?
A module is simply a Python file that contains code like variables, functions, or classes that you can reuse across other files.
Python comes with many built-in modules like:
math
(mathematical functions)random
(generate random numbers)datetime
(date and time)os
(interact with files and the operating system)
You can also create your own.
🔗 Why Use Modules?
- Avoid repeating the same code
- Organize your project into logical parts
- Keep things clean and maintainable
- Use code written by others (standard library or third-party)
🔄 How to Import a Module
✳️ Import Entire Module
Python
import math
print(math.sqrt(25)) # Output: 5.0
Access with:
module_name.function_name
🎯 Import Specific Function
Python
from math import sqrt
print(sqrt(64)) # Output: 8.0
You can use the function directly without prefixing with
math.
📛 Give a Module an Alias
Python
import datetime as dt
today = dt.date.today()
print(today)
Shortens long names, makes code more readable.
🔐 Some Common Built-in Modules
Module | Purpose | Example Use |
---|---|---|
math | Math functions | math.sqrt() , math.pi |
random | Random number generation | random.randint() , random.choice() |
datetime | Date and time handling | datetime.now() |
os | File system interaction | os.getcwd() , os.listdir() |
sys | Python runtime settings | sys.argv , sys.exit() |
statistics | Stats functions | mean() , median() |
🧪 Example: Dice Simulator with random
Python
import random
dice = random.randint(1, 6)
print("You rolled:", dice)
🔥 Creating Your Own Module
Step 1: Create a New File
Create a file called helper.py
and write:
Python
def greet(name):
return f"Hello, {name}!"
Step 2: Import and Use It
In your main script (e.g., main.py
):
Python
import helper
print(helper.greet("Ali"))
Output:
Hello, Ali!
🔎 From Your Module, Import Specific Things
Python
from helper import greet
print(greet("Fatima"))
🧱 Organizing Projects with Modules
Folder structure:
Python
myproject/
│
├── helper.py
├── math_utils.py
├── main.py
You can import like:
Python
from math_utils import multiply
Just make sure all
.py
files are in the same folder or properly packaged.
📦 Installing External Modules (Bonus Tip)
Use pip
to install 3rd-party modules:
Python
pip install requests
Then:
Python
import requests
response = requests.get("https://pyuniverse.com")
print(response.status_code)
⚠️ Common Mistakes with Modules
Mistake | Fix |
---|---|
Forgetting .py extension | Just write import mymodule , NOT import mymodule.py |
File not in the same folder | Use correct relative paths or sys.path for advanced setups |
Function not accessible | Make sure it’s not inside if __name__ == "__main__": |
Same name as built-in module | Don’t name your file math.py , random.py , etc. |