Reputation: 811
What would be the best way to handle the __repr__()
function for an object that is made persistent? For example, one that is representing a row in a database (relational or object).
According to Python docs, __repr__()
should return a string that would re-create the object with eval()
such that (roughly) eval(repr(obj)) == obj
, or bracket notation for inexact representations. Usually this would mean dumping all the data that can't be regenerated by the object into the string. However, for persistent objects recreating the object could be as simple as retrieving the data from the database.
So, for such objects then, all object data or just the primary key in the __repr__()
string?
Upvotes: 2
Views: 141
Reputation: 8021
repr should return a string that would re-create the object with eval
That is legal for simple types like int or string or float, but not usable for multi-column DB object with say 15+ columns
For example if I had a class representing price, it would be reasonable to make the __repr__
show the main characteristics of it: amount and currency
def __repr__(self):
return '%s %s'%(self.amount,self.currency)
Upvotes: 1
Reputation: 798546
How to get it from the database is generally uninteresting. Return the way to recreate the object from scratch, e.g. SomeModel(field1, field2, ...)
.
Upvotes: 0