Sentinel values for special cases

Ben Finney bignose+hates-spam at benfinney.id.au
Fri Oct 27 01:23:33 EDT 2006


"Paddy" <paddy3118 at netscape.net> writes:

> None is what Python readers would expect as a sentinel value, but if
> any of your data fields could have None as a valid value then you may
> have to switch to a module level constant.
> Be wary of using sentinel values which are strings, if your data could
> itself be a string - make sure the sentinel value is not valid data,
> and always use the sentinel name and not its value from then on.

I don't think "be wary" is appropriate; I think a blanket "don't use
strings for sentinel values" is fine. In your example below:

> it is very wrong to do this sort of thing:
>
> NO_DATA = '::NO_DATA::'
>
> def xyz(a,b,c):
>   if a == '::NO_DATA::':
>     # blah blah blah

You should not use a string for that constant at all. Its only purpose
is to be a sentinel value, so just make it a unique object instance:

    NO_DATA = object()

    def xyz(a,b,c):
      if a is NO_DATA:
        # blah blah blah

The sentinel value for the 'a' parameter to 'foo.xyz()' is then
'foo.NO_DATA', nothing else. We're now checking by 'is', not '==', so
there's no way to pass the sentinel value to the function unless it's
that specific object. It's impossible to get that particular value any
other way, so you avoid the possibility of accidentally getting the
sentinel as part of the data.

I don't see any advantage a string would have to make it worth using
over the above type of sentinel.

> If you are having difficulty working out what to use as a sentinel
> value for your data then you could declare a Sentinel class and use
> that:

Just use the plain 'object' class, since the instance name will make
its meaning clear, and other instances don't need to share any
behaviour or semantics.

-- 
 \           "There is no reason anyone would want a computer in their |
  `\          home."  -- Ken Olson, president, chairman and founder of |
_o__)                                    Digital Equipment Corp., 1977 |
Ben Finney




More information about the Python-list mailing list