2.2 descriptor API

Daniel Popowich sfconsulting at attbi.com
Thu Apr 4 11:06:02 EST 2002


I have been working with the new 2.2 descriptor API and have a
question about the __get__ method.

If I have the following:

    class Foo(object):
       x = mydescriptor()

where mydescriptor is a class that defines  __get__, __set__ and
__delete__, then the following code:

    f = Foo()
    f.x = 1
    print f.x
    del f.x

behaves as you would expect and calls the __set__, __get__ and
__delete__ methods in turn.  No problems here.

Now to the meat of my question which relates to descriptor usage when
referenced as class attributes...

If I write:

   Foo.x = 1

The class attribute x is overwritten with the integer 1.  The __set__
method is not involved.  If I write:

   del Foo.x

The x attribute is removed from the class namespace.  The __delete__
method is not involved.

HOWEVER, if I write:

   Foo.x

The __get__ method is called!!!  WHY??  Why isn't the instance of my
descriptor returned as it would be with any other object?  In fact, the
canonical implementation of a __get__ method that I have seen thus far
in examples...

   def __get__(self, inst, type=None):
       if inst is None: return self
       ...

implements exactly what one would expect to happen: return the
instance of the descriptor.  But why do I have to code this?

While I'm on this subject, could someone explain the second argument?
I have not seen any code that makes use of it and I'm not sure what
it's about.

In summary:

1.  Why is the __get__ method called on a descriptor when it is
    referenced as a class attribute?

2.  What is the purpose behind the second argument; does someone have
    an example of how or when I would make use of it?


Thanks,

Daniel Popowich



More information about the Python-list mailing list