Advertisement
lalala33rfs

Untitled

Nov 19th, 2019
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.90 KB | None | 0 0
  1. def contextmanager(foo):
  2. class cls:
  3. def __init__(self):
  4. self.it = iter(foo())
  5. # next(self.it)
  6.  
  7. def __enter__(self):
  8. next(self.it)
  9.  
  10. def __exit__(self, exc_type, exc_val, exc_tb):
  11. # print('__exit__1')
  12. # next(self.it)
  13. if exc_type and exc_type is StopIteration:
  14. return True
  15.  
  16. if exc_type:
  17. # print(exc_val)
  18. self.it.throw(exc_type(exc_val))
  19. return True
  20.  
  21. def __call__(self, *args, **kwargs):
  22. return foo(*args, **kwargs)
  23. return cls
  24.  
  25.  
  26. @contextmanager
  27. def foo():
  28. print("__enter__")
  29. try:
  30. yield 42
  31. except Exception as e:
  32. print(type(e))
  33. print(str(e))
  34. finally:
  35. print("__exit__")
  36. return
  37.  
  38.  
  39. with foo() as i:
  40. print(i)
  41. raise ValueError("OOOPS")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement