[Tutor] What/Why this Cookbook recipe?

Andrei project5 at redrival.net
Tue Mar 6 20:43:34 CET 2007


Dick Moores wrote:
> I've been trying to learn new things from the Cookbook, but here's a 
> recipe the utility of which I don't understand at all. Why interpolation 
> (whether the ruby way or not)? Maybe a better example than the couple 
> given would help me? 
<snip>

Normal string formatting in Python works by including in the string a 
sort of type definition (e.g. '%s' means 'insert a string here', '%d' is 
  'insert an integer here', etc.). You have to supply the arguments 
after the format string, in a tuple. For example:

   >>> print 'Name: %s\nAge: %d' % (username, userage)
   Name: John Doe
   Age: 39

With the recipe provided, you can put the variables you want inserted 
directly in the format string - it's no longer necessary to append them 
in a tuple. So for the example above, it would become:

   >>> print interp('Name: #{username}\nAge: #{userage}')

As you see, it's slightly shorter and more ad-hoc - or it would be, if 
it were built into the language and you didn't have to call the interp 
function. It also has the advantage that you don't have to make sure you 
provide the right number (and type) of arguments in the tuple - it's 
easy to e.g. decide to no longer print the age and forget to update the 
tuple, like this:

   >>> print 'Name: %s' % (username, userage)
   Traceback <snip>
   TypeError: not all arguments converted during string formatting

That's a particularly annoying source of errors that isn't caught even 
in (most? all?) machine-code compiled languages. The opposite may also 
occur, that you e.g. decide to also print a phone number, include that 
in the format string, yet forget to include it in the tuple as well.

The recipe has some disadvantages:

- you have put your variable names in a string. This is bad practice - 
if you rename variables, it's easy to overlook them in strings.

- format strings can be used to translate an application. You just give 
the translator your 'Name: %s' string and he gives you 'Borkbork: %s' or 
whatever. The translation doesn't need to be modified if you decide to 
make a user class and get rid of the username and userage vars.

- format strings give you more control, so you can e.g. specify how many 
digits a float should have when formatted.


-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info:
''.join([''.join(s) for s in zip(
"poet at aao.l pmfe!Pes ontuei ulcpss  edtels,s hr' one oC.",
"rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")])



More information about the Tutor mailing list