SHARE
TWEET

Untitled

lalala33rfs Nov 19th, 2019 89 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. def contextmanager(foo):
  2.     class cls:
  3.         def __init__(self):
  4.             self.it = iter(foo())
  5.  
  6.         def __enter__(self):
  7.             next(self.it)
  8.  
  9.         def __exit__(self, exc_type, exc_val, exc_tb):
  10.             if exc_type:
  11.                 self.it.throw(exc_type(exc_val))
  12.                 return True
  13.  
  14.         def __call__(self, *args, **kwargs):
  15.             return foo(*args, **kwargs)
  16.     return cls
  17.  
  18.  
  19. if __name__ == '__main__':
  20.     pass
  21.  
  22.  
  23. @contextmanager
  24. def foo():
  25.     print("__enter__")
  26.     try:
  27.         yield 42
  28.     except Exception as e:
  29.         print(type(e))
  30.         print(str(e))
  31.     finally:
  32.         print("__exit__")
  33.     return
  34.  
  35.  
  36. with foo() as i:
  37.     print(i)
  38.     raise ValueError("OOOPS")
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top