[Python-Dev] Duck-typing self (original) (raw)
Christian Heimes lists at cheimes.de
Thu Feb 19 01:50:37 CET 2009
- Previous message: [Python-Dev] Duck-typing self
- Next message: [Python-Dev] Duck-typing self
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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 class Duck(object): ... attr = "python" ... Foo.bar(Duck()) Traceback (most recent call last): File "", line 1, in TypeError: unbound method bar() must be called with Foo instance as first argument (got Duck instance instead) Foo.bar.imfunc <function bar at 0x7f6ec83a01b8> Foo.bar.imfunc(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
- Previous message: [Python-Dev] Duck-typing self
- Next message: [Python-Dev] Duck-typing self
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]