Content · Programming · Python

Python Avoid Shared Mutable Class Attributes

Recognize that mutable class attributes are shared across every instance.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

Recognize that mutable class attributes are shared across every instance.

What You Will Learn


A list placed directly on a class is one object shared by all instances until shadowed. This often surprises beginners who expect every instance to have its own collection. Set mutable per-instance state in __init__, or use a dataclass field with default_factory. Class attributes remain appropriate for constants shared by the class.

Class interfaces should preserve their stated invariants. Type annotations describe intent but do not enforce runtime types on their own.

Step-by-Step Example


The example below makes the behavior visible with small input values that you can change safely.

class Basket:
    currency = "USD"

    def __init__(self):
        self.items = []

    def add(self, product):
        self.items.append(product)

first = Basket()
second = Basket()
first.add("Tea")
print(first.items)
print(second.items)
print(first.currency == second.currency)

How the Example Works


  • The class Basket groups data and behavior; its methods run when called on an instance.
  • The variable first holds the result of Basket(). Later lines use that value or inspect how it changes.
  • The variable second holds the result of Basket(). Later lines use that value or inspect how it changes.
  • The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.

Expected output from the example:

['Tea']
[]
True

When You Would Use This


A class becomes useful when several operations must maintain rules around related data. Think about which state belongs to each instance, which operations should be public, and how errors should be reported. Avoid making the design more complex than the underlying task.

Practice: Modify the Code


Move items to a class attribute temporarily and observe the shared-list bug before restoring the fix.

Verify the changed output against the behavior described above, including the relevant invalid or boundary case.

For complete parameters and version details, consult the official Python documentation.

Common Beginner Mistakes


  • Writing items = [] inside the class body for per-customer shopping baskets.
  • Assuming assigning an instance attribute changes that attribute for all other instances.

Key Takeaways


  • Recognize that mutable class attributes are shared across every instance.
  • A list placed directly on a class is one object shared by all instances until shadowed.
  • Apply this operation only after checking the assumptions and input conditions shown in the example.
Share this resourceSend this page to someone who may find it useful.