函数的 quiet/verbose 标志的 Pythonic 实现

Pythonic implementation of quiet / verbose flag for functions

在努力编写 pythonic 代码时,我想知道是否有涵盖函数的安静或详细选项使用的风格指南。

例如,在我的 Python 包中,我有一系列相互调用的函数,因此希望用户能够不时请求打印输出。

例如:

def simple_addition(a, b, silent=True):
    res = a + b
    if not silent: print('The answer is %i' % res)
    return res

这里有标准的参数名称吗?例如 应该使用 "quiet" / "silent" 来抑制所有打印输出。 或者如果 True 应该使用 "verbose" 来要求这个?

基本上,您可以使用 logging module,它使您能够设置所需的日志记录级别,并且记录器将 save/print/export(基于您的配置)记录值。

import logging
logging.warning('Watch out!')  # will print a message to the console
logging.info('I told you so')  # will not print anything

您可以使用以下方式设置记录器的级别:

logging.basicConfig(level=logging.INFO)

还有很多more options there

如果您不想依赖日志记录库,我认为您的解决方案已经pythonic 足够。写起来可能更pythonic一点:

def simple_addition(a, b, silent=True):
    res = a + b
    if not silent:
        print('The answer is %i' % res)
    return res

PEP 8, Other Recommendations 所述,单行 if 语句可以,但不鼓励。

还有其他的可能性。

使用or

使用 or 运算符对条件进行编码可以说不是 pythonic 但我个人认为它读起来不错:"silent or..."、"quiet or..."。见下文:

def simple_addition(a, b, silent=True):
    res = a + b
    silent or print('The answer is %i' % res)
    return res

or 运算符会短路,因此 print 及其参数仅在 silent 为 False 时才被评估,就像使用 if 语句时一样。

缺点是如果 silent 绑定到布尔类型,mypy 类型检查将失败:

$ cat > add.py
def simple_addition(a, b, silent: bool = True):
    res = a + b
    silent or print('The answer is %i' % res)
    return res
^D
$ mypy add.py
add.py:3: error: "print" does not return a value

noop三元

我们也可以这样做:

def noop(*args, **kwargs):
    pass

def simple_addition(a, b, silent=True):
    _print = noop if silent else print
    res = a + b 
    _print('The answer is %i' % res)
    return res

...但感觉很不自然。

我倾向于选择:

def simple_addition(a, b, verbose=True):
    res = a + b
    print('The answer is %i' % res) if verbose else None 
    return res