What does Python mean by a writeable attribute?

Question:

I was reading the Python documentation and came across the following line in relation to the __dict__ attribute:

object.__dict__

A dictionary or other mapping object used to store an object’s (writable) attributes.

What is a writable attribute? What is the difference between a writable attribute and other types of attributes in Python?

Asked By: joepianoblaster

||

Answers:

Consider the following example:

class MyObject:
    def __init__(self, val):
        self.value = val

    @property
    def read_only_val(self):
        return self.value

my_obj = MyObject([10])

Writable attributes are those that can be set, e.g. using setattr or =

my_obj.value = [20]
setattr(my_obj, 'value', [20])

The values of these objects can be mutable or immutable, which will decide whether they can be modified in-place or not. "Writable" in the context of object attributes has nothing to do with mutability.

Non-writable attributes cannot be set. In our example, we defined read_only_val as a read-only property, which means we can’t set it. Both these statements throw an AttributeError: can't set attribute.

my_obj.read_only_val = [30]
setattr(my_obj, 'read_only_val', [30])

To further emphasize that "writable" in the context of object attributes has nothing to do with mutability, we can show that there is no problem in mutating the (non-writable) read_only_val attribute:

my_obj.read_only_val.append(40)
print(my_obj.read_only_val) # [20, 40]

Of course, if an attribute had an immutable value, we wouldn’t be able to mutate it, and we would have to set the attributeprovided it’s writable to give it another value.

When we inspect my_obj.__dict__, we see it contains only the writable attribute:

print(my_obj.__dict__)
# {'value': [20, 40]}
Answered By: Pranav Hosangadi
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.