Hlelp clean up clumpsy code

Scott David Daniels Scott.Daniels at Acm.Org
Tue Jan 4 11:18:58 EST 2005


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

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list