I would like to display / print my sqlalchemy classes nice and clean.
In Is there a way to auto generate a __str__()
implementation in python?
the answer You can iterate instance attributes using vars, dir, ...:... helps in the case of simple classes.
When I try to apply it to a Sqlalchemy
class (like the one from
Introductory Tutorial of Python’s SQLAlchemy - see below), I get - apart from the member variables also the following entry as a member variable:
_sa_instance_state=<sqlalchemy.orm.state.InstanceState object at 0x000000004CEBCC0>
How can I avoid that this entry appears in the __str__
representation?
For the sake of completeness, I put the solution of the linked stackoverflow question below, too.
import os
import sys
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine
Base = declarative_base()
class Person(Base):
__tablename__ = 'person'
# Here we define columns for the table person
# Notice that each column is also a normal Python instance attribute.
id = Column(Integer, primary_key=True)
name = Column(String(250), nullable=False)
As mentioned, this is the solution from Is there a way to auto generate a __str__
() implementation in python?:
def auto_str(cls):
def __str__(self):
return '%s(%s)' % (
type(self).__name__,
', '.join('%s=%s' % item for item in vars(self).items())
)
cls.__str__ = __str__
return cls
@auto_str
class Foo(object):
def __init__(self, value_1, value_2):
self.attribute_1 = value_1
self.attribute_2 = value_2
Applied:
>>> str(Foo('bar', 'ping'))
'Foo(attribute_2=ping, attribute_1=bar)'