End of file

Alex Martelli aleaxit at yahoo.com
Fri Oct 8 04:31:52 EDT 2004


Nick Craig-Wood <nick at craig-wood.com> wrote:

> Alex Martelli <aleaxit at yahoo.com> wrote:
> > >     sentinel = []
> > 
> >  It's fine, but I would still suggest using the Canonical Pythonic Way To
> >  Make a Sentinel Object:
> > 
> >      sentinel = object()
> > 
> >  Since an immediate instance of type object has no possible use except as
> >  a unique, distinguishable placeholder, ``this thing here is a sentinel''.
> 
> Yes a good idiom which I didn't know (still learning) - thanks!

You're welcome.

> This only works in python >= 2.2 according to my tests.

Yes, 2.2 is when Python acquired the 'object' built-in.  If you need to
also support ancient versions of Python, it's often possible to do so by
clever initialization -- substituting your own coding if at startup you
find you're running under too-old versions.  You presumably already do
that, e.g., for True and False, staticmethod, &c -- in the 2.3->2.4
transition it makes sense to do it for sorted, reversed, set, ... -- for
this specific issue of using object() for a sentinel, for example:

try: object
except NameError: def object(): return []

plus the usual optional stick-into-builtins, are all you need in your
application's initialization phase.


> Its also half the speed and 4 times the typing
> 
>   $ /usr/lib/python2.3/timeit.py 'object()'
>   1000000 loops, best of 3: 0.674 usec per loop
>   $ /usr/lib/python2.3/timeit.py '[]'
>   1000000 loops, best of 3: 0.369 usec per loop
> 
> But who's counting ;-)

Nobody, I sure hope.  's=[]' is just four characters, while 'sentinel =
[]', the usage you suggested (with proper spacing and a decent name), is
13, and yet it's pretty obvious the clarity of the latter is well worth
the triple typing; and if going to 'sentinel = object()' makes it
clearer yet, the lesser move from 13 to 19 (an extra-typing factor of
less than 1.5) is similarly well justified.
And I think it's unlikely you'll need so many sentinels as to notice the
extra 300 nanoseconds or so to instantiate each of them...


Alex



More information about the Python-list mailing list