Gen-AI Developer Classroom notes 12/Oct/2025

Lambda

Comprehensions

  • Python supports
    • list
    • set
    • dict
    • range
  • Refer Here for comprehensions
  • list comprehensions
  • note: use this prompt in any llm to get problems to solve
As a expert in python, i'm trying to learn list comprehensions give me excercises from basic to advanced one after other

pandas – library

  • Refer Here for pandas tutorial
  • Installing pandas
  • create a virtual environment
  • Create a restaurant catalog csv and read it into data frame
  • Findout what iloc and labels are
  • Refer Here for sample pandas

Databases

  • To deal with relational databases we have two options
    • executing sql statements from python code:
      • Vendor specific sql
    • treat tables as objects, write python code and some framwork will convert your python operations into SQL (ORM)
      • Independent of database used
  • Database options:
    • SQLite (for development)
    • mysql (Docker)
    • postgres (Docker)

SQLite with python

SQL Alchemy

  • This is ORM (Object Relational Mapping) Refer Here
import os
from typing import List, Optional
from sqlalchemy import create_engine, String
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
from sqlalchemy.orm import Session

# --- 1. Define the Declarative Base ---
# All ORM models inherit from this base.
class Base(DeclarativeBase):
    pass

# --- 2. Define the ORM Model (Table) in 2.0 Style ---
class User(Base):
    # This specifies the table name in the database
    __tablename__ = "users"

    # Define columns using Mapped and mapped_column
    # The 'Mapped' type indicates the Python type, and mapped_column 
    # provides database-specific arguments.
    id: Mapped[int] = mapped_column(primary_key=True)

    # String(50) defines a VARCHAR with a length limit of 50
    username: Mapped[str] = mapped_column(String(50), unique=True, index=True, nullable=False)

    # Optional[str] maps to a NULLable string column 
    email: Mapped[Optional[str]] = mapped_column(String(100), unique=True, index=True)

    # A more concise __repr__ for debugging
    def __repr__(self) -> str:
        return f"User(id={self.id!r}, username={self.username!r})"

# --- 3. Configure Engine for SQLite ---
# Using an in-memory database for a quick example, or a file for persistence.
# For a file: SQLALCHEMY_DATABASE_URL = "sqlite:///example_20.db"
SQLALCHEMY_DATABASE_URL = "sqlite:///examples.db" 
engine = create_engine(
    SQLALCHEMY_DATABASE_URL, 
    echo=True, # Logs all SQL statements to the console
    connect_args={"check_same_thread": False} # Required for multithreading with SQLite
)

# --- 4. Create Tables using Base.metadata.create_all() ---
if __name__ == "__main__":
    print("Initializing database...")

    # This command inspects all models inherited from Base (in this case, 'User')
    # and generates the DDL (CREATE TABLE statements) to create them in the database.
    # It will not recreate tables that already exist.
    Base.metadata.create_all(engine)

    print("\nTable creation successful.")

    # If you used the file-based URL, you could check for the file here:
    # if SQLALCHEMY_DATABASE_URL.startswith("sqlite:///") and not SQLALCHEMY_DATABASE_URL.endswith(":memory:"):
    #     db_file = SQLALCHEMY_DATABASE_URL.split("///")[1]
    #     if os.path.exists(db_file):
    #         print(f"Database file '{db_file}' created.")
    user1 = User(username="spongebob", email="spongebob@bikini.bottom")
    user2 = User(username="patrick", email="patrick@bikini.bottom")
    user3 = User(username="sandy", email="sandy_cheeks@bikini.bottom")
    with Session(engine) as session:
        # Add the new User objects to the session
        session.add_all([user1, user2, user3])

        # The commit() method issues the INSERT statements to the database 
        # and finalizes the transaction.
        session.commit()

        # 3. (Optional) Verify that the primary keys were assigned
        # After commit, the ORM objects are refreshed with their generated 'id' values.
        print("\n--- Records Inserted ---")
        print(f"User 1 ID: {user1.id}")
        print(f"User 2 ID: {user2.id}")
        print(f"User 3 ID: {user3.id}")
        print("------------------------\n")

library management system

By continuous learner

enthusiastic technology learner

Leave a Reply

Discover more from Direct AI Powered By Quality Thought

Subscribe now to keep reading and get access to the full archive.

Continue reading