[Python-Dev] Can we please have a better dict interpolation
syntax?
Barry Warsaw
barry at python.org
Thu Oct 23 10:46:48 EDT 2003
On Thu, 2003-10-23 at 00:16, Guido van Rossum wrote:
> There have been many proposals in this area, even a PEP (PEP 215,
> which I don't like that much, despite its use of $).
And PEP 292, which I probably should update.
I should mention that $string substitutions are optional in Mailman 2.1,
but they will be the only way to do it in Mailman 3. I've played a lot
with various implementations of this idea, and below is the one I've
currently settled on. Not all of the semantics may be perfect for core
Python (i.e. never throw a KeyError), but this is all doable in modern
Python, and for user-exposed templates, gets a +1000 in my book.
>>> s = dstring('${person} lives in $where and owes me $$${amount}')
>>> d = safedict(person='Guido', where='California', amount='1,000,000')
>>> print s % d
Guido lives in California and owes me $1,000,000
>>> d = safedict(person='Tim', amount=.13)
>>> print s % d
Tim lives in ${where} and owes me $0.13
-Barry
import re
# Search for $$, $identifier, or ${identifier}
dre = re.compile(r'(\${2})|\$([_a-z]\w*)|\${([_a-z]\w*)}', re.IGNORECASE)
EMPTYSTRING = ''
class dstring(unicode):
def __new__(cls, ustr):
ustr = ustr.replace('%', '%%')
parts = dre.split(ustr)
for i in range(1, len(parts), 4):
if parts[i] is not None:
parts[i] = '$'
elif parts[i+1] is not None:
parts[i+1] = '%(' + parts[i+1] + ')s'
else:
parts[i+2] = '%(' + parts[i+2] + ')s'
return unicode.__new__(cls, EMPTYSTRING.join(filter(None, parts)))
class safedict(dict):
"""Dictionary which returns a default value for unknown keys."""
def __getitem__(self, key):
try:
return super(safedict, self).__getitem__(key)
except KeyError:
return '${%s}' % key
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 307 bytes
Desc: This is a digitally signed message part
Url : http://mail.python.org/pipermail/python-dev/attachments/20031023/2684c83b/attachment.bin
More information about the Python-Dev
mailing list