Last Updated: January 09, 2021
·
1.158K
· masaya

Convenient use of assert in Python

Recently, I learnt the easy use of assert, so I'd like to make a memo.

when the result is False, assert returns AssertionError.

>>> assert False
AssertionError:

If you connect the assert with comma ( , ) and string, then the string gets displayed after the error as below.

>>> assert False, "it's wrong"
AssertionError: it's wrong

So, if you want to assert an argument in a function, you can easily write a simple check:

def do_something(mode="train"):
    assert mode in ['train', 'test'], "mode only takes either train or test"

By writing like this, a simple check becomes a piece of cake.

>>> do_something(mode='something')
AssertionError: mode only takes either train or test.

That's it for today.

1 Response
Add your response

dude, be aware about assert statements in the shipped packaged code. they're just removed during optimization.

https://stackoverflow.com/a/1838411/5036360

over 1 year ago ·