Skip to content

Instantly share code, notes, and snippets.

@whosaysni
Last active August 29, 2015 14:01
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 whosaysni/54afd69e0b21d7bc9696 to your computer and use it in GitHub Desktop.
Save whosaysni/54afd69e0b21d7bc9696 to your computer and use it in GitHub Desktop.
re の MatchObject を with のコンテキストにする
# coding: utf-8
class MatchContext(object):
"""
>>> import re
>>> with MatchContext(re.match(r'(.)', 'a')) as context:
... print context.groups()
('a',)
>>> import re
>>> with MatchContext(re.match(r'(.)', '')) as context:
... print context.groups()
>>> # context.groups should raise error but suppressed by __exit__.
"""
def __init__(self, match):
self.match = match
def __enter__(self):
return self.match
def __exit__(self, exc_type, exc_value, traceback):
return True
if __name__=='__main__':
from doctest import testmod
testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment