[Python-3000] String formating operations in python 3k
Ian Bicking
ianb at colorstudy.com
Wed Apr 5 01:17:39 CEST 2006
Barry Warsaw wrote:
> On Mon, 2006-04-03 at 15:23 -0500, Ian Bicking wrote:
>
>
>>This is all wandering off-topic, except that all these cases make me
>>think that different kinds of wrapping are very useful. For instance,
>>if you want to make sure everything is quoted before being inserted:
>>
>>class EscapingWrapper:
>> def __init__(self, d):
>> self.d = d
>> def __getitem__(self, item):
>> return cgi.escape(str(self.d[item]), 1)
>>
>>Or if you want expressions:
>>
>>class EvalingWrapper:
>> def __init__(self, d):
>> self.d = d
>> def __getitem__(self, item):
>> return eval(item, d)
>>
>>Then you do:
>>
>>string.Template(pattern).substitute(EscapingWrapper(EvalingWrapper(locals()))
>
>
> I like this. I'd probably not utilize EvalingWrapper, just because I'd
> really want to keep translatable strings really really simple. I think
> most translators can grok simple $-substitutions because they've seen
> those in many other languages.
The useful of a wrapper pattern is if some people would use a wrapper,
and some would not.
One can imagine a formatting wrapper too:
class Formatter:
def __init__(self, d):
self.d = d
def __getitem__(self, item):
if ':' in item:
format, key = item.split(':', 1)
else:
format, key = '', item
value = self.d[item]
if format:
value = ('%'+format) % value
return value
Then "${0.2f:price}" would work. Or you could do:
class Piper:
def __init__(self, d):
self.d = d
def __getitem__(self, item):
parts = item.split('|')
value = self.d[parts[0]]
for filter in parts[1:]
value = self.d[filter](value)
return value
Then "${price|html}" works (assuming you've added an html() function to
your upstream dictionary). And if you are using an evaluating upstream,
you got Django-style filters right there.
These don't quite work with string.Template, because ${...} has the same
content constraints that $... has, so you can't easily put extended
expressions in there. I could have sworn I opened an SF bug on this,
but it appears not. But that's an aside.
Anyway, none of this is very useful if it requires long-winded
invocations and imports, which remains a problem.
--
Ian Bicking / ianb at colorstudy.com / http://blog.ianbicking.org
More information about the Python-3000
mailing list