[BangPypers] BangPypers Digest, Vol 6, Issue 8

Siddharta siddharta.lists at gmail.com
Mon Feb 18 13:27:33 CET 2008


Pythonic wrote:
> * 2. Best solution (Pythonic)*
>
>   
>>>> import itertools
>>>> c = itertools.count(9)
>>>> c.next()
>>>>         
> 9
>   
>>>> c.next()
>>>>         
> 10
>   

+1 Pythonic: itertools is the way to go

But if you really want to implement it yourself, you need to do 
something like this -

 >>> class ns: pass
...
 >>> def make_incr(start):
...     v = ns()
...     v.count = start
...     def incr():
...             v.count += 1
...             return v.count
...     return incr
...
 >>> i = make_incr(5)
 >>> i()
6
 >>> i()
7

It's more complex than if you did it in a functional language because of 
limitations on lambda and accessing variables in nested scopes.

--
Siddharta Govindaraj


More information about the BangPypers mailing list