helpful language feature gets less attention than it deserves
YusufAdel
Posted on August 15, 2021
I’m going to give you an introduction to using assertions in Python.
At this point, you might be wondering “What are assertions and what
are they good for?” Let’s get you some answers for that.
At its core, Python’s assert statement is a debugging aid that tests a
condition. If the assert condition is true, nothing happens, and your
program continues to execute as normal. But if the condition evaluates to false, an AssertionError exception is raised with an optional
error message.
Assert in Python — An Example
Here is a simple example so you can see where assertions might come
in handy. I tried to give this some semblance of a real-world problem
you might actually encounter in one of your programs.
Suppose you were building an online store with Python. You’re working to add a discount coupon functionality to the system, and eventually you write the following apply_discount function:
def apply_discount(product, discount):
price = int(product['price'] * (1.0 - discount))
assert 0 <= price <= product['price']
return price
Notice the assert statement in there? It will guarantee that, no mat-
ter what, discounted prices calculated by this function cannot be lower
than $0 and they cannot be higher than the original price of the prod-
uct.
Let’s make sure this actually works as intended if we call this function
to apply a valid discount. In this example, products for our store will
be represented as plain dictionaries. This is probably not what you’d
do for a real application, but it’ll work nicely for demonstrating asser-
tions. Let’s create an example product—a pair of nice shoes at a price
of $149.00:
>>> shoes = {'name': 'Fancy Shoes', 'price': 14900}
By the way, did you notice how I avoided currency rounding issues
by using an integer to represent the price amount in cents? That’s
generally a good idea… But I digress. Now, if we apply a 25% discount
to these shoes, we would expect to arrive at a sale price of $111.75:
>>> apply_discount(shoes, 0.25)
Alright, this worked nicely. Now, let’s try to apply some invalid dis-
counts. For example, a 200% “discount” that would lead to us giving
money to the customer:
>>> apply_discount(shoes, 2.0)
Traceback (most recent call last):
File "<input>", line 1, in <module>
apply_discount(prod, 2.0)
File "<input>", line 4, in apply_discount
assert 0 <= price <= product['price']
AssertionError
As you can see, when we try to apply this invalid discount, our
program halts with an AssertionError . This happens because a
discount of 200% violated the assertion condition we placed in the
apply_discount function
You can also see how the exception stacktrace points out the exact line
of code containing the failed assertion. If you (or another developer
on your team) ever encounter one of these errors while testing the
online store, it will be easy to find out what happened just by looking
at the exception traceback.
This speeds up debugging efforts considerably, and it will make your
programs more maintainable in the long-run. And that, my friend, is
the power of assertions.
REFERENCE: Python Tricks A Buffet of Awesome Python Features by Dan Bader
Posted on August 15, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 12, 2024
November 22, 2023