Evaluating,
max_val = max(a)
will cause the error,
ValueError: max() arg is an empty sequence
Is there a bett
_DEFAULT = object()
def max_default(*args, **kwargs):
"""
Adds support for "default" keyword argument when iterable is empty.
Works for any iterable, any default value, and any Python version (versions >= 3.4
support "default" parameter natively).
Default keyword used only when iterable is empty:
>>> max_default([], default=42)
42
>>> max_default([3], default=42)
3
All original functionality is preserved:
>>> max_default([])
Traceback (most recent call last):
ValueError: max() arg is an empty sequence
>>> max_default(3, 42)
42
"""
default = kwargs.pop('default', _DEFAULT)
try:
return max(*args, **kwargs)
except ValueError:
if default is _DEFAULT:
raise
return default
Bonus:
def min_default(*args, **kwargs):
"""
Adds support for "default" keyword argument when iterable is empty.
Works for any iterable, any default value, and any Python version (versions >= 3.4
support "default" parameter natively).
Default keyword used only when iterable is empty:
>>> min_default([], default=42)
42
>>> min_default([3], default=42)
3
All original functionality is preserved:
>>> min_default([])
Traceback (most recent call last):
ValueError: min() arg is an empty sequence
>>> min_default(3, 42)
3
"""
default = kwargs.pop('default', _DEFAULT)
try:
return min(*args, **kwargs)
except ValueError:
if default is _DEFAULT:
raise
return default