SQLAlchemy Repr

0.1.0 · active · verified Fri Apr 17

sqlalchemy-repr, currently at version 0.1.0, is a lightweight Python library that automatically generates human-readable `__repr__` methods for SQLAlchemy declarative models. It aims to simplify debugging and logging by providing informative string representations of model instances without manual boilerplate. The project is stable but has a low release cadence.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to integrate `ReprMixin` with a SQLAlchemy declarative model. By inheriting `ReprMixin` alongside `Base`, your model instances will automatically gain a sensible string representation. The example also shows how to customize the included attributes using `_repr_values`.

from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy_repr import ReprMixin

# 1. Setup SQLAlchemy Base
Base = declarative_base()

# 2. Define a model with ReprMixin
class User(ReprMixin, Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    email = Column(String)

    # Optional: Customize which attributes are shown in repr
    _repr_values = ['id', 'name']

# 3. Create an engine and tables
engine = create_engine('sqlite:///:memory:')
Base.metadata.create_all(engine)

# 4. Create a session
Session = sessionmaker(bind=engine)
session = Session()

# 5. Create and add an instance
user1 = User(id=1, name='Alice', email='alice@example.com')
user2 = User(id=2, name='Bob', email='bob@example.com')
session.add_all([user1, user2])
session.commit()

# 6. Demonstrate the custom repr
retrieved_user = session.query(User).filter_by(name='Alice').first()
print(f"User instance repr: {retrieved_user}")
# Expected output (approx): User(id=1, name='Alice')

# Clean up
session.close()

view raw JSON →