🐍 Python

Updated at 2018-06-09 13:54

Use asserts to write down your assumptions. Only use asserts to catch bugs, they are not meant for run-time errors.

  • assert does nothing if it is true.
  • If false, it will raise AssertionError exception with the given message.
assert True
assert False, 'this failed because of that'

name: str = ''
assert len(name) > 0, 'name cannot be empty'
# => AssertionError: name cannot be empty

Asserts are great because they pinpoint to the exact line of code where your assumptions were not true.

from typing import Dict

def apply_discount(product: Dict[str, float], discount: float) -> float:
    price = int(product['price'] * (1.0 - discount))
    assert 0 <= price <= product['price']
    return price

assert apply_discount({'price': 100.0}, 0.5) == 50
assert apply_discount({'price': 100.0}, 1.0) == 0
apply_discount({'price': 100.0}, 1.05)
# => AssertionError
# Traceback:
#   ...
#   File "<input>", line 5, in apply_discount
#     assert 0 <= price <= product['price']
# AssertionError

Don't use assertions for auth checks or data validation. You can disable assertions with -O and -OO command-line flags and PYTHONOPTIMIZE environment variable. Assertions are rarely disable though.

def delete_product(product_id: int, user: User):
    assert user.is_admin(), 'must be admin'
    assert store.has_product(product_id), 'unknown product'


  • Python Tricks The Book, Dan Bader
  • Fluent Python, Luciano Ramalho