is parameter an iterable?

Steven D'Aprano steve at REMOVEMEcyber.com.au
Tue Nov 15 21:30:40 EST 2005


lmaycotte at gmail.com wrote:

> Maybe this helps:

Unfortunately, it doesn't. If you read the sample code 
the original poster first gave, you will see that Py's 
example is virtually the same as yours:

[original code]
def foo(inputVal):
     if isinstance(inputVal, (list, tuple)):
         for val in inputVal:
             # do stuff

It uses the same program logic, only the implementation 
is different: your code tests the object's type, and 
compares it to the type of list and tuple. Py's code 
tests the object's type, comparing it to lists and tuples.

Type testing gives less information than using 
isinstance, and takes more work to do it. For instance, 
Py's code will correctly work with subclasses of lists, 
yours will wrongly reject them.

Check Py's requirements carefully:

"I have function which takes an argument.  My code 
needs that argument to be an iterable (something i can 
loop over)...so I dont care if its a list, tuple, etc."

Notice the "etc"? There are lots of iterables other 
than lists and tuples. There are xrange objects, files, 
strings, buffers, sub-classes of all of those, classes 
that implement __getitem__(), classes that implement 
next(), and probably more things that I have forgotten.

Your code doesn't check for any of those.


-- 
Steven.




More information about the Python-list mailing list