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.
Written by masaya
Related protips
1 Response
dude, be aware about assert
statements in the shipped packaged code. they're just removed during optimization.
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Python
Authors
Related Tags
#python
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#