Writing Custom Validators with Descriptors
Descriptors shine for reusable data validation across multiple fields without duplicating `@property` getters and setters in every class 🛡️.
class StringField:
def __set_name__(self, owner, name):
self.name = name
def __set__(self, instance, value):
if not isinstance(value, str):
raise TypeError(f"{self.name} must be a string! 🛑")
instance.__dict__[self.name] = value
def __get__(self, instance, owner):
return instance.__dict__.get(self.name, "")
class User:
username = StringField()
u = User()
u.username = "octocat"
print(u.username) # 'octocat' 🛡️
# 65. Writing Custom Validators with Descriptors Descriptors shine for reusable data validation across multiple fields without duplicating `@property` getters and setters in every class 🛡️. ```python class StringField: def __set_name__(self, owner, name): self.name = name def __set__(self, instance, value): if not isinstance(value, str): raise TypeError(f"{self.name} must be a string! 🛑") instance.__dict__[self.name] = value def __get__(self, instance, owner): return instance.__dict__.get(self.name, "") class User: username = StringField() u = User() u.username = "octocat" print(u.username) # 'octocat' 🛡️ ``` `__set_name__` was introduced in Python 3.6 so descriptors automatically learn the variable name assigned to them on the class without boilerplate! 🛡️ --- ### Question What is the purpose of `__set_name__(self, owner, name)` in modern Python descriptors? 🧠 - [ ] a. Captures the attribute name assigned to the descriptor on the owner class 🛡️ - [ ] b. Changes the process name in Linux htop - [ ] c. Renames the owner class in sys.modules - [ ] d. Encrypts the variable name using SHA-256 --- ### Challenge Create descriptor `NonEmptyStr` whose `__set__` raises `ValueError` if `value == ''`, otherwise sets `instance.__dict__[self.name] = value`. Test on class `Doc` with `title = NonEmptyStr()`. Set `d = Doc()`, `d.title = 'Manual'`, print `d.title`. 🎯 <details> <summary>Solution</summary> ```python class NonEmptyStr: def __set_name__(self, owner, name): self.name = name def __set__(self, instance, value): if value == "": raise ValueError("Empty string not allowed") instance.__dict__[self.name] = value def __get__(self, instance, owner): return instance.__dict__.get(self.name, "") class Doc: title = NonEmptyStr() d = Doc() d.title = "Manual" print(d.title) ``` </details>