over 3 years ago

Enforce Clarity with Keyword-Only Arguments

下面的程式使用上不方便,因為容易忘記 ignore_overflow 和 ignore_zero_division 的順序。

def safe_division(number, divisor, ignore_overflow,
                  ignore_zero_division):
    try:
        return number / divisor
    except OverflowError:
        if ignore_overflow:
            return 0
        else:
            raise
    except ZeroDivisionError:
        if ignore_zero_division:
            return float('inf')
        else:
            raise

result = safe_division(1, 10**500, True, False)
result = safe_division(1, 0, False, True)

用 keyword 引數可解決此問題,在 Python 3 可以宣告強制接收 keyword-only 引數。

def safe_division_c(number, divisor, *,
                    ignore_overflow=False,
                    ignore_zero_division=False):
    try:
        return number / divisor
    except OverflowError:
        if ignore_overflow:
            return 0
        else:
            raise
    except ZeroDivisionError:
        if ignore_zero_division:
            return float('inf')
        else:
            raise

# TypeError

safe_division_c(1, 10**500, True, False)

Python 2 沒這種東西,但可以用 **kwargs 模擬出來

def safe_division_d(number, divisor, **kwargs):
    ignore_overflow = kwargs.pop('ignore_overflow', False)
    ignore_zero_div = kwargs.pop('ignore_zero_division', False)
    if kwargs:
        raise TypeError('Unexpected **kwargs: %r' % kwargs)
    try:
        return number / divisor
    except OverflowError:
        if ignore_overflow:
            return 0
        else:
            raise
    except ZeroDivisionError:
        if ignore_zero_div:
            return float('inf')
        else:
            raise
← Effective Python 心得筆記: Item 20 Effective Python 心得筆記: Item 22 →
 
comments powered by Disqus