Avoid using global/class-level mutable datatypes like list/dicts

Class-level variables that are assigned with mutable datatypes are like
global static variables, they refer to the same list or dict and can be
modified/accessed via multiple instance or through the class itself,

>>> class Foo:
        bar = []
>>> a, b = A(), A()
>>> a.bar.append(10)
>>> a.bar
[10]
>>> b.bar
[10]
>>> Foo.bar
[10]
>>> class A:
        def __init__(self):
           self.bar = []
>>> a, b = A(), A()
>>> a.bar.append(10)
>>> a.bar
[10]
>>> b.bar    
[]
>>> Foo.bar
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'Foo' has no attribute 'bar'

To avoid using the same global list/dict across multiple instances we should
avoid initializing class/global variables with a mutable datatypes like list/dict

Comments

Popular posts from this blog

Multiple repeat error when the regex has multiple wildcards in python re module

Weakref proxy is for instance only ...