flâneur — a map of the web's best reading

Python Gotcha: Mutable Default Optional Arguments · Ponderings of an Andy

andrewwegner.com · 712 words · saved by 1 readers

A quick walk through of why mutable defaults on optional arguments is bad in Python.

Article Contents The Problem What's going on? Another example Last Example What can I do about this? The Problem ¶ Without running this in your IDE, what does the following code output? Forgive the use of vins , I work in the logistics field and deal with vehicle identification numbers frequently. def add_vin(this_vin: str, vins: list = []): if this_vin not in vins: vins.append(this_vin) return vins add_vin("VIN1") add_vin("VIN2") print(add_vin("VIN3")) You probably saw that vins is an optional argument and that it defaults to an empty list. Run this function three times without passing it a l

Explore this link on the map →

related reading