Advertisement
Guest User

ContextManager with functions

a guest
Jul 19th, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.48 KB | None | 0 0
  1. # Usage example of contextmanager with a function
  2. import os
  3. from contextlib import contextmanager
  4.  
  5.  
  6. @contextmanager
  7. def change_dir(destination):
  8.     try:  # Used for setup
  9.         cwd = os.getcwd()
  10.         os.chdir(destination)
  11.         yield  # Context manager 'with' statement stops here
  12.     finally:  # Used for teardown
  13.         os.chdir(cwd)  # Called once contextmanager is done executing commands in with statement
  14.  
  15.  
  16. with change_dir('folder'):
  17.     print(os.listdir)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement