formatting enhancement idea Re: Most important text processing examples

Roman Suzi rnd at onego.ru
Fri Jul 6 20:03:02 CEST 2001


On Fri, 6 Jul 2001, Sam Penrose wrote:

>class PartialStringSubstitution(UserDict):
>    def __init__(self, dict={}):
>        UserDict.__init__(self, dict)
>    def __getitem__(self, key):
>        return UserDict.get(self, key, '%(' + key + ')s')

BTW, you can use anything but "(" and ")"  in format strings:

>>> print " -- %(2+2)s -- " % {"2+2": 4}
 -- 4 --

(Guido, please, do not change "%" to disallow it!)

It is really
easy to include something like:

text = EvaluatingFormat("""lalala %(2+2)s ... %(anything[0])s ...
     %({a+b}*c)s """, vars())

with {} used instead of ().

(I had a piece of code for that, but can't find it now.
It was, I remember, more efficient than DocumentTemplate)

You can even make a special class for string and
redefine "%" to do evaluation transparent...

BTW, it could be supercool feature to have built-in something
like:

a=2
b=2
""" %(a+b)z """ % {'__eval__': eval, '__dict__': vars()}

to produce:

4

And, also, it could be of some interest to make hooks
into formatting procedure. (If it will do no slowdown ;-)
(something similar to SAX ;-) to allow to define
calls for individual format identifiers.)
Probably, this idea is too old-fashioned in the world of
XML though...

def i_format(value, len, zero, ...):
  return "%s" % value
...

__format__.hook(i_format=i_format)

...

print "%012i" % 2.3
23
(and not 000000000023, because we defined though)

This feature could be useful, for example, to redefine
rounding rules of floating point formats, etc...

Wadda yu think?

Sincerely yours, Roman Suzi
-- 
_/ Russia _/ Karelia _/ Petrozavodsk _/ rnd at onego.ru _/
_/ Friday, July 06, 2001 _/ Powered by Linux RedHat 6.2 _/
_/ ""Stupid" is a boundless concept." _/





More information about the Python-list mailing list