Pythonic实现安静/详细标志的功能

Ian*_*rts 4 python variables pep8

为了编写pythonic代码,我想知道是否有一个样式指南,涵盖了使用安静或冗长的函数选项.

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

例如:

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

这里是否有标准的arg名称.例如,应使用"安静"/"静音"来抑制所有打印输出.或者应该"详细"用于要求这个如果是真的?

Rud*_*ela 8

如果你不想依赖日志库,我认为你的解决方案已经足够 Pythonic 了。写起来可能更像pythonic:

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

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

还有其他的可能性。

使用 or

使用or运算符对条件进行编码可以说不是 Pythonic,但我个人认为它读起来很好:“沉默或……”、“安静或……”。见下文:

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

or运营商不短路,所以print当沉默是它的参数,只能判断False使用时像if声明。

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

$ 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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

...但感觉相当不pythonic。


Dek*_*kel 7

基本上,您可以使用该logging模块,该模块使您能够设置所需的日志记录级别,并且记录器将保存/打印/导出(基于您的配置)记录的值.

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

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

logging.basicConfig(level=logging.INFO)
Run Code Online (Sandbox Code Playgroud)

还有更多的选择.