如何在调用 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/