Common Python Libraries
Numerous libraries extend Python’s capabilities, making it a versatile language for various applications. Here are some of the most common Python libraries you should know about:
These libraries appear in real projects, interviews, and daily development work.
| Library | Main Use |
|---|---|
os | OS operations, file system tasks, environment variables |
sys | Python runtime info, command-line arguments, exits |
typing | Type hints for better code clarity, IDE support, and error catching |
json | Convert Python data to/from JSON |
csv | Read and write CSV files |
sqlite3 | Lightweight embedded SQL database |
requests | HTTP client for APIs and web calls |
datetime | Dates, times, formatting, arithmetic |
pathlib | Modern and clean path/file handling |
python-dotenv | Load environment variables from .env |
logging | Structured application logs |
flask | Build simple web applications and APIs |
tkinter | Build desktop GUI applications |
os - File System and OS Utilities
Section titled “os - File System and OS Utilities”Use os when you need low-level operating system interaction.
Common use cases
Section titled “Common use cases”- Working directories and files
- Environment variables
- Process-related values
Frequently used functions
Section titled “Frequently used functions”os.getcwd()-> current working directoryos.listdir(path)-> list directory contentsos.makedirs(path, exist_ok=True)-> create folders safelyos.remove(path)-> delete fileos.environ.get("KEY")-> read environment variable
import os
print("Current directory:", os.getcwd())
os.makedirs("data/output", exist_ok=True)
api_key = os.environ.get("API_KEY")print("API key loaded:", bool(api_key))Best practices
Section titled “Best practices”- Prefer
pathlibfor path operations in new code - Use
os.environ.get()instead of direct indexing to avoidKeyError
sys - Python Runtime and CLI Arguments
Section titled “sys - Python Runtime and CLI Arguments”Use sys for runtime info and command-line scripts.
Common use cases
Section titled “Common use cases”- Read script arguments
- Exit program with status code
- Inspect Python path/version
Frequently used attributes and functions
Section titled “Frequently used attributes and functions”sys.argv-> command-line argumentssys.exit(code)-> terminate programsys.version-> Python version stringsys.path-> import search paths
import sys
if len(sys.argv) < 2: print("Usage: python app.py <name>") sys.exit(1)
name = sys.argv[1]print(f"Hello, {name}")Best practices
Section titled “Best practices”- Validate argument count and format before use
- Return non-zero exit codes for failures in automation scripts
typing - Type Hints for Better Code
Section titled “typing - Type Hints for Better Code”Use typing to add type information to your code. Type hints clarify the expected data types for function arguments and return values.
Why use typing?
Section titled “Why use typing?”- Catches errors early → IDEs and type checkers find bugs before runtime
- Self-documenting code → Other developers understand what types are expected without reading docs
- Better IDE support → Autocomplete and type checking work better
- Enables static analysis → Tools like
mypyvalidate code without running it - Improves maintainability → Code is easier to refactor when types are explicit
Common type hints
Section titled “Common type hints”int,str,float,bool-> basic typesList[int]-> list of integersDict[str, int]-> dictionary with string keys and integer valuesTuple[str, int]-> tuple with specific typesOptional[str]-> string or NoneUnion[str, int]-> can be string or integerCallable[[int, str], bool]-> function taking int + str, returning boolAny-> any type (use sparingly)
Basic function example
Section titled “Basic function example”from typing import List, Dict, Optional
def greet(name: str, age: int) -> str: """Greet a person with their age.""" return f"Hello {name}, you are {age} years old"
def find_user(user_id: int) -> Optional[Dict[str, str]]: """Return user data or None if not found.""" users = {1: {"name": "Alice"}, 2: {"name": "Bob"}} return users.get(user_id)
def process_scores(scores: List[int]) -> float: """Calculate average score.""" return sum(scores) / len(scores) if scores else 0.0
# Function callsprint(greet("Sahil", 25))print(find_user(1))print(process_scores([85, 90, 78]))Complex types example
Section titled “Complex types example”from typing import List, Dict, Tuple, Union, Callable
# A list of dictionaries (common with API responses)users: List[Dict[str, Union[str, int]]] = [ {"name": "Alice", "age": 25}, {"name": "Bob", "age": 30},]
# Tuple with fixed typescoordinates: Tuple[float, float] = (10.5, 20.3)
# Callback function typeprocess_callback: Callable[[str], int] = lambda x: len(x)
# Optional values (might be None)api_key: Optional[str] = NoneClass type hints
Section titled “Class type hints”from typing import List, Optional
class User: def __init__(self, name: str, email: str) -> None: self.name: str = name self.email: str = email self.posts: List[str] = []
def add_post(self, title: str) -> None: """Add a post to user's list.""" self.posts.append(title)
def get_email(self) -> str: return self.email
user = User("Sahil", "sahil@example.com")user.add_post("My First Post")Validate types with mypy
Section titled “Validate types with mypy”Install mypy to check types without running code:
uv add --dev mypyuv run mypy your_file.pymypy catches type errors:
# This will be flagged by mypyname: str = "Alice"age: int = name # Error: incompatible types (str vs int)Best practices
Section titled “Best practices”- Add type hints to function parameters and return values
- Use
Optional[T]for values that might beNone, notOptional[Union[T, None]] - Use
List,Dict,Tuplefromtypingfor Python < 3.9, or use built-inlist,dictfor Python 3.9+ - Keep types simple and readable; avoid overly complex unions
- Type hints are optional but highly recommended for production code
json - Serialization and API Data
Section titled “json - Serialization and API Data”json converts between Python objects and JSON text.
Important methods
Section titled “Important methods”json.dumps(obj)-> Python object to JSON stringjson.loads(text)-> JSON string to Python objectjson.dump(obj, file)-> write JSON to filejson.load(file)-> read JSON from file
import json
user = {"name": "Sahil", "active": True, "score": 91}
# To stringpayload = json.dumps(user, indent=2)print(payload)
# To filewith open("user.json", "w", encoding="utf-8") as f: json.dump(user, f, indent=2)Best practices
Section titled “Best practices”- Use
indent=2for readable files - Use
ensure_ascii=Falsewhen storing Unicode text - JSON supports basic types only (dict, list, str, int, float, bool, null)
csv - Read and Write CSV Files
Section titled “csv - Read and Write CSV Files”csv is useful for tabular data exchange.
Core tools
Section titled “Core tools”csv.reader()/csv.writer()for row-based accesscsv.DictReader()/csv.DictWriter()for column-name access
import csv
rows = [ {"name": "A", "marks": 85}, {"name": "B", "marks": 92},]
with open("marks.csv", "w", newline="", encoding="utf-8") as f: writer = csv.DictWriter(f, fieldnames=["name", "marks"]) writer.writeheader() writer.writerows(rows)
with open("marks.csv", "r", newline="", encoding="utf-8") as f: reader = csv.DictReader(f) for row in reader: print(row["name"], row["marks"])Best practices
Section titled “Best practices”- Always use
newline=""on Windows to avoid blank lines - Prefer
DictReaderandDictWriterfor clearer code
sqlite3 - Lightweight Database Basics
Section titled “sqlite3 - Lightweight Database Basics”sqlite3 provides a local SQL database stored in a single file.
When to use
Section titled “When to use”- Small to medium local apps
- Prototypes and learning SQL
- Desktop or offline tools
Core workflow
Section titled “Core workflow”- Connect
- Create cursor
- Execute SQL
- Commit (for writes)
- Close connection
import sqlite3
conn = sqlite3.connect("app.db")cur = conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)")cur.execute("INSERT INTO users (name) VALUES (?)", ("Sahil",))
conn.commit()
cur.execute("SELECT id, name FROM users")print(cur.fetchall())
conn.close()Best practices
Section titled “Best practices”- Use parameterized queries (
?) to prevent SQL injection - Wrap DB operations with try/except in production code
requests - HTTP Requests Made Simple
Section titled “requests - HTTP Requests Made Simple”requests is the most popular Python library for making HTTP calls.
Install
Section titled “Install”uv add requestsCommon methods
Section titled “Common methods”requests.get(url)requests.post(url, json=data)response.status_coderesponse.json()response.raise_for_status()
import requests
url = "https://jsonplaceholder.typicode.com/todos/1"response = requests.get(url, timeout=10)response.raise_for_status()
data = response.json()print(data["title"])Best practices
Section titled “Best practices”- Always set
timeout - Use
raise_for_status()to catch HTTP errors early - Use
Session()for repeated calls to the same host
datetime - Date and Time Handling
Section titled “datetime - Date and Time Handling”Use datetime for timestamps, formatting, and date arithmetic.
Common operations
Section titled “Common operations”- Current date/time:
datetime.now() - Parse string:
datetime.strptime() - Format output:
datetime.strftime() - Add/subtract using
timedelta
from datetime import datetime, timedelta
now = datetime.now()print("Now:", now.strftime("%Y-%m-%d %H:%M:%S"))
deadline = now + timedelta(days=7)print("Deadline:", deadline.strftime("%Y-%m-%d"))Best practices
Section titled “Best practices”- Store times in UTC for backend systems
- Convert to local timezone only for display
pathlib - Modern Path Handling
Section titled “pathlib - Modern Path Handling”pathlib gives object-oriented path operations and cleaner code than manual string paths.
Common operations
Section titled “Common operations”- Build paths with
/ - Check file existence
- Read and write text quickly
- Iterate directory contents
from pathlib import Path
base = Path("data")base.mkdir(exist_ok=True)
file_path = base / "notes.txt"file_path.write_text("Hello from pathlib\n", encoding="utf-8")
print(file_path.read_text(encoding="utf-8"))Best practices
Section titled “Best practices”- Prefer
Pathover manual string concatenation - Keep file encoding explicit (
utf-8)
python-dotenv - Environment Variables from .env
Section titled “python-dotenv - Environment Variables from .env”python-dotenv loads variables from a .env file into environment variables.
Install
Section titled “Install”uv add python-dotenvExample
Section titled “Example”.env
API_KEY=your_secret_keyDEBUG=trueapp.py
from dotenv import load_dotenvimport os
load_dotenv()
api_key = os.getenv("API_KEY")debug = os.getenv("DEBUG", "false").lower() == "true"
print("Key exists:", bool(api_key))print("Debug:", debug)Best practices
Section titled “Best practices”- Do not commit
.envto version control - Keep secrets in environment variables, not hardcoded in source code
logging - Professional Logging Basics
Section titled “logging - Professional Logging Basics”Use logging instead of print() for production-grade applications.
Log levels
Section titled “Log levels”DEBUG-> detailed troubleshooting infoINFO-> normal eventsWARNING-> unexpected but manageable eventERROR-> operation failedCRITICAL-> severe failure
import logging
logging.basicConfig( level=logging.INFO, format="%(asctime)s | %(levelname)s | %(message)s")
logging.info("Application started")logging.warning("Cache miss for user profile")logging.error("Database connection failed")Best practices
Section titled “Best practices”- Include timestamps and level in format
- Use
logger.exception("...")insideexceptblocks for traceback - Write logs to file in long-running apps
flask - Basic Web Application Framework
Section titled “flask - Basic Web Application Framework”flask is a lightweight framework for building web apps and APIs.
It is beginner-friendly and great for learning backend development.
Install
Section titled “Install”uv add flaskCore concepts
Section titled “Core concepts”Flask(__name__)creates the app@app.route("/")maps URLs to functionsrequestreads input from browser/clientjsonify()returns JSON responses
Basic app example
Section titled “Basic app example”from flask import Flask, jsonify
app = Flask(__name__)
@app.route("/")def home(): return "Hello, Flask!"
@app.route("/api/health")def health(): return jsonify({"status": "ok"})
if __name__ == "__main__": app.run(debug=True)Run the app
Section titled “Run the app”python app.pyThen open http://127.0.0.1:5000 in your browser.
Request flow
Section titled “Request flow”Best practices
Section titled “Best practices”- Keep routes small and move business logic to separate functions/modules
- Use
debug=Trueonly in development - Validate user input before processing
tkinter - Basic Desktop GUI
Section titled “tkinter - Basic Desktop GUI”tkinter is Python’s built-in GUI library for desktop apps.
You can create windows, buttons, labels, and input forms without extra installation.
Core concepts
Section titled “Core concepts”Tk()creates the main window- Widgets:
Label,Entry,Button command=runs a function on button clickmainloop()keeps the UI running
Basic app example (Greeting App)
Section titled “Basic app example (Greeting App)”import tkinter as tk
def greet(): name = name_entry.get().strip() or "Friend" output_label.config(text=f"Hello, {name}!")
app = tk.Tk()app.title("Greeting App")app.geometry("320x180")
tk.Label(app, text="Enter your name:").pack(pady=8)
name_entry = tk.Entry(app, width=28)name_entry.pack(pady=4)
tk.Button(app, text="Greet", command=greet).pack(pady=10)
output_label = tk.Label(app, text="")output_label.pack(pady=6)
app.mainloop()Event flow
Section titled “Event flow”Best practices
Section titled “Best practices”- Keep callback functions short and clear
- Validate input from
Entryfields - For larger apps, split UI into classes/files