Properties with validation in Python
A property turns attribute access into a method call, so invariants hold.
class Run:
def __init__(self, accuracy):
self.accuracy = accuracy
@property
def accuracy(self):
return self._accuracy
@accuracy.setter
def accuracy(self, value):
if not 0 <= value <= 100:
raise ValueError(f"accuracy out of range: {value}")
self._accuracy = float(value)
run = Run(97.5)
print(run.accuracy)
try:
run.accuracy = 140
except ValueError as exc:
print(exc)
How it works
- The getter is decorated with
@property. - The setter is
@name.setterand validates before storing. - Callers still write plain attribute syntax.
Keywords and builtins used here
Runaccuracyasclassdefexceptfloatifprintraisereturnselftry
The run, in numbers
- Lines
- 21
- Characters to type
- 370
- Tokens
- 95
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 54 seconds.
Step 2 of 3 in Attributes & descriptors, step 33 of 53 in Pythonic Python.