how can i check whether a variable is iterable in my code?

S

satoru

hi, all
i want to check if a variable is iterable like a list, how can i
implement this?
 
A

Aidan

satoru said:
hi, all
i want to check if a variable is iterable like a list, how can i
implement this?

this would be one way, though I'm sure others exist:

if hasattr(yourVar, '__iter__'):
# do stuff
 
S

satoru

this would be one way, though I'm sure others exist:

if hasattr(yourVar, '__iter__'):
        # do stuff

thank you,but this will miss out sequences like string just because it
doesn't have an attribute named '__iter__'
 
V

Vito De Tullio

satoru said:
hi, all
i want to check if a variable is iterable like a list, how can i
implement this?

untested

def is_iterable(param):
try:
iter(param)
except TypeError:
return False
else:
return True
 
J

John Machin

thank you,but this will miss out sequences like string just because it
doesn't have an attribute named '__iter__'

str objects have a __getitem__ attribute, as do other built-in
sequence types: unicode, xrange, buffer.
AFAIK if an object has no __iter__ but has a __getitem__, iter(obj)
will create an iterator that calls obj.__getitem__(0),
obj.__getitem__(1), etc until IndexError is raised.
 
T

Terry Reedy

satoru said:
thank you,but this will miss out sequences like string just because it
doesn't have an attribute named '__iter__'

In 3.0, it does. Such consistency is one of the advantages of 3.0.

In at least some 2.x's, str still uses the older __getitem__ iteration
protocol. I am not sure about other built-in sequences.
 
J

James Mills

satoru,

I should point out that the normal
approach is to just try whatever it
is that you're doing, and let it fail
where it fails. For example:

def processSeq(x):
for i in x:
print i

processSeq([1, 2, 3])
processSeq("foobar")
processSeq(5) <-- This will fail.

cheers
James
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,898
Latest member
BlairH7607

Latest Threads

Top