Rather that using
for foo in bar: if something: process foo
you can flip the condition around and terminate early:
for foo in bar: if not something: continue process foo
this reduces the nesting level from the number of loops + the number of conditionals to just the number of loops. I believe this is controversial, though. Some devs don’t like early termination in general, and it does lean towards cargo cult behaviour – indentation, in itself, does not make code objectively more complex, and terminating early does objectively add a tiny bit of complexity in the form of a
Chunk logically related lines in functions. Often the contents of an
ifblock belong together, so you’d convert
for cell in table: if something: preprocess row for cell in row: if something: process cell
for cell in table: if something: process_row(row) def process_row(row): preprocess row for cell in row: if something: process_cell(cell) def process_cell(cell): […]
- I suspect there is a bug in this code.
metraLocationis only set (or changed) the condition
entity.trip_update.trip.trip_id == metraTrip["trip_id"]holds. If that condition does not hold for the first item then I believe the script will crash. If it does hold for the first item but not for one of the subsequent items, then that
predictionArrayentry will get the value from the previous iteration.