Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What does Python mean by a writeable attribute?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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]}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading