Python Class Variable Mutation Trap Explained for Experienced Developers
A common Python pitfall involves mutable class variables being shared across all instances, producing unexpected behavior. When a list is defined as a class attribute, all instances reference the same object, so mutations like append affect every instance simultaneously. This differs from immutable types such as integers, where augmented assignment creates a new instance variable rather than modifying the class-level object. The correct fix is to initialize mutable attributes inside __init__, ensuring each instance gets its own copy. Class variables remain appropriate for constants, shared configuration, or carefully managed class-wide counters when modified explicitly through the class name.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in