Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Usage example of contextmanager with a function
- import os
- from contextlib import contextmanager
- @contextmanager
- def change_dir(destination):
- try: # Used for setup
- cwd = os.getcwd()
- os.chdir(destination)
- yield # Context manager 'with' statement stops here
- finally: # Used for teardown
- os.chdir(cwd) # Called once contextmanager is done executing commands in with statement
- with change_dir('folder'):
- print(os.listdir)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement