Skip to content

Instantly share code, notes, and snippets.

@unixnut
Created January 18, 2026 13:13
Show Gist options
  • Select an option

  • Save unixnut/91717546cdadfca2028ab6a20faddbc1 to your computer and use it in GitHub Desktop.

Select an option

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

unixnut commented Jan 18, 2026

Copy link
Copy Markdown
Author
class Person:
    age = AgeValidator()

    def __init__(self, name: str, age: int) -> None:
        self.name = name
        self.age = age


if __name__ == "__main__":
    p = Person("John", 3) 
    print(p.age)
    q = Person("Amy" , 16)
    q.age = -10

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment