0

I was looking at this SO question about the Python For Else flow control and I thought I had a portion of code that which is very close to the example given. I think that my code is very close to the example code except that I want the for loop to finish (for logging purposes).

for module_name, class_name in BASIC_PARSERS_TO_RUN:
    full_module_name = "parsers." + module_name
    parser = getattr(import_module(full_module_name), class_name)(
        logger=logger)
    parser_data = parser.parse(cluster_path)

    if parser_data is None or parser_data == "0":
        # Basic None instead of "None" so that json is serialized to null
        # instead of "None"
        json_data_list.append({module_name: parser_data})
        failed_basic_checks = True
    else:
        json_data_list.append({module_name: str(parser_data)})

# Checking if we have a valid data set.
if failed_basic_checks:
    json_data_list.append({"basic_validation_succeeded": False})
    return json.dumps(json_data_list)
    # We've run into a dataset which isn't valid.
    exit(1)

Is there any way to change my for loop to use the for else flow control?

found_obj = None
for obj in objects:
    if obj.key == search_key:
        found_obj = obj
        break
else:
    print 'No object found.'
Community
  • 1
  • 1
AlexLordThorsen
  • 8,057
  • 5
  • 48
  • 103
  • 1
    You can't guarantee your loop will always finish if you have an if-statement with a break inside that loop (unless you have something like `if 1 == 2:1). You can of course *always* uese the `else` clause by just leaving it out. Then, "No object found." will always be printed, no mattter whether a matching key was found or not. –  Jan 20 '15 at 19:38
  • 3
    Your question seems unclear; what is the larger context of your question? What do you want to achieve with always using the `else` clause. –  Jan 20 '15 at 19:39
  • 2
    If you always want your loop to run to completion, then you probably don't want any `break` statements in the loop. If there are no `break` statements in the loop, then the point of having the `else` construct isn't clear to me. – rchang Jan 20 '15 at 20:03

1 Answers1

2

The code as written is just fine; there's no reason to use a for/else structure.

According to the docs, an else after a loop is always executed unless the loop was terminated by a break statement. So if you are not using break statements in the loop, an else clause is unnecessary; you should simply put the relevant code after the loop.

augurar
  • 12,081
  • 6
  • 50
  • 65