[Python-Dev] Descriptor write-up [Draft: Please comment]

Guido van Rossum guido@python.org
Sun, 01 Jun 2003 09:02:58 -0400


> Something about data descriptors (ones defining __set__) and method
> descriptors (ones not defining __set__) and their differences would be
> cool (particularly as this is something I don't quite understand!).

The main difference is that a non-data descriptor (they're not just
for methods) can be overridden by something in the instance __dict__,
while a data descriptor *always* overrides the instance __dict__.

This is done mostly for backwards compatibility, although it is useful
enough to call it a feature: you can define a method, and then assign
some other function (or callable) to the corresponding instance
variable, and this will hide the method *for that instance*.  (Sort of
like treating the instance as a subclass of the class, but not
quite. :-)

Data descriptors exist so that you can also have a different behavior,
which is also useful: setting the attribute calls the data
descriptor's __set__ method and doesn't affect the instance __dict__.
This is so that you can implement properties without overriding
__setattr__ (the horrible overkill hack that had to be used before 2.2
to trap setting even a single attribute).

And note that to create a read-only attribute, you create a data
descriptor whose __set__ raises an exception.  (This explains why a
property which has only a 'get' function still has the __set__
attribute.)

--Guido van Rossum (home page: http://www.python.org/~guido/)