is parameter an iterable?

Rocco Moretti roccomoretti at hotpop.com
Tue Nov 15 20:39:47 CET 2005


marduk wrote:
> On Tue, 2005-11-15 at 11:01 -0800, py wrote:
> 
>>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.  So I need a way to make sure that the argument is an
>>iterable before using it.  I know I could do...
>>
>>def foo(inputVal):
>>    if isinstance(inputVal, (list, tuple)):
>>        for val in inputVal:
>>            # do stuff
>>
>>...however I want to cover any iterable since i just need to loop over
>>it.
>>
>>any suggestions?
> 
> You could probably get away with 
> 
> if hasattr(inputVal, '__getitem__')

No, you probably couldn't.

##################
 >>> def g(s):
	for i in xrange(s):
		yield i+s

		
 >>> m = g(5)
 >>> hasattr(m, '__getitem__')
False
###################

I'd do something like:

#####################
def foo(inputVal):
     try:
	iter(inputVal) # Can you change it into an interator?
     except TypeError:
         # Return Error Code
     else:
         for val in inputVal:
             # do stuff
#######################

Again, you'll have to be careful about strings.



More information about the Python-list mailing list