【问题标题】:Pythonic implementation of quiet / verbose flag for functions函数的安静/详细标志的 Pythonic 实现
【发布时间】:2022-05-04 09:37:08
【问题描述】:

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

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

例如:

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

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

【问题讨论】:

标签: python variables pep8


【解决方案1】:

如果您不想依赖日志库,我认为您的解决方案已经 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 但我个人认为它读起来很好:“沉默或......”,“安静或......”。见下文:

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

or 运算符会短路,因此 print 及其参数仅在静默为 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

...但感觉很不合Python。

【讨论】:

    【解决方案2】:

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

    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

    【讨论】:

    • 请注意,logging.DEBUG 可能是适合 OP 的级别。
    • 这不是去stderr吗?
    【解决方案3】:

    我倾向于:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-05
      • 1970-01-01
      • 2013-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多