Created
January 18, 2026 13:13
-
-
Save unixnut/91717546cdadfca2028ab6a20faddbc1 to your computer and use it in GitHub Desktop.
Example of Python generic descriptor from @Carberra; source: https://youtube.com/watch?v=l0T4jvuP0H8
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import abc | |
| from typing import Generic, TypeVar, cast | |
| T = TypeVar("T") | |
| class Validator(Generic[T]), metaclass=abc.ABCMeta): | |
| def __set_name__(self, owner: type, name: str) -> None: | |
| self.name = name | |
| self.private_name = "_" + name | |
| def __get__(self, obj: object, objtype: type | None = None) -> T: | |
| return cast(T, getattr(obj, self.private_name)) | |
| @abc.abstractmethod | |
| def __set__(self, obj: object, value: T) -> None: | |
| pass | |
| class AgeValidator(Validator[int]): | |
| def __set__(self, obj: object, value: int) -> None: | |
| if value < 0: | |
| raise ValueError(f"{self.name!r} must be positive") | |
| setattr(obj, self.private_name, value) |
unixnut
commented
Jan 18, 2026
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment