Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to break out of loop

Total python beginner here.

I have the following function, which checks if a string derived from certain inputs exists in a text file. It loops through each line of the text file, to see if an exact match is found.

I have to break out of looping, immediately after the match is found, to avoid needless looping.

Here is the code:

def DateZoneCity_downloaded_previously(Order_Date,ZoneCity):    #   function to check if a given DateZoneCity
                                                                    #   combination had already been completely downloaded
    string_to_match = Order_Date.strftime('%Y/%m/%d') + "-" + ZoneCity[0] + "-" + ZoneCity[1]
    with open(Record_File) as download_status:
        DateZoneCity_exists = False
        for line in download_status:
            if string_to_match in line:
                DateZoneCity_exists = True                      #   if match found, then set "DateZoneCity_exists" to True
                break                                           #   and break out from the [for line in download_status:] loop
        if DateZoneCity_exists: return True
    download_status.close()

I am searching for a more concise, pythonic way to structure the code. Is there anything I can do to make this better? Somehow to eliminate the need for "DateZoneCity_exists" and the second If statement?

like image 512
Chinmay Kamat Avatar asked Jun 10 '16 04:06

Chinmay Kamat


2 Answers

This feels like a situation where any would be the best solution:

# Function to check if a given DateZoneCity
def DateZoneCity_downloaded_previously(Order_Date, ZoneCity):
    # Combination had already been completely downloaded
    string_to_match = Order_Date.strftime('%Y/%m/%d') + "-" + ZoneCity[0]
                                                      + "-" + ZoneCity[1]
    with open(Record_File) as download_status:
        return any((string_to_match in line) for line in download_status)

Note that in this case it will return False on negative rather than your current implementation that will return None, also note that it does break out of the looping immediately upon finding a positive result so it does not require looping through the entire file either way.

like image 140
Tadhg McDonald-Jensen Avatar answered Oct 12 '22 05:10

Tadhg McDonald-Jensen


Just return instead of break:

def DateZoneCity_downloaded_previously(Order_Date,ZoneCity):
    """Check if a given DataZoneCity combination had already been downloaded."""
    string_to_match = Order_Date.strftime('%Y/%m/%d') + "-" + ZoneCity[0] + "-" + ZoneCity[1]
    with open(Record_File) as download_status:
        for line in download_status:
            if string_to_match in line:
                return True
    return False  # No match found.
like image 31
Adriano Avatar answered Oct 12 '22 05:10

Adriano