Sep 13, 2019

python contextlib vs context manager

import contextlib

class contextManagerExample:
  def __init__(self):
    print('inside __init__')
  def __enter__(self):
    print('inside __enter__')
    return 'returning from contextManagerExample enter'
  def __exit__(self, exc_type, exc_val, exc_tb):
    print('inside __exit__')

#No need to write __enter__, __exit__ separately
#yield instead of return
@contextlib.contextmanager
def context_lib_test():
  try:
    yield 'returning from context_lib_test enter'
  except Exception as e:
    raise

if __name__ == '__main__':
  print('-'*20)
  with contextManagerExample() as cm:
    print('inside ContextManagerExample scope')
    print(cm)
  print('-'*20)
  with context_lib_test() as cm:
    print('inside context_lib_test scope')
    print(cm)
  print('-'*20)



Output:
--------------------
inside __init__
inside __enter__
inside ContextManagerExample scope
returning from contextManagerExample enter
inside __exit__
--------------------
inside context_lib_test scope
returning from context_lib_test enter
--------------------



No comments:

Post a Comment