[Python-Dev] PEP 292, Simpler String Substitutions
Oren Tirosh
oren-py-d@hishome.net
Wed, 19 Jun 2002 03:36:57 -0400
On Wed, Jun 19, 2002 at 02:45:46AM -0400, Raymond Hettinger wrote:
> > Handling Missing Keys
> >
> > What should happen when one of the substitution keys is missing
> > from the mapping (or the locals/globals namespace if no argument
> > is given)? There are two possibilities:
> >
> > - We can simply allow the exception (likely a NameError or
> > KeyError) to propagate.
> >
> > - We can return the original substitution placeholder unchanged.
>
> And/Or,
> - Leave placeholder unchanged unless default argument supplied:
> mystr.sub(mydict, undefined='***') # Fill unknowns with
> stars
> And/Or,
> - Raise an exception only if specified:
> mystr.sub(mydict, undefined=NameError)
> And/Or
> - Return a count of the number of missed substitutions:
> nummisses = mystr.sub(mydict)
>
> > BDFL proto-pronouncement: It should always raise a NameError when
> > the key is missing. There may not be sufficient use case for soft
> > failures in the no-argument version.
>
> I had written a minature mail-merge program and learned that the NameError
> approach is a PITA. It makes sense if the mapping is defined inside the
> program;
Exceptions are *supposed* to be a PITA in order to make sure they are hard
to ignore.
+1 on optional argument for default value.
-1 on not raising exception for missing name.
I think the best approach might be to raise NameError exception *unless* a
default argument is passed.
The number of misses cannot be returned by this method - it returns the new
string.
Oren