⬅ Previous Next ➡

Modules and Packages

Packages (Overview)
  • Module = a single Python file (.py).
  • Package = a folder that contains multiple modules.
  • Packages help organize big projects in a clean structure.
  • Traditionally, package folder contains __init__.py (still commonly used).
project/
    main.py
    mypkg/
        __init__.py
        calc.py
        utils.py
Creating and Using a Package (Example)
  • Create a folder (package) and add Python modules inside it.
  • Add __init__.py file to mark it as a package (recommended).
File: mypkg/calc.py
def add(a, b):
    return a + b
File: main.py
from mypkg.calc import add

print(add(10, 20))
Importing Modules (Ways to Import)
  • import module
  • import module as alias
  • from module import name
  • from module import * (not recommended)
import math
print(math.sqrt(25))

import math as m
print(m.pi)

from math import factorial
print(factorial(5))
Built-in Packages / Libraries (Examples)
  • os → file/folder & OS tasks
  • sys → system info, argv
  • math → maths functions
  • random → random values
  • datetime → date/time
  • json → JSON handling
  • csv → CSV handling
import os
import datetime

print(os.getcwd())
print(datetime.datetime.now())
Virtual Environment (Why and What)
  • Virtual environment keeps project dependencies separate.
  • Prevents version conflicts between projects.
  • Each project can have its own libraries and versions.
# Example
Project A uses Django 4
Project B uses Django 5
Virtual env keeps both separate
Create and Activate Virtual Environment (venv)
  • Create virtual env using python -m venv.
  • Activate it before installing packages.
Windows:
python -m venv venv
venv\Scripts\activate
Linux / macOS:
python3 -m venv venv
source venv/bin/activate
Deactivate:
deactivate
Installing External Libraries (pip)
  • pip is Python package installer.
  • Install packages after activating virtual environment.
  • Use pip list to see installed packages.
pip install requests
pip install flask
pip list
Using Installed Library (Example: requests)
  • After installation, import and use the library.
import requests

res = requests.get("https://example.com")
print(res.status_code)
print(res.text[:100])
Freeze Requirements and Reinstall
  • requirements.txt stores all dependency versions.
  • Useful to run same project on another system.
pip freeze > requirements.txt
pip install -r requirements.txt
⬅ Previous Next ➡