1

How do I run multiple commands after calling an assert statement? For example, here's what I would like to do (without using assert):

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

This does exactly what I want, but it seems more Pythonic to use assert in this case. I cannot figure out how to do multiple things after calling assert. Here's what I'm trying to do (but with incorrect syntax):

x = False
assert x == True, my_func() "My statement"
5
  • 2
    Why would it be more Pythonic to use assert? On the contrary, using exceptions is the right way. Commented Jan 3, 2018 at 11:48
  • 1
    It just seemed like a natural place to use assert, but I guess not. I'll use the exception then. Commented Jan 3, 2018 at 11:50
  • I would suggest using a try statement here, in which case you can do proper exception handling and execute multiple commands if something goes right or wrong. Commented Jan 3, 2018 at 11:53
  • 2
    Could you try with assert x == True, [my_func(), "My statement"][1] Commented Jan 3, 2018 at 11:59
  • Nice Adbul, that works as well Commented Jan 3, 2018 at 12:01

1 Answer 1

1

You could do

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

DEMO

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

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

OUTPUT

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
Sign up to request clarification or add additional context in comments.

1 Comment

Clever solution. But in my opinion still a lot harder to read then the classic if not x: ....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.