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 👍
