Skip to content

Instantly share code, notes, and snippets.

@shomah4a
Created July 14, 2012 06:09
Show Gist options
  • Save shomah4a/3109647 to your computer and use it in GitHub Desktop.
Save shomah4a/3109647 to your computer and use it in GitHub Desktop.
contextmanager のテスト
#-*- coding:utf-8 -*-
import contextlib
def gencon():
u'''
ふつうの contextmanager
'''
print 'enter'
yield 10
print 'exit'
def gencon():
u'''
__exit__ で 'generator が終わってねーぞあほか' って言われる
'''
print 'enter'
yield 10
print 'exit'
yield 20
if __name__ == '__main__':
with contextlib.GeneratorContextManager(gencon()) as x:
print x
@shimizukawa
Copy link

yield書かずに関数抜ければStopIteration例外がでるのでその場合の例。

@contextmanager
def foo():
    print 'enter'
    return 1
    print 'what?'
    yield 2
    print 'exit'

with foo() as x:
    print x

RuntimeError: generator didn't yield

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