Hlelp clean up clumpsy code

It's me itsme at yahoo.com
Tue Jan 4 19:16:39 CET 2005


What's "LBYL"?  Oh...Look-before-you-leap.  OK.

I think I understand what's going on now (I read up on generator and
iterators and my head still hurts).  I knew there must be a cleaner way of
"walking" around in Python.  I will experiment with generator more.

Thanks everybody.


"Jp Calderone" <exarkun at divmod.com> wrote in message
news:mailman.140.1104857018.22381.python-list at python.org...
>
>
> On Tue, 04 Jan 2005 08:18:58 -0800, Scott David Daniels
<scott.daniels at acm.org> wrote:
> >Nick Coghlan wrote:
> > > A custom generator will do nicely:
> > >
> > > Py> def flatten(seq):
> > > ...   for x in seq:
> > > ...     if hasattr(x, "__iter__"):
> > > ...       for y in flatten(x):
> > > ...         yield y
> > > ...     else:
> > > ...       yield x
> >
> > Avoiding LBYL gives you:
> >      def flatten(seq):
> >          for x in seq:
> >              try:
> >                  for y in flatten(x):
> >                      yield y
> >              except TypeError:
> >                  yield x
>
>   But totally messes up on error handling.  Instead:
>
>     def flatten(seq):
>         for x in seq:
>             try:
>                 subseq = iter(x)
>             except TypeError:
>                 yield x
>             else:
>                 for subx in flatten(subseq):
>                     yield subx
>
>   to avoid catching TypeErrors from .next().
>
>   Jp





More information about the Python-list mailing list