Descriptor Protocol in Python

Level 5494 keystrokes

This implements the descriptor protocol to create a reusable validation mechanism for class attributes.

Python code

# Define descriptor class for validation
1class Validated:
# Initialize with min and max allowed values
2 def __init__(self, min_val, max_val):
# Store minimum value
3 self.min_val = min_val
# Store maximum value
4 self.max_val = max_val
5
# Called when descriptor is assigned to class attribute
6 def __set_name__(self, owner, name):
# Store the attribute name
7 self.name = name
8
# Called when attribute is accessed
9 def __get__(self, obj, type=None):
# Return value from instance dict
10 return obj.__dict__.get(self.name)
11
# Called when attribute is set
12 def __set__(self, obj, value):
# Validate value is within range
13 if not self.min_val <= value <= self.max_val:
# Raise error with descriptive message
14 raise ValueError(f"{self.name} must be {self.min_val}-{self.max_val}")
# Store valid value in instance dict
15 obj.__dict__[self.name] = value
16
# Class using the descriptor for validation
17class Person:
# age must be between 0 and 150 (inclusive)
18 age = Validated(0, 150)
19
# Create Person instance
20p = Person()
# Set valid age value
21p.age = 25
# Print the validated age
22print(f"Age: {p.age}")

Output

Age: 25
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • _× 35
  • .× 15
  • =× 10
  • ,× 9
  • (× 9
  • )× 9
  • :× 8
  • "× 4
  • {× 4
  • }× 4

More Python examples at level 5

← Python typing practice