Access to formatting controls from within __repr__ or __str__?

Dan Sommers me at privacy.net
Thu Feb 17 18:45:24 EST 2005


Hi,

I have a class whose objects represent physical quantities including
uncertainties and units, and I would like more control over the way they
print.

I have a __str__ method which outputs the quantity and its uncertainty,
properly rounded (i.e. the uncertainty to one digit and the quantity to
the same precision as the uncertainty), followed by the units (mostly)
as they accumulated during whatever calculations led to the quantity's
current value.  Inside this method, I round the floating point values
appropriately and depend on '%s' to do the Right Thing with the floating
point numbers.

I have a __repr__ method that outputs the three parts in such a way that
eval( repr( v ) ) returns a quantity as equal to v as possible.

I would like to add some other options, e.g., an SI mode that prints the
numbers and units according to SI guidelines, and a LaTeX option that
prints something I can copy and paste into a LaTeX document that uses
the SIunits and/or SIstyle packages and/or my own related macros.

So my question is:  Is there a way to pass options "through" a format
string to the __str__ and __repr__ functions?  For example, can I define
my own alternate form for use with the '#' formatting character, so that
'%#s' generates output according to SI guidelines?

I know I can always write the formatting methods separately and call
them explicitly, but IMO that's not as clean as using the format control
codes.  A collection of "set output format" methods is possible, but
that solution makes me cringe.

Thank you,
Dan

-- 
Dan Sommers
<http://www.tombstonezero.net/dan/>
Never play leapfrog with a unicorn.



More information about the Python-list mailing list