Exception safe context manager

Without the try/finally the cleanup could be skipped by an exception
being raised.
This commit is contained in:
Carlos Nihelton 2023-03-01 09:44:36 -03:00
parent babf0255b9
commit 33597e3c7d
No known key found for this signature in database
GPG Key ID: 6FE346D245197E9A
1 changed files with 7 additions and 5 deletions

View File

@ -34,11 +34,13 @@ def hostname_context(hostname: str):
back in the end of the caller scope. """ back in the end of the caller scope. """
hostname_current = gethostname() hostname_current = gethostname()
hostname_process = run_command(['hostname', hostname]) hostname_process = run_command(['hostname', hostname])
yield hostname_process try:
# Restoring the live session hostname. yield hostname_process
hostname_process = run_command(['hostname', hostname_current]) finally:
if hostname_process.returncode: # Restoring the live session hostname.
log.info("Failed to restore live session hostname") hostname_process = run_command(['hostname', hostname_current])
if hostname_process.returncode:
log.info("Failed to restore live session hostname")
class AdJoinStrategy(): class AdJoinStrategy():