In this Python lesson you will learn how to use assert. This will be a proof that you are truly the Python pro.
Do you know what is the difference between Python professionalist and beginner?
Python code of experienced Python developer takes care about correctness of the data.
Let’s see how to use assert for simple data validation check.
I’ve used assert to take care about the data to be validated. In my example I’m sure that the delivery date cannot be earlier than order date. I used assert to take care about dates validation check.
import datetime as dt order_date = dt.date(2022, 1, 1) delivery_date = dt.date(2022, 1, 1) assert order_date <= delivery_date, 'Delivery date can\'t be earlier than order date'
Even when both dates will be the same (technically it is possible to order and deliver the same date) nothing will happen. After you will run the code in such shape literally nothing will happen. Meaning that the code can move on because assert will not find the problem here.
And what will happen when assert will find date validation error?
import datetime as dtorder_date = dt.date(2022, 6, 1)
delivery_date = dt.date(2022, 1, 1)
assert order_date <= delivery_date, 'Delivery date can\'t be earlier than order date'
Assert properly checked that delivery date is earlier than order date which we agreed is not proper. That's how assert saved us from wrong date to be provided. Thank's to assert we checked that our code was working wrongly.
This is how use of assert found a bug in my Python code.