[Python-ideas] Adding`Unpicklable` to the `collections` module

Masklinn masklinn at masklinn.net
Tue Nov 30 23:08:54 CET 2010

On 2010-11-30, at 20:14 , Éric Araujo wrote:
>> For instance, as of Python 2.7 these blocks of code are roughly
>> equivalent (the first two are in fact identical in effect):
>>    if isinstance(obj, collections.Sized):
>>        doSomethingWith(len(obj))
>>    if hasattr(obj, '__len__'):
>>        doSomethingWith(len(obj))
>>    try:
>>        doSomethingWith(len(obj))
>>    except TypeError:
>>        pass
>> They all test for the same thing: that you can call len() on the object.
> Not exactly: magic methods are looked up on the class, not on the
> instance.

>  That’s why isintance+ABCs is the right test to use here.  See
> http://docs.python.org/dev/reference/datamodel#special-method-names
Due to Python's lookup rule, looking up most (if not all) of the special method on the instance is going to give the same result.

> (The third block also suffers from an over-catching except clause.

> ABCs are not contradictory to duck typing at all:
>>>> import collections
>>>> class Demo:
> ...     def __len__(self):
> ...         return 42
> ...
>>>> isinstance(Demo(), collections.Sized)
> True
> Demo is not required to subclass Sized or register.  ABCs are an
> optional mechanism that implements duck typing, so to speak.
> http://docs.python.org/dev/glossary
> http://docs.python.org/whatsnew/2.6#pep-3119-abstract-base-classes
> http://www.python.org/dev/peps/pep-3119/#abcs-vs-duck-typing

May I know why you're replying that to *my* mail?

More information about the Python-ideas mailing list