typestar

Declarative models in Python

A mapped class per table, with typed columns.

from sqlalchemy import String, create_engine
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column


class Base(DeclarativeBase):
    pass


class Run(Base):
    __tablename__ = "runs"

    id: Mapped[int] = mapped_column(primary_key=True)
    lang: Mapped[str] = mapped_column(String(32), index=True)
    tpm: Mapped[float]
    stars: Mapped[int] = mapped_column(default=1)

    def __repr__(self):
        return f"Run({self.lang!r}, {self.tpm})"


engine = create_engine("sqlite+pysqlite:///:memory:")
Base.metadata.create_all(engine)
print(sorted(Base.metadata.tables))
print([c.name for c in Run.__table__.columns])

How it works

  1. DeclarativeBase is the shared parent.
  2. Mapped annotations declare the column types.
  3. create_all emits the DDL for every mapped class.

Keywords and builtins used here

The run, in numbers

Lines
24
Characters to type
596
Tokens
150
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 82 seconds.

Type this snippet

Step 2 of 5 in SQLAlchemy, step 14 of 19 in Web services & data access.

← Previous Next →