Inconsistent behavior of descriptors
Denis S. Otkidach
ods at strana.ru
Wed Oct 1 08:02:47 EDT 2003
On Wed, 1 Oct 2003, John Roth wrote:
JR> The behavior of descriptors is documented in the article on
JR> the python web site. You might have to hunt a bit to find
JR> it.
http://users.rcn.com/python/download/Descriptor.htm
"The implementation works through a precedence chain that gives
data descriptors priority over instance variables, instance
variables priority over non-data descriptors, and assigns lowest
priority to __getattr__ if provided."
I can't see any reason why "data descriptors" have priority over
instance variables anyway.
JR> The reason for the inconsistency is simply that descriptors
JR> with only a __get__ method are used for methods, functions
JR> and similar entities, while descriptors with both __get__
JR> and
JR> __put__ are used for properties and similar entities.
There are many examples when data (in common sense) descriptors
are used with the only __get__ method defined, i.e. non-data
descriptors in your terms. Here are two I use most frequently:
class CachedAttribute(object):
def __init__(self, method, name=None):
self.method = method
self.name = name or method.__name__
def __get__(self, inst, cls):
# Some tricks here to walk around bug in Python 2.2 are
# skiped
result = self.method(inst)
setattr(inst, self.name, result)
return result
class ReadAliasAttribute(object):
def __init__(self, name):
self.name = name
def __get__(self, inst, cls):
return getattr(inst, self.name)
JR> It's useful to be able to put a unique version of a function
JR> or method in an instance, it would completely subvert the
JR> meaning of a property if you could do so.
Why? You can't do it directly anyway if __set__ method is
defined.
--
Denis S. Otkidach
http://www.python.ru/ [ru]
More information about the Python-list
mailing list