tim.clifford.io

The blog of an aspiring technologist.

I'm a web developer.

I'm the lead developer behind The Gleaners Interface.

I got my start in web development making fast Wordpress Spinups for non-profits.

I run an irc server and spend time asking and answering questions in the popular #django and #python channels on freenode.

I live in Vermont, and love to travel.

My Github Repos

Flag Variables

Quick python post: turns out those flag variables that I've always begrudged making have a convenient and clean workaround already built into python's code.
If you're using a for loop to find something, you can break out of a loop early if you found something you wanted. But if you're looking for the exclusion of something, the obvious solution is to use a flag variable:
alphabet_soup = ["n", "e", "fly", "b", "a", "f", "w"]

good_to_eat = True
for item in example_list:
    if item == "fly":
        print "There's a fly in my soup!"
        good_to_eat = False
        break
if good_to_eat:
    print "Good enough to eat"
    ## meaningful soup eating code
The Python devs thought there was a better way to do this, so they included an implicit if statement, which fails on a break. Because there's a hidden if statement in your for loop, else will fire if nothing broke it:
soup_with_fly = ["n", "e", "fly", "b", "a", "f", "w"]
alphabet_soup = ["n", "e", "c", "b", "a", "f", "w"]

def inspect_soup(example_list):
    for item in example_list:
        if item == "fly":
            print "there's a fly in my soup!"
            break
    else:
        print "Apparently I didn't find any flies this time"
        ## consume soup

inspect_soup(soup_with_fly)
>>> "there's a fly in my soup!"
inspect_soup(alphabet_soup)
>>> "Apparently I didn't find any flies this time"

Neat, right? For some reason this struck me as particularly clever, and if you wanted to see more you can go straight to source, a Python Dev going over how to write beautiful and idiomatic python.