Skip to content

Instantly share code, notes, and snippets.

@ericmoritz
Forked from seancribbs/test_context.py
Created December 26, 2012 23:20
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 ericmoritz/4383896 to your computer and use it in GitHub Desktop.
Save ericmoritz/4383896 to your computer and use it in GitHub Desktop.
$ python test_context.py
CONTEXT: start
USER: got resource
CONTEXT: done
Traceback (most recent call last):
File "test_context.py", line 32, in <module>
for i in user():
File "test_context.py", line 27, in user
for item in resource:
TypeError: iter() returned non-iterator of type 'MyIterator'
# A simple test that demonstrates my problem
from contextlib import contextmanager
class MyIterator(object):
def __init__(self):
self.list = [1,2,3,4,5,6,7,8,9,10]
def __iter__(self):
return self
def __next__(self):
item = self.list[0]
print "ITER: yielding %s" % str(item)
self.list = self.list[1:]
return item
@contextmanager
def taker():
print "CONTEXT: start"
try:
yield MyIterator()
finally:
print "CONTEXT: done"
def user():
with taker() as resource:
print "USER: got resource"
for item in resource:
print "USER: yielding %s" % str(item)
yield item
for i in user():
print "GOT: %s" % str(i)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment