✳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
- 6 | Functions Revisited - The Python Coding Bookthepythoncodingbook.com
- Programming FAQ — Python 3.14.6 documentationdocs.python.org
- 2.4 Mutable Datacomposingprograms.com
- A half-hour to learn Rustfasterthanli.me
- Variables and Mutability - The Rust Programming Languagedoc.rust-lang.org
- References and Borrowing - The Rust Programming Languagedoc.rust-lang.org
- Emulating pass-by-value behaviour in Python - Stack Overflowstackoverflow.com
- Facts and myths about Python names and values | Ned Batcheldernedbatchelder.com
- styleguide | Style guides for Google-originated open-source projectsgoogle.github.io
- Reading 11: Recursive Data Typesweb.mit.edu
- Immutable object - Wikipediaen.wikipedia.org
- Copying data is wasteful, mutating data is dangerouspythonspeed.com