is parameter an iterable?
Dan Sommers
me at privacy.net
Tue Nov 15 14:06:45 EST 2005
On 15 Nov 2005 11:01:48 -0800,
"py" <codecraig at gmail.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(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?
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.tombstonezero.net/dan/>
More information about the Python-list
mailing list