I'm quite new to Python and currently I need to have a __repr__ for a SqlAlchemy class.
I have an integer column that can accept Null value and SqlAlchemy converts it to None.
For example:
class Stats(Base):
__tablename__ = "stats"
description = Column(String(2000))
mystat = Column(Integer, nullable=True)
What is the correct way to represent the "mystat" field in the __repr__ function when SqlAlchemy returns None?
The
__repr__should return a string that describes the object. If possible, it should be a valid Python expression that evaluates to an equal object. This is true for built-in types likeintorstr:If that's not possible, it should be a
'<...>'string uniquely describing the object. The default__repr__is an example of this:It uses the object's address in memory to uniquely identify it. Of course address doesn't tell us much about the object so it's useful to override
__repr__and return a string describing the object's state.The object's state is defined by other objects it contains so it makes sense to include their
reprin yours. This is exactly whatlistordictdo:In your case, the state is in your
Columnproperties so you want to use theirrepr. You can use the%rformatting for this, it inserts arepr()of the argument:An equivalent using the new formatting: