Python 在断言后运行多个命令

标签 python python-3.x assert

如何在调用 assert 语句后运行多个命令?例如,这是我想做的(不使用断言):

x = False
if x != True:
    my_func()
    raise ValueError("My statement")

这正是我想要的,但在这种情况下使用 assert 似乎更Pythonic。我不知道如何在调用 assert 后执行多项操作。这是我想要做的(但语法不正确):

x = False
assert x == True, my_func() "My statement"

最佳答案

你可以这样做

assert x == True, [my_func(), "My statement"][1]

演示

def my_func():
    print("my function")

x = False
assert x == True, [my_func(),  "My statement"][1]

输出

my function
Traceback (most recent call last):
  File "C:/Users/abdul.niyas/AppData/Local/Programs/Python/Python36-32/a.py", line 5, in <module>
    assert x == True, [my_func(),  "My statement"][1]
AssertionError: My statement

关于Python 在断言后运行多个命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48076764/

相关文章:

不是来自文件系统的 Python 包

python - 如何从平面文件(Gene Ontology OBO 文件)生成递归树状字典?

django - 设置可选用户名 django 用户

python - 在 python 中测试副作用

c# - TDD - 为什么这个 Assert.AreSame 通过?

python - 与 Photoshop 相比,OpenCV Warpaffine 的质量较低

python - 在django models.py中如何使项目表的剩余数量列自动更改?

python - python中的时间数据格式

将十六进制转换为单精度 IEEE-754 浮点的 Python 程序

vhdl - 如何在VHDL中正确使用assert?