[Python-Dev] Py2.6 ideas

Raymond Hettinger python at rcn.com
Fri Feb 16 19:41:40 CET 2007


[Martin v. Löwis]
>Why does this still need to support the
> tuple interface (i.e. indexed access)?

I used named tuples whereever I need a tuple but the number and meaning
of the fields starts to tax my memory.  For doctests, I return a named
tuple like TestResults(failed=0, attempted=15).  That named tuple can
still be unpacked after a function call:  f,a=results.  And it can be unpacked
in a function call:  f(*results).   It can be handed to functions that expect
a tuple:   'Missed %d out of %d tests' % results.  Also, the named tuple
used with indexed access has the same high performance as a regular
tuple; however, if an error occurs, its repr is shown in a more readable
form.  Likewise, when constructing the NamedTuple, an editor's
tooltips reminds you of what goes in each field.

Those properties have proved useful to me when modeling option
contracts where each contract has to track the remaining time,
interest rate, option type, underlying security, and strike price.
The same applies to model results:  delta, gamma, vega, theta, rho.
This could also be done with attribute access, but it would be
much slower and much more verbose when unpacking the model's results:

  d, g, v, t, r = model(somecontract)

vs.

  m = model(somecontract)
  d, g, v, t, r = m.delta, m.gamma, m.vega, m.theta, m.rho


> I'm not (anymore) sure that you are aware that the os.stat result *already*
> has named fields, in addition to the indexed access.

Of course, that specific example was solved long ago.  We did not
however expose a general purpose mechanism applicable where
similar issues arise for other tuples.


Raymond 


More information about the Python-Dev mailing list