Explain the concept of a SQLAlchemy Session.

Beginner

Answer

A Session in SQLAlchemy ORM is the primary interface for persistence operations. It represents a "workspace" for your objects and acts as a holding zone for all objects you've loaded or created until you commit the changes to the database.
Key characteristics:

  • Identity Map: Ensures one object instance per database row per session
  • Unit of Work: Tracks changes and flushes them to database in transactions
  • Transaction Management: Handles database transactions automatically
from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind=engine)
session = Session()
# Add new object
user = User(name="John")
session.add(user)
session.commit()  # Persists to database