[CentralOH] Python % Formatting

Brian Costlow brian.costlow at gmail.com
Mon Dec 10 14:49:14 CET 2007

I can think of something I might be able to use it for.

We're using Django for some of our work. Django models (their
lightweight ORM mapper, for those unfamiliar with Django) use the
__str__ function as a quick way to get a string representation of
objects (db rows).

It's used in their automatic admin system, and we have used it in a
couple of places to display data in our own views. It works best where
data from the same object will get displayed out as part of the same
line with the same formatting (so it can all be stuffed into one
template variable.)

So if I have a model instance breakfast, Instead of :

response['breakfast'] = "I had %s and %s eggs for breakfast",
(breakfast.meat, breakfast.egg_type)

I can just write

response['breakfast'] = str(breakfast)

Except that doesn't work so well when one of the fields for a
particular instance is blank. You end up with:

'I had spam and  eggs for breakfast'  # extra space after and

or worse

'I had  and scrambled eggs for breakfast.'

Using something like this, I could add the 'eggs' and the  'and' as
string variable back in the model,
and get a more intelligent string representation that I can use more often.

'I had %s %s %s %s for breakfast'.

Not a too terrible violation of separation of concerns, (you can
always access the fields directly if you need them) and  it helps with

Oh, and hello all, first time posting here.

I'm part of a small group of folks doing process automation and the
occasional web application for Vertis, a fairly large printing and
communications company.
We use Django and parts of Twisted on Linux, OS X and Solaris. We also
do some legacy PHP and Perl stuff (that we're porting whenever we can
make an ROI case).

More information about the CentralOH mailing list