[Tutor] recursive problem

Steven D'Aprano steve at pearwood.info
Sun Sep 12 02:10:53 CEST 2010


On Sun, 12 Sep 2010 09:03:49 am Walter Prins wrote:

> So, perhaps it's an idea to call dir() on a given object and see
> whether the object provides the necessary methods to function, e.g.
> __iter__, __delitem__, __setitem__ and friends?

There's no need to do this:

attributes = dir(obj)
if '__iter__' in attributes and '__len__' in attributes:
    print "Quacks like a list"
else:
    print "Not like a list"


when you can do this:


if hasattr(obj, '__iter__') and hasattr(obj, '__len__'):
    print "Quacks like a list"
else:
    print "Not like a list"


or this:

try:
    obj.__iter__
    obj.__len__
except AttributeError:
    print "Not like a list"
else:
    print "Quacks like a list"


or even 

try:
    iter(obj)
    len(obj)
except TypeError:
    print "Not like a list"
else:
    print "Quacks like a list"


Where possible, the last version is to be preferred, because it doesn't 
care about internal details which might change.



-- 
Steven D'Aprano


More information about the Tutor mailing list