Firstly, what exactly is MyUsefulClass().a? Is it an instance of a ValidatedAttribute class somehow bound to an instance of a MyUsefulClass class?
Yes, that is it exactly.
And secondly, what I'd really like is something like [...] and somehow bind an attribute access to some sort of intercept method, without having to use a whole other descriptor class.
Well, you could overwrite __getattribute__
, as it does intecept every attribute lookup, but it is way more complicated than using descriptors.
Descriptors work for exactly what you are wanting to do (automatic validation). About the only improvement you could make is to also use a metaclass to automatically set the key for you, and then your class code look like this:
class MyUsefulClass(object):
a = ValidatedAttribute(int)
But first get comfortable with descriptors, metaclasses are complex and can be tough to grok.
Oh, and one small change I would make to your ValidatedAttribute
:
def __init__(self, key, default):
self.key = key
self.kind = type(default)
self.default = default
def __get__(self, instance, owner):
if self.key not in instance.__dict__:
return self.default
return instance.__dict__[self.key]