[Python-Dev] Duck-typing self

Christian Heimes lists at cheimes.de
Thu Feb 19 01:50:37 CET 2009


Steven Bethard wrote:
>> Is it a design decision that duck-typing self does not work or is there a
>> technical reason? From a practical standpoint it seems that being able to
>> duck-type self has merit, for example in unit testing complex classes.
> 
> Works for me in 3.0:

It works in 3.0 because we have lifted some restrictions (and increased
speed as a neat side effect). In Python 2.x the type checking speed with
negligible, but Python 3's abc system with the new __instancecheck__()
and __subclasscheck__() hooks are a real speed drain.

In 2.x a class objects wrap their functions in a method wrapper. The
method wrapper does the type check. You can get around the type check by
using the im_func attribute of the method wrapper.

Python 2.5.2 (r252:60911, Oct  5 2008, 19:29:17)
[GCC 4.3.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Foo(object):
...     def bar(self):
...         print(self.attr)
...
>>> Foo.bar
<unbound method Foo.bar>
>>> class Duck(object):
...     attr = "python"
...
>>> Foo.bar(Duck())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unbound method bar() must be called with Foo instance as
first argument (got Duck instance instead)
>>> Foo.bar.im_func
<function bar at 0x7f6ec83a01b8>
>>> Foo.bar.im_func(Duck())
python


In 3.0 the unbound method wrapper is gone and class objects return the
pure function. Without the type checking of the unbound method wrapper
the restriction is gone.

Python 3.0.1 (r301:69655, Feb 15 2009, 23:28:13)
[GCC 4.3.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Foo(object):
...     def bar(self):
...         print(self.attr)
...
>>> Foo.bar
<function bar at 0x7f0f747666b0>
>>> class Duck(object):
...     attr = "python"
...
>>> Foo.bar(Duck())
python

HTH
Christian



More information about the Python-Dev mailing list