Repository full of examples written for my blog www.joshstephens.io
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

context_mgr_example.py 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. from typing import IO, Callable
  2. from contextlib import contextmanager
  3. class FileHandler:
  4. """Demonstrates how to build a class to be used as a context manager"""
  5. def __init__(self, file_path: str):
  6. self.file_path = file_path
  7. self.file_handler = None
  8. def __enter__(self) -> IO:
  9. """Context Manager begins the work here"""
  10. self.file_handler = open(self.file_path)
  11. return self.file_handler
  12. def __exit__(self, *exec: Callable):
  13. """Context Manager has comnpleted and time to clean up"""
  14. self.file_handler.close()
  15. @contextmanager
  16. def text_file(file_path: str) -> IO:
  17. """Demonstrates a function as a context manager"""
  18. file = open(file_path)
  19. try:
  20. yield file
  21. except:
  22. file.close()
  23. raise
  24. else:
  25. file.close()
  26. if __name__ == '__main__':
  27. print('*' * 100)
  28. print("Using Try Finally to demonstrate how a context manager behaves when implemented")
  29. print('*' * 100)
  30. # Long way to write a context manager
  31. try:
  32. file = open('test.txt')
  33. for line in file.readlines():
  34. print(line.rstrip())
  35. finally:
  36. file.close()
  37. print()
  38. print('*' * 100)
  39. print("Normal open function")
  40. print('*' * 100)
  41. # Standard way of using a context manager
  42. with open('test.txt') as infile:
  43. for line in infile.readlines():
  44. print(line.rstrip())
  45. print()
  46. print('*' * 100)
  47. print("Class Context Manager")
  48. print('*' * 100)
  49. # Class As a File Handler written to be a context manager.
  50. with FileHandler('test.txt') as infile:
  51. for line in infile.readlines():
  52. print(line.rstrip())
  53. print()
  54. print('*' * 100)
  55. print("Function Context Manager")
  56. print('*' * 100)
  57. # Function that is written to be a context manager.
  58. with text_file('test.txt') as infile:
  59. for line in infile.readlines():
  60. print(line.rstrip())
  61. print()