[Tutor] string.Template
Steven D'Aprano
steve at pearwood.info
Tue Apr 23 17:03:33 CEST 2013
On 24/04/13 00:47, Chris “Kwpolska” Warrick wrote:
> 1. locals() is hacky and you shouldn’t use it.
Actually this, or something like this, is exactly one of the use-cases for the locals() function.
Using locals() as a read-only mapping of name:value pairs is perfectly safe. It's only unsafe if you try to write to it. It may or may not work.
> 2. Do you need “$”? Why not use the newfangled {} syntax
The two advantages of the $-template system are:
- It's simpler for non-programmers to use.
- By using the safe_substitute method instead of substitute, it can avoid raising an exception when a replacement is missing. Sometimes that's useful.
py> from string import Template
py> template = Template("Nobody expects the $nationality Inquisition!")
py> template.substitute(nationality="Spanish")
'Nobody expects the Spanish Inquisition!'
py> template.safe_substitute(country="Spain")
'Nobody expects the $nationality Inquisition!'
--
Steven
More information about the Tutor
mailing list