On 17/05/2020 20:17, James Lu wrote:
Many a python programmer have tired to see code written like:
def bar(a1, a2, options=None):
if options is None:
options = {}
... # rest of function
syntax if argument is not passed, evaluate {} and store to options
def foo(options:={}): pass
syntax if argument is not passed or is None, evaluate {} and store to options*
def foo(options?={}): pass
The Zen of Python states "there shouldn't be two ways to do the same thing."
Thus, only one of ":=" or "?=" should be adopted. They should be evalued on:
- Which encourages writing better code?
- Which catches mistakes easier?
Do we want to encourage callers to pass None to indicate default arguments?
spam = { data: True } if arg else None
bar(a1, a2, param=spam)
versus
bar(a1, a2, { data: True }) if arg else bar(a1, a2)
versus
_ = foo.curry(a1, a2)
_({data: True}) if arg else _(a1, a2)
Since Python is a strongly typed language, it seems more consistent to me that
this code should throw an error:
def getoptions():
... # code to get options
# whoops! missing return statement
#return os.environ
foo(a1, a2, param=getoptions())
:= should be adopted because it catches mistakes more quickly.
On the other hand, ?= replaces the "if kwarg is not None: kwarg = ..." idiom.
(I propose adopting only ":=". I show "?=" as a strawman.)
This seems to have some merit. It is quite common, I believe, to want
an argument's default value to
be evaluated on each call (and beginners are often confused when it
isn't), and to use the idiom James quotes:
def bar(a1, a2, options=None):
if options is None:
options = {}
Allowing `options:={}` will confuse beginners, but many of them are already
confused.:-)
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/python-ideas@python.org/message/MILIX6HSW3PRUNWWP6BN2G2D7PXYFZJ7/
Code of Conduct: http://python.org/psf/codeofconduct/
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/python-ideas@python.org/message/3J2OSS6XIDDVM2HSJAWE5HPRCCHPS26N/
Code of Conduct: http://python.org/psf/codeofconduct/