473,569 Members | 2,735 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

is parameter an iterable?

py
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(inpu tVal, (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?

Nov 22 '05 #1
70 3993
On 15 Nov 2005 11:01:48 -0800,
"py" <co*******@gmai l.com> 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(inpu tVal, (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?


Just do it. If one of foo's callers passes in a non-iterable, foo will
raise an exception, and you'll catch it during testing. Watch out for
strings, though:
def foo(i): ... for j in i:
... print j foo([1, 3, 4, 5, 6, 7]) 1
3
4
5
6
7 foo("hello")

h
e
l
l
o

Regards,
Dan

--
Dan Sommers
<http://www.tombstoneze ro.net/dan/>
Nov 22 '05 #2
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(inpu tVal, (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(inputVa l, '__getitem__')
Nov 22 '05 #3
py
Dan Sommers wrote:
Just do it. If one of foo's callers passes in a non-iterable, foo will
raise an exception, and you'll catch it during testing


That's exactly what I don't want. I don't want an exception, instead I
want to check to see if it's an iterable....if it is continue, if not
return an error code. I can't catch it during testing since this is
going to be used by other people.

Thanks for the suggestion though.

Nov 22 '05 #4
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(inpu tVal, (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(inputVa l, '__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.
Nov 22 '05 #5
py wrote:
Dan Sommers wrote:
Just do it. If one of foo's callers passes in a non-iterable, foo will
raise an exception, and you'll catch it during testing
That's exactly what I don't want. I don't want an exception, instead I
want to check to see if it's an iterable....if it is continue, if not
return an error code.


Why return an error code? Just pass along the exception (i.e. do nothing
special). Python's exception mechanism is far superior to error codes.
Don't try to fight the language.
I can't catch it during testing since this is
going to be used by other people.


Then *they'll* catch it during testing.

--
Robert Kern
rk***@ucsd.edu

"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter

Nov 22 '05 #6
py
Thanks for the replies. I agree with Jean-Paul Calderone's
suggestion...le t the exception be raised.

Thanks.

Nov 22 '05 #7
Hi!

py wrote:
Dan Sommers wrote:
Just do it. If one of foo's callers passes in a non-iterable, foo will
raise an exception, and you'll catch it during testing

That's exactly what I don't want. I don't want an exception, instead I
want to check to see if it's an iterable....if it is continue, if not
return an error code. I can't catch it during testing since this is
going to be used by other people.


Note that using error codes is usually quite "unpythonic ", the way to
signal that something is exceptional (not necessarily wrong) is, well,
an exception.

Anyway, one way to solve this is the following:

def foo(input_val):
try:
iterator = iter(input_val)
except TypeError:
# do non-iterable stuff
else:
for val in iterator:
# do loop stuff

Cheers,

Carl Friedrich Bolz

Nov 22 '05 #8
In article <11************ *********@g49g2 000cwa.googlegr oups.com>,
py <co*******@gmai l.com> 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.


My first thought was to just write your loop inside a try block and
catch the error if it wasn't iterable, but then I noticed that you get:

TypeError: iteration over non-sequence

I was kind of hoping for a more specific exception than TypeError.
You can't tell the difference between:

try:
for i in 5:
print i + 1
except TypeError:
print "non-iterable"

and

try:
for i in ["one", "two", "three"]:
print i + 1
except TypeError:
print "can't add string and integer"

Unfortunately, you can't just try it in a bodyless loop to prove that
you can iterate before doing the real thing because not all iterators
are idempotent.

It's an interesting problem.
Nov 22 '05 #9
On 2005-11-15, py <co*******@gmai l.com> wrote:
Dan Sommers wrote:
Just do it. If one of foo's callers passes in a non-iterable, foo will
raise an exception, and you'll catch it during testing


That's exactly what I don't want. I don't want an exception, instead I
want to check to see if it's an iterable....if it is continue, if not
return an error code. I can't catch it during testing since this is
going to be used by other people.


If I were those other people, and you decided to return error
codes to me instead of passing up the proper exception (the
good, Pythonic thing to do), I'd be fairly pissed off at you.

An exception is the _right_ way to let the caller know
something is wrong.

--
Grant Edwards grante Yow! I smell like a wet
at reducing clinic on Columbus
visi.com Day!
Nov 22 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
1638
by: Michele Simionato | last post by:
According to the standand library (http://docs.python.org/lib/typeiter.html) an *iterable* is something with an __iter__ method. This means that strings are *not* iterable. However I can loop over a string without problem and I would say that an iterable is anything I can iterate over. Of course I am *not* proposing we add __iter__ to...
0
278
by: py | last post by:
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:...
7
53004
by: Tim N. van der Leeuw | last post by:
Hi, I'd like to know if there's a way to check if an object is a sequence, or an iterable. Something like issequence() or isiterable(). Does something like that exist? (Something which, in case of iterable, doesn't consume the first element of the iterable) Regards,
0
7694
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7609
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7921
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8118
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
7964
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6278
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
3651
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3636
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1208
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.