[Python-ideas] max() allowed to take empty list
Chris Rebert
pyideas at rebertia.com
Tue Apr 13 03:52:33 CEST 2010
On Mon, Apr 12, 2010 at 6:36 PM, Tom Pinckney <thomaspinckney3 at gmail.com> wrote:
> Many functions are happy to take empty lists:
<snip>
> But not max():
>
>>>> max([])
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> ValueError: max() arg is an empty sequence
>
> Allowing max to return None would make a lot of functional style programming easier, instead of explicitly having to check for empty lists or ignoring exceptions.
>
> None makes sense as a return value in many contexts. For example, hypothetical code like:
>
> if max(values) >= 90: return True # works even if values is []
No, actually it *doesn't* work. It makes no sense to try and compare
None to a number, and Python 3.x rightfully complains:
Python 3.1.1 (r311:74480, Feb 1 2010, 23:08:45)
>>> if None >= 90: pass
Traceback (most recent call last):
File "prog.py", line 1, in <module>
if None >= 90: pass
TypeError: unorderable types: NoneType() >= int()
Errors should never pass silently unless explicitly silenced, so
having None as a default fails on those grounds too.
Adding a 'default value' parameter to max() to be returned when the
iterable is empty would make slightly more sense.
Cheers,
Chris
--
http://blog.rebertia.com
More information about the Python-ideas
mailing list