Sentinel values for special cases

Paddy paddy3118 at netscape.net
Fri Oct 27 00:06:58 EDT 2006


Ben Finney wrote:
> Howdy all,
>
> Ned Batchelder blogged[0] about a debate over checking function
> parameters, and to what extent dynamic typing should be relied upon.
>
> I was one of many who commented, but I wrote what purports to be a
> comprehensive checklist when considering special-case inputs for
> functions. I thought the best way to puncture my ego would be to post
> that list here and see how well it survives :-) Here goes:
>
> [0]: <URL:http://www.nedbatchelder.com/blog/200610.html#e20061022T192641>

Referring to the blog entry, if I had a function that could take
several items of data, where data items were 'expensive' to gather, but
might not all be needed due to other data values, then I can see the
need for using sentinel values for some of the data items and only
computing their true value when necessary.

In Python, as others stated, the sentinel value of choice for all the
data values should be None, or, some module level global constant,
guaranteed not to be part of the data.

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. 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 use the name NO_DATA for the comparison.

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:


class _Sentinel(object):
  ' Initial data value when true data has not been fetched/computed
yet'
  pass

NO_DATA = _Sentinel

def xyz(a,b,c):
  if a == NO_DATA:
    # go get a


(Hmm, should that be double underscores on _Sentinel ...).

- Paddy.




More information about the Python-list mailing list