diff --git a/notebook/context manager/hands_on/1_microscope_script.py b/notebook/context manager/hands_on/1_microscope_script.py index 78e59f1..8220c62 100644 --- a/notebook/context manager/hands_on/1_microscope_script.py +++ b/notebook/context manager/hands_on/1_microscope_script.py @@ -4,12 +4,12 @@ connect_to_microscope, # Connect to microscope and get a state object release_microscope, - activate_vacuum_pump, # Make vacuum inside the microscope + activate_vacuum_pump, # Make vacuum inside the microscope deactivate_vacuum_pump, - + insert_sample, # Insert sample for scanning remove_sample, - + calibrate, # Calibrate microscope scan_sample, # Scan sample currently in the microscope ) @@ -26,21 +26,23 @@ def do_stuff_under_vacuum(microscope_state): # Write here the `sample_inserted` context manager that inserts a sample -# in the microscope before executing a block of code, and safely removes +# in the microscope before executing a block of code, and safely removes # it at the end of the block. +@contextmanager +def sample_inserted(microscope_state): + insert_sample(microscope_state) + try: + yield + finally: + remove_sample(microscope_state) + # Rewrite this script using the two context managers. microscope_state = connect_to_microscope() -activate_vacuum_pump(microscope_state) -try: - insert_sample(microscope_state) - try: +with do_stuff_under_vacuum(microscope_state): + with sample_inserted(microscope_state): sample_image = scan_sample(microscope_state) - finally: - remove_sample(microscope_state) -finally: - deactivate_vacuum_pump(microscope_state) release_microscope(microscope_state)