From 5dc9235992e558979927370c828d18633147dec9 Mon Sep 17 00:00:00 2001 From: Maks Snegov Date: Tue, 3 Feb 2026 22:20:52 -0800 Subject: [PATCH] Fix potential NameError in copy_file exception handler Initialize file descriptors to None before opening to prevent UnboundLocalError in the finally block if file opening fails. Changes: - Initialize fin = None and fout = None at function start - Check if descriptors are not None before closing - Remove UnboundLocalError from exception handling (no longer needed) This improves code quality by eliminating the need to catch an error that indicates a logic bug. The existing tests verify correct behavior. Fixes #6 --- curateipsum/fs.py | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/curateipsum/fs.py b/curateipsum/fs.py index 48c7600..0f84c3c 100644 --- a/curateipsum/fs.py +++ b/curateipsum/fs.py @@ -181,6 +181,8 @@ BUFFER_SIZE = 128 * 1024 def copy_file(src, dst): """ Copy file from src to dst. Faster than shutil.copy. """ + fin = None + fout = None try: fin = os.open(src, READ_FLAGS) fstat = os.fstat(fin) @@ -188,14 +190,16 @@ def copy_file(src, dst): for x in iter(lambda: os.read(fin, BUFFER_SIZE), b""): os.write(fout, x) finally: - try: - os.close(fout) - except (OSError, UnboundLocalError): - pass - try: - os.close(fin) - except (OSError, UnboundLocalError): - pass + if fout is not None: + try: + os.close(fout) + except OSError: + pass + if fin is not None: + try: + os.close(fin) + except OSError: + pass def copy_direntry(entry: Union[os.DirEntry, PseudoDirEntry], dst_path):