Closures in Python

def incorrect():
    fruit = ['apples', 'bananas', 'peaches']
    printers = {}

    for food in fruit:
        def output():
          print food
        printers[food] = output

    printers['apples']()
    printers['bananas']()
    printers['peaches']()

def correct():
    fruit = ['apples', 'bananas', 'peaches']
    printers = {}

    for food in fruit:
        def create_output(food):
            def output():
                print food
            return output
        printers[food] = create_output(food)

    printers['apples']()
    printers['bananas']()
    printers['peaches']()
>>> incorrect()
peaches
peaches
peaches
>>> correct()
apples
bananas
peaches
Advertisements