Common Python Libraries
Python has a huge collection of libraries that add extra powers to the language. These libraries let you do things like talk to the internet, save data to a database, build websites, and much more - without writing everything from scratch yourself.
These libraries show up in real projects, job interviews, and everyday 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”Official docs: https://docs.python.org/3/library/os.html
Use os when you need to talk directly to the operating system - things like checking folders, deleting files, or reading environment variables.
Common use cases
Section titled “Common use cases”- Working with directories and files
- Reading environment variables
- Getting info about the current process
Frequently used functions
Section titled “Frequently used functions”os.getcwd()-> get the current working directoryos.listdir(path)-> list everything inside a folderos.makedirs(path, exist_ok=True)-> create folders without crashing if they already existos.remove(path)-> delete a fileos.environ.get("KEY")-> safely read an 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 file path work in new code - it’s cleaner - Use
os.environ.get()instead ofos.environ["KEY"]to avoid aKeyErrorcrash when the variable doesn’t exist
sys - Python Runtime and CLI Arguments
Section titled “sys - Python Runtime and CLI Arguments”Official docs: https://docs.python.org/3/library/sys.html
Use sys when you want to read arguments passed to your script, exit the program, or check which version of Python is running.
Common use cases
Section titled “Common use cases”- Read values the user passes when running your script
- Stop the program and return an exit code
- Check the Python version or module search paths
Frequently used attributes and functions
Section titled “Frequently used attributes and functions”sys.argv-> list of arguments passed to the scriptsys.exit(code)-> stop the program (0 = success, anything else = error)sys.version-> the current Python version as a stringsys.path-> list of folders Python searches when importing modules
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”- Always check that the right number of arguments were passed before using them
- Use a non-zero exit code (like
1) when something goes wrong, so other programs or scripts can detect the failure
typing - Type Hints for Better Code
Section titled “typing - Type Hints for Better Code”Official docs: https://docs.python.org/3/library/typing.html
Use typing to add labels to your code that say what type of data a variable or function should work with. These labels are called type hints.
Why use typing?
Section titled “Why use typing?”- Catches errors early - IDEs and type checkers can spot bugs before you even run the code
- Self-documenting code - other developers can understand what your functions expect without reading extra docs
- Better IDE support - autocomplete and suggestions work much better
- Enables static analysis - tools like
mypycan check your code for type mistakes without running it - Improves maintainability - it’s easier to change and refactor code when types are clearly written out
Common type hints
Section titled “Common type hints”int,str,float,bool-> basic built-in typesList[int]-> a list that contains integersDict[str, int]-> a dictionary with string keys and integer valuesTuple[str, int]-> a tuple with a string and then an integerOptional[str]-> a string, orNoneUnion[str, int]-> can be either a string or an integerCallable[[int, str], bool]-> a function that takes an int and a str and returns a boolAny-> any type at all (try not to use this too much)
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 your types without running your code:
uv add --dev mypyuv run mypy your_file.pymypy will catch mistakes like this:
# 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]when a value might beNone, notOptional[Union[T, None]]- they mean the same thing butOptional[T]is cleaner - Use
List,Dict,Tuplefromtypingfor Python versions below 3.9, or just use the built-inlist,dictfor Python 3.9 and above - Keep your types simple and easy to read - avoid making them too complex
- Type hints are optional, but strongly recommended for any code that others will use or maintain
json - Serialization and API Data
Section titled “json - Serialization and API Data”Official docs: https://docs.python.org/3/library/json.html
json lets you convert Python data (like dictionaries and lists) into JSON text, and turn JSON text back into Python data. This is very common when working with APIs.
Important methods
Section titled “Important methods”json.dumps(obj)-> turn a Python object into a JSON stringjson.loads(text)-> turn a JSON string into a Python objectjson.dump(obj, file)-> write JSON directly into a filejson.load(file)-> read JSON from a 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=2to make the JSON file easy to read - Use
ensure_ascii=Falseif your data has non-English characters - Remember that JSON only supports basic types - dict, list, str, int, float, bool, and null (which becomes
Nonein Python)
csv - Read and Write CSV Files
Section titled “csv - Read and Write CSV Files”Official docs: https://docs.python.org/3/library/csv.html
csv is for working with spreadsheet-style data where values are separated by commas. This format is very common for exporting and sharing data.
Core tools
Section titled “Core tools”csv.reader()/csv.writer()- work with rows as plain listscsv.DictReader()/csv.DictWriter()- work with rows as dictionaries using column names
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=""when opening CSV files on Windows to avoid getting blank lines between rows - Prefer
DictReaderandDictWriter- using column names makes the code much easier to understand
sqlite3 - Lightweight Database Basics
Section titled “sqlite3 - Lightweight Database Basics”Official docs: https://docs.python.org/3/library/sqlite3.html
sqlite3 gives you a simple database that lives in a single file on your computer. No server setup needed - it just works.
When to use
Section titled “When to use”- Small to medium local apps
- Learning SQL and databases
- Desktop tools or apps that work offline
Core workflow
Section titled “Core workflow”- Connect to the database file
- Create a cursor (the tool you use to run SQL)
- Run your SQL commands
- Commit the changes (save them)
- Close the 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”- Always use parameterized queries with
?placeholders - never put user input directly into SQL strings, as that can cause security problems (SQL injection) - Wrap database operations in
try/exceptblocks in real apps so errors don’t crash everything
requests - HTTP Requests Made Simple
Section titled “requests - HTTP Requests Made Simple”Official docs: https://requests.readthedocs.io/en/latest/
requests is the most popular Python library for talking to the internet - fetching web pages, calling APIs, sending data, and more.
Install
Section titled “Install”uv add requestsCommon methods
Section titled “Common methods”requests.get(url)- fetch data from a URLrequests.post(url, json=data)- send data to a URLresponse.status_code- check if the request succeeded (200 = OK)response.json()- parse the response as JSONresponse.raise_for_status()- automatically raise an error if the request failed
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 a
timeoutso your program doesn’t hang forever waiting for a response - Call
raise_for_status()right after the request so you catch HTTP errors (like 404 or 500) straight away - Use
Session()if you’re making many requests to the same website - it reuses the connection and is faster
datetime - Date and Time Handling
Section titled “datetime - Date and Time Handling”Official docs: https://docs.python.org/3/library/datetime.html
Use datetime whenever you need to work with dates, times, or both - like getting the current time, formatting a date for display, or calculating how many days until a deadline.
Common operations
Section titled “Common operations”- Get the current date/time:
datetime.now() - Turn a string into a date:
datetime.strptime() - Turn a date into a string:
datetime.strftime() - Add or subtract time 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 (a universal time standard) in backend systems to avoid timezone confusion
- Only convert to the local timezone when you’re showing the time to a user
pathlib - Modern Path Handling
Section titled “pathlib - Modern Path Handling”Official docs: https://docs.python.org/3/library/pathlib.html
pathlib is the modern way to work with file and folder paths in Python. Instead of joining strings together manually, you use Path objects that are much cleaner to read and work with.
Common operations
Section titled “Common operations”- Build paths by joining them with
/ - Check if a file or folder exists
- Read and write text files quickly
- Loop through all files in a folder
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”- Use
Pathinstead of manually joining strings with+oros.path.join() - Always specify
encoding="utf-8"when reading or writing text files
python-dotenv - Environment Variables from .env
Section titled “python-dotenv - Environment Variables from .env”Official docs: https://saurabh-kumar.com/python-dotenv/
python-dotenv reads a .env file and loads the values inside it as environment variables. This is a very common way to keep secrets (like API keys) out of your code.
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”- Never commit your
.envfile to Git - add it to.gitignore - Never paste API keys or passwords directly into your code - always use environment variables
logging - Professional Logging Basics
Section titled “logging - Professional Logging Basics”Official docs: https://docs.python.org/3/library/logging.html
Use logging instead of print() when building real applications. It gives you much more control - you can set levels, add timestamps, write to files, and filter what gets shown.
Log levels
Section titled “Log levels”DEBUG-> very detailed info, useful when tracking down a bugINFO-> normal things happening as expectedWARNING-> something unexpected happened, but the app is still workingERROR-> something went wrong and a task failedCRITICAL-> something went very wrong and the app may not be able to continue
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”- Always include a timestamp and log level in your format string
- Inside
exceptblocks, uselogger.exception("...")instead oflogger.error(...)- it also prints the full error traceback - For apps that run for a long time, write logs to a file so you can check them later
flask - Basic Web Application Framework
Section titled “flask - Basic Web Application Framework”Official docs: https://flask.palletsprojects.com/
flask is a small and beginner-friendly framework for building websites and APIs with Python. It’s a great starting point for learning how web backends work.
Install
Section titled “Install”uv add flaskCore concepts
Section titled “Core concepts”Flask(__name__)-> creates your app@app.route("/")-> connects a URL to a Python functionrequest-> lets you read data sent by the browser or clientjsonify()-> sends back a JSON response
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 route functions short - move your actual logic into separate functions or files
- Only use
debug=Truewhile developing, never in production - Always check and validate user input before doing anything with it
tkinter - Basic Desktop GUI
Section titled “tkinter - Basic Desktop GUI”Official docs: https://docs.python.org/3/library/tkinter.html
tkinter is Python’s built-in library for building desktop apps with windows, buttons, and text fields. You don’t need to install anything extra - it comes with Python.
Core concepts
Section titled “Core concepts”Tk()-> creates the main window- Widgets like
Label,Entry,Button-> the building blocks of your UI command=-> tells a button which function to run when clickedmainloop()-> keeps the window open and listening for user actions
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 button callback functions short and focused on one thing
- Always check and clean input from
Entryfields before using it - For bigger desktop apps, split your UI code into classes or separate files to keep things organized