[Python-ideas] optional parameters

Zachary Ware zachary.ware+pyideas at gmail.com
Wed Apr 16 20:22:29 CEST 2014


On Wed, Apr 16, 2014 at 12:09 PM, Yury Selivanov
<yselivanov.ml at gmail.com> wrote:
> Hello,
>
> There is a very common pattern for creating optional arguments
> when you can't use None:
>
> _optional = object()
> def foo(*, arg1='spam', arg3=None, arg4=_optional):
>     if arg4 is _optional:
>         # caller didn't pass *anything* for arg4
>     else:
>         # caller did pass some (maybe None) value for arg4
>
> It's a bit annoying to create this marker objects, and also,
> if you try to render a signature of such function, you'll get
> something like:
>
> "(*, arg1='spam', arg3=None, arg4=<object object at 0x104be7080>)"
>
> What if we add a standard marker for this use-case:
> functools.optional or inspect.Parameter.optional?

Has Ellipsis (...) been suggested and rejected for this use before?
It's not an absolutely perfect fit, but it looks better to me:

def foo(*, arg1='spam', arg3=None, arg4=...):
    if arg4 is Ellipsis:
        # caller didn't pass anything for arg4
        ...
    else:
        # caller passed something, possibly None, for arg4
        ...

The signature would look like "(*, arg1='spam', arg3=None,
arg4=Ellipsis)", unless inspect.Signature.__str__ special-cased
Ellipsis to be "..." (or "<optional>" if we officially blessed
Ellipsis for the purpose).

-- 
Zach


More information about the Python-ideas mailing list