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

Chris Rebert clp at rebertia.com
Thu Dec 4 00:31:44 EST 2008


On Wed, Dec 3, 2008 at 9:18 PM,  <excord80 at gmail.com> wrote:
> 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
>

Depending on your version of Python, you need to do either (A) or (B).
(A) requires Python 3.0 IIRC.

> def make_counter(start_num):
>    start = start_num
(B) replace prev line with: start = [start_num]

>    def counter():
(A) add:        nonlocal start
>        start += 1
(B) replace prev line with: start[0] += 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.

See http://www.python.org/dev/peps/pep-3104/ for more info.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

>
> How can I do it in Python?
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list