In Raymond Hettingers Mental Game on YouTube:
class Validator:
def __set_name__(self, owner, name):
self.private_name = f'_{name}'
def __get__(self, obj, objtype=None):
return getattr(obj, self.private_name)
def __set__(self, obj, value):
self.validate(value)
setattr(obj, self.private_name, value)
Daw-Ran Liou states in Writing descriptors in Python 3.6+:
[...] instead of using builtin function getattr and setattr, we need to reach into the dict object directly, because the builtins would be intercepted by the descriptor protocols too and cause the RecursionError.
class Validator:
def __set_name__(self, owner, name):
self.name= name
def __get__(self, obj, objtype=None):
return obj.__dict__[self.name]
def __set__(self, obj, value):
self.validate(value)
obj.__dict__[self.name] = value
But Matthew Egans Describing Descriptors on YouTube says:
from weakref import WeakKeyDictionary
class Validator:
def __init__(self):
self.data = WeakKeyDictionary()
def __get__(self, obj, owner):
return self.data[obj]
def __set__(self, obj, value):
self.validate(value)
self.data[obj] = value
What would be the correct way to implement descriptors?