[Python-ideas] __missing__ object/keyword

Jim Jewett jimjjewett at gmail.com
Sat Nov 8 18:15:33 CET 2008


On Thu, Nov 6, 2008 at 3:31 PM, George Sakkis <george.sakkis at gmail.com> wrote:
> Several times I find myself using the following idiom:

> _Missing = object()   # sentinel

> def foo(x, y=_Missing):
>   if y is _Missing:
>     do_this
>   else:
>     do_that

And I often catch myself trying to write

    def foo(x, y=object()):
        if y is ... # oops, I need to define the y *outside* the function.

But once I've defined it outside the function, it gets tempting to
reuse it for something else, such as another method in the same class
with a similar need.  And eventually, it may end up getting promoted
to a real object, like None...

I'll freely grant that this is a small use case, but ... it is one I
would appreciate seeing handled better.

> Specifically, the only valid usages of __missing__ would be:
> 1. As a default argument in a callable.
> 2. In identity tests: <var> is __missing__

I assume you could also write

2a.  var is not __missing__

> If this was to be accepted, a further generalization could be to
> allow the `var is __missing__` expression even if `var` is not a
> formal parameter. This would be equivalent to:

> try: var
> except NameError: expr = True
> else: expr = False

I wouldn't do this, at least at first.  I see now that it is
effectively a way of checking for run-time parameters added to
builtins, which can be used to control imports, etc.  But that wasn't
obvious as first.

-jJ



More information about the Python-ideas mailing list