A safe max() function for empty lists

后端 未结 7 1130
天命终不由人
天命终不由人 2021-02-01 12:28

Evaluating,

max_val = max(a)

will cause the error,

ValueError: max() arg is an empty sequence

Is there a bett

相关标签:
7条回答
  • 2021-02-01 13:01
    _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
    
    0 讨论(0)
提交回复
热议问题