[Python-ideas] __missing__ object/keyword
george.sakkis at gmail.com
Thu Nov 6 21:59:49 CET 2008
On Thu, Nov 6, 2008 at 3:43 PM, Chris Rebert <cvrebert at gmail.com> wrote:
On Thu, Nov 6, 2008 at 12:31 PM, George Sakkis <george.sakkis at gmail.com>
> > 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
> > The reason for using a "private" sentinel is that any python object,
> > including None, might be a valid argument. Another option is using
> > *args or **kwds instead of y but that obfuscates unnecessarily the
> > function signature.
> > It would be nice if a new object or keyword, say __missing__, was
> > introduced as a canonical way to address this common scenario.
> > Specifically, the only valid usages of __missing__ would be:
> > 1. As a default argument in a callable.
> > 2. In identity tests: <var> is __missing__
> > Anything else would raise either a SyntaxError (e.g. `x =
> > __missing__`) or a RuntimeError/TypeError (e.g. `x = y` if y is
> > __missing__). Only the interpreter could assign __missing__ to a name
> > when binding objects to formal parameters.
> > 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
> > Thoughts ?
> By analogy with the necessity of __missing__ when we already have
> None, what if I have something that calls foo() and I want __missing__
> to be a valid argument?
You won't be able to; by definition __missing__ cannot be a valid argument.
> Is the one extra line to define `sentinel` really so bad?
Certainly it's not a showstopper by any means, but it's more than one extra
line. If __missing__ is a regular object, a client may "cheat" by passing it
explicitly. It can also help introspection and documentation tools (e.g.
epydoc) and IDEs.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-ideas