disgrating a list

Hardcoded Software hardcoded.software at gmail.com
Sat Sep 2 09:51:17 EDT 2006


Tal Einat wrote:
> 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.
>
> - Tal

I agree. Code readability is much more important than code performance
(Well, in the Python realm.). A Python coder shouldn't care about
performance until he/she does a profiling and finds out a bottleneck.

Besides, I like my solution a little better :). When performing the
extend in the try, the extend will raise TypeError anyway. No need to
call iter(). It's what my Python in a nutshell book calls "It's easier
to ask forgiveness than permission" idiom, as opposed to the "Look
before you leap" idiom.




More information about the Python-list mailing list