"%(a)s ... %(b)s" % {'a': foo, 'b': '%(b)s'}

Tim Peters tim_one at email.msn.com
Sat Dec 4 22:11:19 EST 1999


[Gerrit Holl]
> ...
> But _why_ isn't this permitted:
> >>> print '%(a)s, %(b)s' % {'a': 'aaaa'}
> Traceback (innermost last):
>   File "<stdin>", line 1, in ?
> KeyError: b
>
> Can't Python automatticaly detect there's no B so leave it blank?

It certainly could -- in fact, that it gives an error msg naming "b" now
demonstrates that it's already detecting it <wink>.

> Why doesn't Python do this?

Likely because in *most* cases where a key is missing, it was an error on
the programmer's part (perhaps they misspelled the key name in the format
string, or perhaps they're referencing a key that simply doesn't exist due
to a program logic error -- whichever, if a programmer tells Python to
interpolate a key "b", and there is no key "b", the obvious response is to
protest "but I can't!").

These kinds of mistakes are actually quite common, and it's good to get
yelled at when you make them -- it wouldn't help in general for Python to
make up some other behavior, *guessing* that what looks like an error really
isn't.  Most people wouldn't like that.

I think you're going down a bad path here:  look for approaches that don't
require multiple layers of substitution to begin with!

do-it-once-when-it's-ready-to-be-done-ly y'rs  - tim






More information about the Python-list mailing list