Descriptor Protocol in Python

Level 5330 keystrokes

This implements the descriptor protocol for attribute validation. __get__ and __set__ control attribute access on instances.

Python code

# Define descriptor class for validation
1class Validator:
# Called when descriptor is assigned to class attribute
2 def __set_name__(self, owner, name):
# Store the attribute name
3 self.name = name
# Called when getting the attribute value
4 def __get__(self, obj, type=None):
# Return value from instance dict
5 return obj.__dict__.get(self.name)
# Called when setting the attribute value
6 def __set__(self, obj, value):
# Validate the value is non-negative
7 if value < 0:
# Raise error for invalid value
8 raise ValueError("Must be >= 0")
# Store value in instance dict
9 obj.__dict__[self.name] = value
10
# Class using the descriptor
11class Product:
# price attribute uses Validator descriptor
12 price = Validator()
13
# Create Product instance
14p = Product()
# Set price through descriptor
15p.price = 100
# Get price through descriptor
16print(p.price)

Output

100
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.

  • _× 21
  • .× 8
  • (× 8
  • )× 8
  • =× 7
  • ,× 6
  • :× 6
  • "× 2
  • [× 1
  • ]× 1

More Python examples at level 5

← Python typing practice