[Python-ideas] [Python-Dev] nodef

Collin Winter collinw at gmail.com
Thu May 24 02:27:44 CEST 2007


[moving to python-ideas, where it belongs]

On 5/23/07, Martin Blais <blais at furius.ca> wrote:
> I often have the need for a generic object to use as the default value
> for a function parameter, where 'None' is a valid value for the
> parameter.  For example:
>
>     _sentinel = object()
>
>     def first(iterable, default=_sentinel):
>         """Return the first element of the iterable, otherwise the default value (if
>         specified).
>         """
>         for elem in iterable:   # thx to rhettinger for optim.
>           return elem
>         if default is _sentinel:
>           raise StopIteration
>         return default
>
> Here, 'default' could legally accept None, so I cannot use that as the
> default value, nor anything else as far as I'm concerned (I don't know
> what lives in the iterable, so why should I make assumptions?).
> Sometimes in the past I've create generic objects, declared a class,
> e.g.:
>
>   class NoDef: pass
>   def foo(default=NoDef):
>       ...
>
> and lately I've even started using the names of builtin functions (it
> bothers me a little bit though, that I do that).
>
> I think Python needs a builtin for this very purpose.  I propose
> 'nodef', a unique object whose sole purpose is to serve as a default
> value.  It should be unique, in the same sense that 'None' is unique.

I've run into this situation several times before, and I've never felt
that defining my own sentinel was unduly taxing. Having a built-in
would only save a single line, the initial "sentinel = object()".

Collin Winter



More information about the Python-ideas mailing list