TGViewer
Learn Python Coding Learn Python Coding @pythonre · 40.7K subscribers
Post #9492 2.55K
Why can't you use mutable default values in constructors?

If you set a list or dictionary as the default value, the object is created once and then reused by all instances.
class User:
    def __init__(self, tags=[]):
        self.tags = tags

This results in a change in one instance affecting the others:
u1 = User(); u2 = User()
u1.tags.append("x"); print(u2.tags)

default_factory creates a new object each time the constructor is called, eliminating shared state:
field(default_factory=list)

Thus, each instance receives an independent data structure:
User().tags is User().tags

🔥 Using default_factory is an important practice when working with mutable types and prevents hard-to-detect state errors.

https://t.me/pythonRe 👍
  • ❤ 9
  • 👍 1
More from @pythonre
  1. Oct 9, 20267 Days Certified AI Agents with Python: Autonomous Apps Build autonomous AI agents with Py…
  2. Oct 7, 2026A distinctive bot for subscribing to courses on the most popular educational platforms acr…
  3. Oct 7, 2026Python Lists: A Quick Reference 🐍 * Definition: Lists are ordered, mutable collections th…
  4. Oct 7, 2026📱 270 tools for Python developers The repository contains: 🫡 Linters and formatters; 🫡…
  5. Oct 7, 2026Hands On Python Data Science - Data Science Bootcamp Master Python for Data Science with R…
  6. Oct 6, 2026Post #9851
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →