I'm trying to use inspect.getmembers()
to list all the writeable attributes of a class. Is there a way to query if a class attribute is readonly or writeable?
Edit: I'm using the first solution from https://stackoverflow.com/a/3818861/2746401 and get an error when trying to copy read-only attributes (e.g. __doc__
). I want to filter our these read-only properties and only copy the writeable ones
Most names will be settable by default. The exceptions are the data descriptor objects and classes that define the __setattr__
hook.
A data descriptor is any attribute of the class that has a __get__
method and at least either a __set__
or a __delete__
method. These methods are used when you try to set or delete the attribute on an instance of the class.
Data descriptors with a __set__
method may not be writeable, and it'll depend on the exact descriptor implementation what they'll allow. A property
object is such a data descriptor; if the property
has a fset
attribute set to None
it won't be writeable. If property().fset
is not set to None
but to a callable, then that callable determines if the attribute is writeable.
In addition, any data descriptor with only a __delete__
method can't be written either, the lack of a __set__
method results in a AttributeError
when you try to set the attribute name on the instance.
A __setattr__
hook intercepts all attribute setting, and can prevent any such action to fail. There is a corresponding __delattr__
hook too, which matters if you want to count deleting attributes as writing.
In other words, this is really hard to determine, not in a generic way, once descriptors or a __setattr__
hook are involved.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With