>>>>> "RH" == Raymond Hettinger <python@rcn.com> writes: >> 1. $$ is an escape; >> it is replaced with a single $ RH> Hmm, some strings (at least in the spam I receive) contain RH> $$$$$$. How about ${$}? How often will you be interpolating into spam? Sounds like it could get messy. ;) >> 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. RH> And/Or, RH> - Leave placeholder unchanged unless default argument RH> supplied: mystr.sub(mydict, undefined='***') # Fill unknowns RH> with RH> stars RH> And/Or, RH> - Raise an exception only if specified: RH> mystr.sub(mydict, undefined=NameError) RH> And/Or RH> - Return a count of the number of missed substitutions: RH> nummisses = mystr.sub(mydict) I /really/ dislike interfaces that raise an exception or don't, based on an argument to the function. Returning the number of missed substitutions doesn't seem useful, but could be done with a regexp. Filling unknowns with stars could just as easily be done with a different safedict wrapper. The specific issue is when using locals+globals. In that case, it's seems like the problem is clearly a programming bug, so the exception should be raised. >> 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. RH> I had written a minature mail-merge program and learned that RH> the NameError approach is a PITA. It makes sense if the RH> mapping is defined inside the program; however, externally RH> supplied mappings (like a mergelist) can be expected to have RH> "holes" and launching exceptions makes it harder to recover RH> than having a default behavior. The best existing Python RH> comparison is the str.replace() method which does not bomb-out RH> when the target string is not found. I agree that certain use cases make the exception problematic. Think a program that uses a template entered remotely through the web. That template could have misspellings in the variable substitutions. In that case I think you'd like to carry on as best you can, by returning a string with the bogus placeholders still in the string. -Barry
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4