[Python-ideas] Optional parameters without default value

MRAB python at mrabarnett.plus.com
Thu Mar 2 15:07:52 EST 2017


On 2017-03-02 08:03, Serhiy Storchaka wrote:
> Function implemented in Python can have optional parameters with default
> value. It also can accept arbitrary number of positional and keyword
> arguments if use var-positional or var-keyword parameters (*args and
> **kwargs). But there is no way to declare an optional parameter that
> don't have default value. 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
>
> There are drawback of this:
>
> * Module's namespace is polluted with sentinel's variables.
>
> * You need to check for the sentinel before passing it to other function
> by accident.
>
> * Possible name conflicts between sentinels for different functions of
> the same module.
>
> * Since the sentinel is accessible outside of the function, it possible
> to pass it to the function.
>
> * help() of the function shows reprs of default values. "foo(bar=<object
> object at 0xb713c698>)" looks ugly.
>
>
> I propose to add a new syntax for optional parameters. If the argument
> corresponding to the optional parameter without default value is not
> specified, the parameter takes no value. As well as the "*" prefix means
> "arbitrary number of positional parameters", the prefix "?" can mean
> "single optional parameter".
>
> Example:
>
> def get(store, key, ?default):
>      if store.exists(key):
>          return store.retrieve(key)
>      try:
>          return default
>      except NameError:
>          raise LookupError
>
> Alternative syntaxes:
>
> * "=" not followed by an expression: "def get(store, key, default=)".
>
> * The "del" keyword: "def get(store, key, del default)".
>
> This feature is orthogonal to supporting positional-only parameters.
> Optional parameters without default value can be positional-or-keyword,
> keyword-only or positional-only (if the latter is implemented).
>
Could you use 'pass' as the pseudo-sentinel?

Maybe also allow "<name> is pass"/"<name> is not pass" as tests for 
absence/presence.



More information about the Python-ideas mailing list