Python Bug: Default Args in NamedTuple vs Dataclass

One of the trickiest Python bugs: mutable default arguments. If you define tags: list = [] on a NamedTuple, every instance ends up sharing the same list. With dataclass, this pattern is rejected. You must use field(default_factory=list), which creates a fresh list each time. My free interactive course lets you run both versions in your browser and compare the results yourself. 🚀 Try the course: https://bit.ly/4bdtQMg #Python #DataScience #InteractiveLearning #dataclass

  • No alternative text description for this image

Yes, and the same applies to other mutable defaults like dict and set: default_factory=dict default_factory=set 😉

Technical debt often stems from these subtle shared state vulnerabilities that default_factory is designed to prevent. Our approach at Recursyx emphasizes using explicit factories to ensure data integrity across independent class instances.

Like
Reply

Default mutable arguments are a classic "gotcha" that I’ve seen trip up even senior devs during late-night debugging sessions. Switching to default_factory in dataclasses is one of those small shifts that saves hours of tracking down shared state bugs. 

Imutable types are default-recommended

See more comments

To view or add a comment, sign in

Explore content categories