[Python-ideas] Optional parameters without default value
Victor Stinner
victor.stinner at gmail.com
Thu Mar 2 19:53:53 EST 2017
I dislike the try/except NameError test to chevk if the parameter is set.
Catching NameError is slow.
What is the root issue? Function signature in help(func)? If yes, the
solution can be a special value understood by inspect.signature().
Should it be possible to pass explicitly the special value?
func(optional=special_value)? I think it's ok to allow it. The expected
behaviour is to behave as func().
Victor
Le 2 mars 2017 9:04 AM, "Serhiy Storchaka" <storchaka at gmail.com> a écrit :
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).
_______________________________________________
Python-ideas mailing list
Python-ideas at python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20170303/9692fa20/attachment.html>
More information about the Python-ideas
mailing list