According to the Python documentation about __repr__, a call to repr() should give you a valid Python expression if possible. This is a very useful guideline. And it is also something I I like to implement in my Python projects as much as possible.
Now, for mapped database entities, you might argue that it makes sense to have a default constructor as long as it accepts the primary key columns.
By default, it is possible to create new instances by specifying column values in SQLAlchemy. For example:
It should be possible to create such “repr” values automatically for primary keys. All the required meta info is available. Digging through the SA docs, I found that it is possible the customize Base in order to add behaviour to all mapped entities!
Here’s the result:
With this in place, all representations of DB entities will finally make sense and be copy/pasteable directly into your code.
Of course, by nature of ORMs, the new instances created this way will be detached from the session and need to be merged before you can do any DB related operations on them! A simple example:
sess = Session()
user = User(name=u'John Doe', email=u'john.doe@example.com')
user = sess.merge(user)
sess.refresh(user)