If your pytest files start with the same four lines of setup in every test, you are paying for it twice: once in reading, and again every time the setup changes. Fixtures fix both. This post walks through the core of them with one small shopping cart, including the part people skip: cleanup with yield .
The problem
Here is a small cart, shop.py :
DISCOUNTS = { }
def register_discount ( code , percent ) : DISCOUNTS [ code ] = percent
def remove_discount ( code ) : del DISCOUNTS [ code ]
class Cart : def __init__ ( self ) : self . lines = [ ]
def add ( self , name , price , quantity = 1 ) : if quantity < 1 : raise ValueError ( f "quantity must be at least 1: {quantity}" ) self . lines . append ( ( name , price , quantity ) )
def total ( self , code = None ) : amount = sum ( price * quantity for _ , price , quantity in self .…