How can I do this (from Perl) in Python? (closures)

excord80 at gmail.com excord80 at gmail.com
Thu Dec 4 06:18:53 CET 2008


I just came across http://www.perl.com/pub/a/2002/05/29/closure.html
and wanted to try the "canonical example of closures" in Python. I
came up with the following, but it fails:

#######################
#!/usr/bin/env python

def make_counter(start_num):
    start = start_num
    def counter():
        start += 1
    return counter

from_ten = make_counter(10)
from_three = make_counter(3)

print from_ten()       # 10
print from_ten()       # 11
print from_three()     # 3
print from_ten()       # 12
print from_three()     # 4
####################

The error message is: "UnboundLocalError: local variable 'start'
referenced before assignment". The same thing happens if I omit start
and just use start_num directly.

How can I do it in Python?



More information about the Python-list mailing list