Modules & Packages
What is a Module?
A module is simply a Python file containing:
- Functions
- Variables
- Classes
- Code
Example:
math.py,random.py,os.py→ all are modules.
Why Use Modules?
- Reusable code
- Avoid writing same code again
- Makes code clean
- Easy to debug
- Increases productivity
How to Import Modules
1.Basic import
import math
print(math.sqrt(16))
2.Import with alias
import math as m
print(m.sqrt(25))
3.Import only specific items
from math import sqrt, pi
print(sqrt(81))
print(pi)
4.Import everything
from math import *
Built-in Python Modules
Important modules to remember:
| Module | Usage |
|---|---|
math |
Mathematical functions |
random |
Random numbers |
os |
File & OS operations |
sys |
System-specific info |
datetime |
Date & time |
re |
Regular expressions |
json |
JSON handling |
statistics |
Mean, median, mode |
time |
Current time, sleep() |
Examples of Built-in Modules
math module
import math
print(math.factorial(5))
print(math.pow(2, 3))
print(math.pi)
random module
import random
print(random.randint(1, 100))
print(random.choice([10, 20, 30]))
os module
import os
print(os.getcwd()) # current dir
os.mkdir("newfolder") # make folder
sys module
import sys
print(sys.version)
print(sys.argv)
datetime module
from datetime import datetime
print(datetime.now())
Creating Your Own Module
Create file: calc.py
def add(a, b):
return a + b
def sub(a, b):
return a - b
Use it in another file:
import calc
print(calc.add(10, 20))
What is a Package?
A package = collection of multiple modules inside a folder.
Example:
my_package/
init.py
add.py
subtract.py
init.py**
- Used to treat folder as a package
- Can be empty
- Or can initialize package variables
Creating a Package — Example
Folder structure:
mathpkg/
init.py
add.py
sub.py
add.py
def add(a, b):
return a + b
sub.py
def sub(a, b):
return a - b
main program
from mathpkg.add import add
from mathpkg.sub import sub
print(add(5, 3))
print(sub(5, 3))
Types of Packages
1.User-defined packages
Created by you.
2.Built-in packages
Already in Python.
3.External packages
Installed using pip:
pip install numpy
pip install requests
Installing and Using External Packages
Install:
pip install requests
Use:
import requests
res = requests.get("https://google.com")
print(res.status_code)
Virtual Environment (Very Important for DevOps & Development)
A virtual environment isolates packages for each project.
Create Virtual Environment
python -m venv myenv
Activate Environment
Windows:
myenv\Scripts\activate
macOS/Linux:
source myenv/bin/activate
Deactivate
deactivate
Install packages inside it
pip install flask
dir() and help() Functions
List all methods in module:
import math
print(dir(math))
Documentation:
help(math)
Top comments (0)