Python › Descriptors & Properties
How does @property's read-only behavior (no setter defined) actually raise an AttributeError, and how would you customize that error message?
AdvancedAnswer
If only a getter is defined (no @x.setter), attempting to ASSIGN to the property raises `AttributeError: can't set attribute` by default; to provide a more descriptive custom message, explicitly define a setter that always raises your own AttributeError with a clearer explanation.
class ReadOnly:
@property
def value(self):
return 42
@value.setter
def value(self, new_value):
raise AttributeError("'value' is read-only and cannot be modified after creation")
r = ReadOnly()
# r.value = 99 # AttributeError: 'value' is read-only and cannot be modified after creationReal-world example Providing a clearer, more helpful error message when code mistakenly tries to set a computed, read-only property.