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 validation1class Validated: # Initialize with min and max allowed values2 def __init__(self, min_val, max_val): # Store minimum value3 self.min_val = min_val # Store maximum value4 self.max_val = max_val5 # Called when descriptor is assigned to class attribute6 def __set_name__(self, owner, name): # Store the attribute name7 self.name = name8 # Called when attribute is accessed9 def __get__(self, obj, type=None): # Return value from instance dict10 return obj.__dict__.get(self.name)11 # Called when attribute is set12 def __set__(self, obj, value): # Validate value is within range13 if not self.min_val <= value <= self.max_val: # Raise error with descriptive message14 raise ValueError(f"{self.name} must be {self.min_val}-{self.max_val}") # Store valid value in instance dict15 obj.__dict__[self.name] = value16 # Class using the descriptor for validation17class Person: # age must be between 0 and 150 (inclusive)18 age = Validated(0, 150)19 # Create Person instance20p = Person()# Set valid age value21p.age = 25# Print the validated age22print(f"Age: {p.age}")Output
Age: 25
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