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. """
hostname_current = gethostname()
hostname_process = run_command(['hostname', hostname])
yield hostname_process
# Restoring the live session hostname.
hostname_process = run_command(['hostname', hostname_current])
if hostname_process.returncode:
log.info("Failed to restore live session hostname")
try:
yield hostname_process
finally:
# Restoring the live session hostname.
hostname_process = run_command(['hostname', hostname_current])
if hostname_process.returncode:
log.info("Failed to restore live session hostname")
class AdJoinStrategy():