disgrating a list
tal.no.no.spam at gmail.com
Sat Sep 2 13:22:01 CEST 2006
Neil Cerutti wrote:
> On 2006-09-01, Tal Einat <tal.no.no.spam at gmail.com> wrote:
> > Tim Chase wrote:
> >> I'm not sure if '__iter__' is the right thing to be looking
> >> for, but it seems to work at least for lists, sets,
> >> dictionarys (via their keys), etc. I would use it because at
> >> least then you know you can iterate over it
> > AFAIK and as seen throughout posts on c.l.py, the best way to
> > check if something is iterable is:
> > try:
> > iter(obj)
> > except TypeError:
> > <obj is not iterable>
> > else:
> > <obj is iterable>
> That confounds me. Of course, I'm coming from a C++, where you
> never want to throw an exception in a common case, hence the name
> 'exception'. The Python FAQ does say that raising and catching an
> exception is an expensive operation. I see that type-checking is
> good to avoid, but type-checking must be better than "abusing"
> exceptions in this way. Is the above really a popular idiom?
> If so, I guess I'll get used to it.
Such use of exceptions is surely common enough in Python to be worth
getting to know, if only in order to understand others' code.
If you had wanted to check if an object was callable, which is a more
basic functionality in Python, you would use Python's built-in function
callable(). Unfortunately there is no such function as iterable().
(perhaps there should be? ...)
Raising an exception is a relatively "expensive" operation, but not so
much that you would want to avoid it altogether... In most such cases,
such as checking whether an object is iterable, speed isn't an issue.
IMO this is far from "abuse". The iter() function's documenation
explicitly notes "If it does not support either of those protocols,
TypeError is raised." This can be viewed as one possible output of the
function, in addition to the possibility of returning an iterator. In
such a function, raising exceptions instead of returning None or other
special values (often called "return codes") is much more modular, and
IMO much more readable.
More information about the Python-list