duck typing assert‏

Steven D'Aprano steve+comp.lang.python at
Fri Nov 9 07:30:24 CET 2012

On Thu, 08 Nov 2012 23:44:54 -0500, Terry Reedy wrote:

> On 11/8/2012 6:40 PM, Steven D'Aprano wrote:
>>  # returns a computed property
> Assuming IFoo is a class and bar is a property attribute of the class,
> is the property object itself, not the computed property of an
> instance.

Given the context we were discussing, namely duck-typing, the examples I 
gave should have been understood as indications, not literal code 
snippets. Yes, it is true that "" returns a property object, and 
"" returns an unbound method (a function in Python 3). But they 
are meant as illustrations, not working code samples. Much the same way 
that we will often talk about "list.append" when what we actually mean is 
the bound append method on some specific, context-dependent list instance.

I am sorry that I did not make that clear and that my terminology was 

But in context, duck-typing classes normally is intended to substitute an 
instance of one class for an instance of another class. In that case, if is a property, and is a method, then you cannot 
substitute an IFoo instance for a Foo instance, or vice versa:

ifoo = IFoo()  # returns a computed attribute

foo = Foo()  # calls the method

In the general case, you cannot use where is 
expected, nor can you use where is expected. Just in 
case it isn't clear what I mean:

Suppose the expected interface is that is a method that 
takes no arguments. matches that interface, because bar is a 
method. But is a property. Suppose it computes an int result. 
Then will try to call an int, and raise TypeError. So ifoo 
cannot be used in place of foo, and types IFoo and Foo are not duck-type 
compatible. Likewise if the expected interface is for a property or 
attribute, such as would give. Then returns an unbound 
method. Instead of getting an error there and then, you might not get an 
error until much later, say:

integers = [1, 3,,, 42]
# much later
y = sum(integers)  # raises TypeError because is a method

So, duck-typing classes IFoo (with bar a property) and Foo (with bar a 
method) will not in general work, and looks(IFoo).like(Foo) should return 


More information about the Python-list mailing list