[Python-ideas] Optional parameters without default value

Barry Warsaw barry at python.org
Thu Mar 2 18:00:24 EST 2017


On Mar 02, 2017, at 10:03 AM, Serhiy Storchaka wrote:

>Currently you need to use the sentinel idiom for implementing this:
>
>_sentinel = object()
>def get(store, key, default=_sentinel):
>     if store.exists(key):
>         return store.retrieve(key)
>     if default is _sentinel:
>         raise LookupError
>     else:
>         return default

The reason for using a special sentinel here is to ensure that there's no way
(other than deliberate subterfuge) for code using this API to pass that
sentinel in.  Normally, None is just fine, but for some cases None is a
possible legitimate value, so it won't do as a sentinel.  Thus you make one up
that you know will mean "wasn't given".

A classic example is dict.get():

missing = object()
if d.get('key', missing) is missing:
    its_definitely_not_in_the_dictionary()

i.e. because it's possible for d['key'] == None.

I don't think this use case is common enough for special syntax, or a
keyword.  I'm -0 for adding a new built-in because while it might serve your
purposes, it's easier to commit subterfuge.

>>> get(store, key, default=NoDefault)
# Whoop!

or

if d.get('key', NoDefault) is NoDefault:
    hopefully_its_not_in_the_dictionary()

Cheers,
-Barry
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 801 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20170302/774c0ff8/attachment.sig>


More information about the Python-ideas mailing list