Skip to content

Instantly share code, notes, and snippets.

@durden
Created November 28, 2012 00:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save durden/4158116 to your computer and use it in GitHub Desktop.
Save durden/4158116 to your computer and use it in GitHub Desktop.
Python generator attempting to simulate static variable in a C function
# Just playing around and thinking about how itertools.count might work (without # looking at source :) )
# Simple version of a 'static' variable in C, just keep state internally
# and use next() to get values out
def counter():
for ii in xrange(100):
yield ii
cnt = counter()
print cnt.next()
print cnt.next()
# Equivalent of this but built-in count doesn't have a max defined explicitly
from itertools import count
cnt = count(0)
print cnt.next()
print cnt.next()
@eloyz
Copy link

eloyz commented Nov 28, 2012

def counter():
i = 0
while True:
i += 1
yield i

Nice brain teaser.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment