Junior — Middle
Can a class be considered completely immutable if it contains such an attribute?
sobes.tech AI
Answer from AI
A class cannot be considered fully immutable if it contains a mutable attribute, such as a list or dictionary. Even if the class itself does not provide methods to modify this attribute, its contents can be changed from outside, which violates the immutability of the object.
For complete immutability, all attributes should be of immutable types (e.g., tuples, strings, numbers) and should not provide access to mutable data structures. If you need to store mutable data, it is better to use copies or special immutable structures.
An example of a mutable attribute that violates immutability:
class ImmutableExample:
def __init__(self, data):
self.data = data # data is a mutable object, such as a list
obj = ImmutableExample([1, 2, 3])
obj.data.append(4) # the object has changed, so the class is not immutable