Python 根据真值优化多个if-else
Python Optimize multiple if-else based on truthy value
我在 Python 中有以下代码,其中基于布尔标志,我需要检查列表计数,想知道是否有更好的方法在 Python 中对此进行编码?
If var_true:
if len(something) > 0:
logger.console (“Something found”)
else:
raise AssertionError(“something was not found”)
If not var_true:
if len(something) == 0:
logger.console (“Something not expected to be found, was not seen”)
else:
raise AssertionError(“something unexpected was found”)
将 else: raise AssertionError
代码替换为实际的 assert
语句(当 运行 处于 -O
模式时可以跳过它,但其行为与您当前的代码相同正常 [调试] 模式):
if var_true:
assert something, "something was not found" # Also remove len checks; sequences are naturally truthy when non-empty
logger.console("Something found")
else:
assert not something, "something unexpected was found" # Same length check removal
logger.console("Something not expected to be found, was not seen")
在测试期间(或者所有时间,如果您从不 运行 和 -O
,您的选择)您将被告知是否违反了您的假设。在发布模式下,您将跳过永远不会命中的测试,并且 运行 会更快一些。
如果这 不是 assert
的情况 永远不会 发生,除非开发人员犯了错误,你不应使用 assert
或 AssertionError
(两者都暗示发生了“不可能”的事情),而应引发其他一些适当的异常,例如ValueError
当提供了无效值时。
我在 Python 中有以下代码,其中基于布尔标志,我需要检查列表计数,想知道是否有更好的方法在 Python 中对此进行编码?
If var_true:
if len(something) > 0:
logger.console (“Something found”)
else:
raise AssertionError(“something was not found”)
If not var_true:
if len(something) == 0:
logger.console (“Something not expected to be found, was not seen”)
else:
raise AssertionError(“something unexpected was found”)
将 else: raise AssertionError
代码替换为实际的 assert
语句(当 运行 处于 -O
模式时可以跳过它,但其行为与您当前的代码相同正常 [调试] 模式):
if var_true:
assert something, "something was not found" # Also remove len checks; sequences are naturally truthy when non-empty
logger.console("Something found")
else:
assert not something, "something unexpected was found" # Same length check removal
logger.console("Something not expected to be found, was not seen")
在测试期间(或者所有时间,如果您从不 运行 和 -O
,您的选择)您将被告知是否违反了您的假设。在发布模式下,您将跳过永远不会命中的测试,并且 运行 会更快一些。
如果这 不是 assert
的情况 永远不会 发生,除非开发人员犯了错误,你不应使用 assert
或 AssertionError
(两者都暗示发生了“不可能”的事情),而应引发其他一些适当的异常,例如ValueError
当提供了无效值时。