如果您不想依赖日志库,我认为您的解决方案已经 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。