PEP 246 revision

Magnus Lie Hetland mlh at selje.idi.ntnu.no
Fri Mar 4 04:34:12 EST 2005


In article <1109767002.529330.56850 at f14g2000cwb.googlegroups.com>,
boisgera at gmail.com wrote:
>
>
>I had a look at the new reference implementation of PEP 246
>(Object Adaptation) and I feel uneasy with one specific point
>of this new version. I don't fully understand why it checks
>if *the type of* the protocol has a method "__adapt__":
>
>    ...
>    # (c) then check if protocol.__adapt__ exists & likes obj
>    adapt = getattr(type(protocol), '__adapt__', None)
>    ...
>
>As a consequence of this change, you can't define a protocol
>as a class that implements __adapt__ anymore.

How about an instance of such a class?

>    class Protocol(object):
>        def __adapt__(self, obj):
>            ...

If you instantiate this class, the object's type will have the
__adapt__ attribute...

This is the way it works with other special methods (i.e.
__foo__-methods) in Python, too. Instead of looking in the object (or
class) in question, Python checks the *type* of the object (or class).
That's the general rule -- no reason to make an exception here. (In
fact, there is every reason *not* to make an exception, IMO.)

A good example of why this makes sense is the __call__ method. Imagine
what would happen if Python looked for this in the object itself,
instead of in the type of the object... Now imagine we defined this
class:

  class Foo(object):
      def __call__(self):
          print "Howdy!"

If, under the "new lookup rule", we tried to instantiate this class,
we'd get:

  >>> foo = Foo()
  Howdy!

... and no instance. We're calling the Foo-object, and the
__call__-method we defined gets called.

Instead, of course, Python has the wisdom to check the *type* of the
object for such special calls -- and thus uses object.__call__
instead, which (obviously) instantiates the class just like we want it
to.

So: The scenario needn't be as complex as in your example, as long as
you use instances instead of classes as protocols.

(I guess the case could be made for using classes as protocols, but I
suspect the case would be mainly syntactical...)

- M

-- 
Magnus Lie Hetland               Time flies like the wind. Fruit flies
http://hetland.org               like bananas.         -- Groucho Marx



More information about the Python-list mailing list