for / while else doesn't make sense

Lawrence D’Oliveiro lawrencedo99 at gmail.com
Tue Jun 7 03:52:42 EDT 2016


On Tuesday, June 7, 2016 at 4:36:37 PM UTC+12, Ian wrote:
> A 500-line function? Yikes, what an eyesore. When you have to include
> #end comments in order to visually match things up, that should be a
> smell that your code is excessively complex.

Feel free to come up with a simpler version.

>     def generate_lines():
>         nonlocal input_line
>         while True:
>             try:
>                 # Note input_line appears to be an iterator, not a string
>                 # as suggested by the name.
>                 yield next(input_line)
>             except StopIteration:
>                 if include_stack:
>                     input_line = include_stack.pop()
>                 else:
>                     return
> 
>     for line in generate_lines():
>         if not include_stack:
>             linenr += 1
>         if ... line contains something special ...:
>             ... process special line ...
>         else:
>             ... process regular line ...

Wow, that’s only twice the length of the code you’re replacing. Well done.


More information about the Python-list mailing list