is parameter an iterable?
steve at REMOVETHIScyber.com.au
Tue Nov 15 23:38:39 CET 2005
On Tue, 15 Nov 2005 14:06:45 -0500, Dan Sommers wrote:
> 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...
> 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.
It isn't during testing so much that he needs to watch out, as run-time.
You have three options:
(1) The "if the user is silly enough to pass a non-iterable to my
function, they deserve to have it fail" school of thought. Dan's advise
comes under this heading.
(2) The "if the user passes a non-iterable, I want to catch the exception
and recover gracefully" school of thought. Recovering gracefully may mean
raising your own exception, with a user friendly error message ("Hey
butthead, pass an iterable willya!!!"), or it may mean just catching the
exception and doing something else, depending on the needs of your
program. (For example, as a user-friendly feature, you might want to treat
ints as if they were iterables of one item only, so users can pass 5 as an
argument instead of .)
For the second case, what you want to do is wrap your code in a
try...except block and catch the exception raised when a non-iterator is
passed as an argument.
Which exception is that? I leave that as an exercise for the reader.
(Hint: Just Do It and read the traceback Python prints.)
Actually, I think "Just Do It" might make a good motto for Python.
More information about the Python-list