how to write function that returns function

Oren Tirosh oren-py-l at hishome.net
Thu May 16 03:00:46 EDT 2002


On Wed, May 15, 2002 at 05:34:39PM -0400, Kragen Sitaker wrote:
> a "counter" closure in Python is ugly:
> 
> def counter(startvalue):
>     state = [startvalue]
>     def counter_internal():
>         state[0] += 1
>         return state[0]
>     return counter_internal

How about this:

def counter(startvalue):

   def gen_count():
      state = startvalue
      while 1:
          yield state
          state += 1

   return gen_count().next

	Oren





More information about the Python-list mailing list