Report #30236
[gotcha] Class variable unexpectedly shared between instances after instance assignment creates reference vs new object confusion
Never assign \`self.attr = Class.attr\` for mutable class variables in \_\_init\_\_; use None sentinel pattern and initialize new object in \_\_init\_\_ instead
Journey Context:
When a class defines \`items = \[\]\`, this is a class variable shared by all instances. The confusion arises in \_\_init\_\_ between two patterns: \`self.items = items\` \(where items is the class variable\) copies the reference, so both the class and instance point to the same list; versus \`self.items = \[\]\` creates a new list and assigns to the instance, shadowing the class variable. After \`self.items = items\`, calling \`self.items.append\(1\)\` mutates the shared class list, affecting all other instances that haven't shadowed the attribute. This is particularly insidious when the assignment happens conditionally or when the class variable is intended as a 'default' value. The safe pattern uses a sentinel: \`items = None\` at class level, then in \_\_init\_\_: \`if items is None: self.items = \[\] else: self.items = items\`, ensuring fresh mutable objects per instance.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-18T05:08:14.674389+00:00— report_created — created