diff --git a/notebook/context manager/hands_on/1_microscope_script.py b/notebook/context manager/hands_on/1_microscope_script.py index 78e59f1..4ffa317 100644 --- a/notebook/context manager/hands_on/1_microscope_script.py +++ b/notebook/context manager/hands_on/1_microscope_script.py @@ -24,15 +24,30 @@ def do_stuff_under_vacuum(microscope_state): finally: deactivate_vacuum_pump(microscope_state) +@contextmanager +def sample_inserted(microscope_state): + """ inserts a sample in the microscope before executing a + block of code, and safely removes it at the end of the block.""" + insert_sample(microscope_state) + try: + yield + finally: + remove_sample(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 -# it at the end of the block. -# Rewrite this script using the two context managers. microscope_state = connect_to_microscope() +with do_stuff_under_vacuum(microscope_state): + with sample_inserted(microscope_state): + sample_image = scan_sample(microscope_state) +release_microscope(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) @@ -44,3 +59,4 @@ def do_stuff_under_vacuum(microscope_state): deactivate_vacuum_pump(microscope_state) release_microscope(microscope_state) +