SQLAlchemy Repr
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
-
ModuleNotFoundError: No module named 'sqlalchemy_repr'
cause The `sqlalchemy-repr` package is not installed in your current Python environment.fixInstall the package using pip: `pip install sqlalchemy-repr` -
TypeError: object.__init__() takes exactly one argument (the instance)
cause This error can occur if `ReprMixin` is not the *first* class inherited alongside SQLAlchemy's `Base` in a multiple inheritance scenario, causing conflicts with SQLAlchemy's initialization process (especially in older SQLAlchemy versions).fixEnsure `ReprMixin` is listed *before* `Base` in the inheritance order for your model: `class MyModel(ReprMixin, Base):` -
sqlalchemy.exc.NoReferenceError: Can't find reference to the table 'tablename' in the database (or similar SQLAlchemy-related error)
cause This usually indicates an issue with the SQLAlchemy declarative setup itself, rather than `ReprMixin`. `ReprMixin` requires a properly configured SQLAlchemy declarative model.fixVerify your SQLAlchemy declarative base setup, table definitions, and that `Base.metadata.create_all(engine)` has been called correctly or that tables exist in your database. Ensure the model inherits from `Base`.
Warnings
- gotcha The project `sqlalchemy-repr` is stable but has a low level of active development. While it works reliably with existing SQLAlchemy versions, new SQLAlchemy features or major API changes might not be immediately supported.
- gotcha By default, `ReprMixin` includes all mapped columns in the `__repr__` output. For models containing sensitive data (e.g., passwords, API keys, private information), this could lead to unintended exposure in logs or during debugging.
- gotcha For models with complex, deeply nested, or circular relationships, relying solely on `ReprMixin`'s default behavior can lead to overly verbose representations or even infinite recursion if relationships are eagerly loaded.
Install
-
pip install sqlalchemy-repr
Imports
- ReprMixin
from sqlalchemy_repr import ReprMixin
Quickstart
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()