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

Duncan Booth duncan.booth at invalid.invalid
Thu Dec 4 03:50:21 EST 2008


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
> 
> def make_counter(start_num):
>     start = start_num
>     def counter():
>         start += 1
>     return counter

The other answers you got will work, but here's an alternative to 
consider: you can convert the function into a generator and then just 
move the variable inside.

>>> def make_counter(start_num):
	def counter():
		start = start_num
		while 1:
			yield start
			start += 1
	return counter().next

>>> 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
>>> 

While I realise you are just trying a simple example, if you actually 
wanted the code the truly Pythonic way would be to use the existing 
libraries:

>>> import itertools
>>> def make_counter(start_num):
	return itertools.count(start_num).next

>>> 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
>>> 

Never reinvent the wheel unless you really need a square one. :^)

-- 
Duncan Booth http://kupuguy.blogspot.com



More information about the Python-list mailing list