Skip to content

Instantly share code, notes, and snippets.

@shomah4a
Last active November 15, 2016 06:32
Show Gist options
  • Save shomah4a/fc3b204b19320f97c024788125030ae1 to your computer and use it in GitHub Desktop.
Save shomah4a/fc3b204b19320f97c024788125030ae1 to your computer and use it in GitHub Desktop.
#-*- coding:utf-8 -*-
class BlockExit(BaseException):
def __init__(self, block):
self.block = block
class Block(object):
def __enter__(self):
return self
def __exit__(self, exc_type=None, exc_value=None, traceback=None):
if isinstance(exc_value, BlockExit) and exc_value.block is self:
return True
def escape(self):
raise BlockExit(self)
def test():
with Block() as block:
for i in range(20):
print(i)
if i == 10:
# with 文抜ける
block.escape()
with Block() as outer:
for i in range(20):
with Block() as inner:
for j in range(30):
print(i, j)
if j == 20:
outer.escape()
if __name__ == '__main__':
test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment