Access to formatting controls from within __repr__ or __str__?

Serge Orlov Serge.Orlov at gmail.com
Fri Feb 18 04:25:06 EST 2005


Dan Sommers wrote:

> 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?

You can create your own class FmtTemplate like string.Template was done
in python 2.4: http://docs.python.org/lib/node105.html

and have it call obj.__str__("#s") when you use ${obj:#s} format. I'm
not sure why you want to pass format to repr (as far as I understand
repr is mostly for debug purposes) but you can call from template as
${obj:r} --> obj.__repr__()
${obj:#r} --> obj.__repr__("#r")

fmt = FmtTemplate("quantity1: ${q1:#s}, quantity2: ${q2:#s}")
q1=MyQuantity(...)
q2=MyQuantity(...)
print fmt.substitute(q1=q1,q2=q2)

  Serge.




More information about the Python-list mailing list