Type Hints and Testing
Type hints say what kind of value a variable or function uses. Python doesn't enforce them while running, but editors and tools like mypy use them to catch mistakes early.
As programs grow and teams get bigger, it becomes hard to remember what every function expects. Type hints document this directly in the code, editors use them to warn you about mistakes as you type, and tools like mypy check whole projects. They're optional, but most professional Python code now uses them.
Testing with assert
A test is code that checks your code. The simplest test uses assert: if the condition is false, Python stops with an error.
Tests are how you know your code still works after you change it. Without tests, every change is a risk; with them, you run one command and see instantly if anything broke. Companies expect developers to write tests, and writing them also makes you think more clearly about what your code should do.
pytest: the standard test tool
Put tests in files named test_*.py, write functions named test_*, and run pytest. It finds and runs them all and shows which ones failed.
# cart.py
def cart_total(items, coupon=None):
total = sum(price * qty for price, qty in items)
if coupon == "SAVE10":
total = total * 0.9
return round(total, 2)
# test_cart.py
import pytest
from cart import cart_total
def test_empty_cart():
assert cart_total([]) == 0
def test_total_adds_quantities():
assert cart_total([(100, 2), (50, 1)]) == 250
def test_coupon_takes_ten_percent():
assert cart_total([(200, 1)], coupon="SAVE10") == 180
@pytest.mark.parametrize("items, expected", [([(10, 1)], 10), ([(10, 3)], 30)])
def test_many_cases(items, expected):
assert cart_total(items) == expectedpip install pytest
pytest -q- Type hints document types; mypy checks them.
- assert is the simplest test.
- pytest runs test_*.py files and shows failures clearly.
- Add a test for every bug you fix.
