Access to formatting controls from within __repr__ or __str__?

Serge Orlov Serge.Orlov at gmail.com
Sat Feb 19 06:02:37 EST 2005


Dan Sommers wrote:
> On 18 Feb 2005 01:25:06 -0800,
> "Serge Orlov" <Serge.Orlov at gmail.com> wrote:
>
>> 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
>
> That looks interesting.  Perhaps that will push me into upgrading to
> 2.4 sooner rather than later (I'm *not* looking forward to rebuilding
> all my extensions...).

You don't need to upgrade to Python 2.4. string.Template is a pure
Python code (about 130 lines) and it looks like it's Python 2.2
compatible. My suggestion was to grab it and hack it to add the
feature you want and then keep it in your own library.

  Serge.





More information about the Python-list mailing list