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
This commit is contained in:
@@ -181,6 +181,8 @@ BUFFER_SIZE = 128 * 1024
|
|||||||
|
|
||||||
def copy_file(src, dst):
|
def copy_file(src, dst):
|
||||||
""" Copy file from src to dst. Faster than shutil.copy. """
|
""" Copy file from src to dst. Faster than shutil.copy. """
|
||||||
|
fin = None
|
||||||
|
fout = None
|
||||||
try:
|
try:
|
||||||
fin = os.open(src, READ_FLAGS)
|
fin = os.open(src, READ_FLAGS)
|
||||||
fstat = os.fstat(fin)
|
fstat = os.fstat(fin)
|
||||||
@@ -188,13 +190,15 @@ def copy_file(src, dst):
|
|||||||
for x in iter(lambda: os.read(fin, BUFFER_SIZE), b""):
|
for x in iter(lambda: os.read(fin, BUFFER_SIZE), b""):
|
||||||
os.write(fout, x)
|
os.write(fout, x)
|
||||||
finally:
|
finally:
|
||||||
|
if fout is not None:
|
||||||
try:
|
try:
|
||||||
os.close(fout)
|
os.close(fout)
|
||||||
except (OSError, UnboundLocalError):
|
except OSError:
|
||||||
pass
|
pass
|
||||||
|
if fin is not None:
|
||||||
try:
|
try:
|
||||||
os.close(fin)
|
os.close(fin)
|
||||||
except (OSError, UnboundLocalError):
|
except OSError:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user