Skip to content

gh-102931: Use explicit exception when shutil._copytree should group exceptions - #128309

Open
berland wants to merge 7 commits into
python:mainfrom
berland:fix_copy_itself_exc_error
Open

berland wants to merge 7 commits into
python:mainfrom
berland:fix_copy_itself_exc_error

Conversation

@berland

@berland berland commented Dec 28, 2024 •

Copy link
Copy Markdown

If not, it is caught as a shutil.Error for which it is assumed to be a recursive error, resulting in splitting of the error string as

shutil.Error: ['<', 'D', 'i', 'r', 'E', 'n', 't', 'r', 'y', ' ', ...,
               's', 'a', 'm', 'e', ' ', 'f', 'i', 'l', 'e']

@ghost

ghost commented Dec 28, 2024 •

Copy link
Copy Markdown

All commit authors signed the Contributor License Agreement.
CLA signed

@bedevere-app

bedevere-app Bot commented Dec 28, 2024

Copy link
Copy Markdown

Most changes to Python require a NEWS entry. Add one using the blurb_it web app or the blurb command-line tool.

If this change has little impact on Python users, wait for a maintainer to apply the skip news label instead.

@bedevere-app bedevere-app Bot mentioned this pull request Dec 28, 2024
@berland berland changed the title gh-102391: Catch SameFileError explicitly in _copytree gh-102931: Catch SameFileError explicitly in _copytree Dec 28, 2024
@berland

berland commented Dec 28, 2024

Copy link
Copy Markdown
Author

This is based on @eric-wieser's work in #102827 but with tests adde and a different approach to resolution.

@ZeroIntensity
ZeroIntensity self-requested a review December 28, 2024 14:22
Comment thread Lib/shutil.py Outdated
copy_function(srcobj, dstname)
# catch the Error from the recursive copytree so that we can
# continue with other files
except SameFileError as err:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you need the same handler for SpecialFileError, which is also instantiated with a string.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(and possibly the other errors too, I haven't attempted to trace them all).

Using ExceptionGroup here might make things cleaner, but is probably backwards-incompatible.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will try to reproduce that with a test.

@berland berland Dec 29, 2024 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I could not make a scenario that would yield this error (a splitted string in the error message) when a SpecialFileError is triggered. There is already a test function that checks the error string when a SpecialFileError is provoked with a pipe

def test_copytree_named_pipe(self):

which already passes and that behaviour is not changed in this PR. In that case there is recursion involved, and then the existing code works. The bug with splitted strings only occurs when there is no recursion.

@ZeroIntensity ZeroIntensity left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Some high-level comments.

Comment thread Lib/test/test_shutil.py Resolved
Comment thread Lib/test/test_shutil.py Resolved
Comment thread Lib/shutil.py Resolved
@berland
berland force-pushed the fix_copy_itself_exc_error branch from b8dc15b to 470b7bd Compare December 29, 2024 15:49
Comment thread Lib/shutil.py Outdated
except SameFileError as err:
errors.append((srcname, dstname, str(err)))
except Error as err:
errors.extend(err.args[0])

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it instead be better to use:

if type(e) is Error:
  errors.extend(err.args[0])
else:
  errors.append((srcname, dstname, str(err)))

which perhaps is more robust

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, it is more robust if there are more bugs that we have not found. It is best if we could find them too and add a test case for them.

If it is impossible to trigger other exceptions in the outermost recursion layer, I would prefer the code to be explicit and only catch what is attainable.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would prefer the code to be explicit and only catch what is attainable.

Agreed; perhaps then we should add

class ErrorGroup(Error): pass

and throw/catch this when grouping the exceptions. That way it is explicit that this merging behavior is actually going to do the right thinking, rather than hoping the exception is the one we think it is.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, that looked good in the code! Fixed

@berland berland changed the title gh-102931: Catch SameFileError explicitly in _copytree gh-102931: Use explicit exception when _copytree should group exceptions Jan 2, 2025
@berland berland changed the title gh-102931: Use explicit exception when _copytree should group exceptions gh-102931: Use explicit exception when shutil._copytree should group exceptions Jan 2, 2025
@berland
berland force-pushed the fix_copy_itself_exc_error branch 2 times, most recently from 6e9603b to 101bf86 Compare January 2, 2025 06:27
Comment thread Lib/shutil.py Outdated
Comment on lines +534 to +537
except Error as err:
errors.extend(err.args[0])
errors.append((srcname, dstname, str(err)))

@eric-wieser eric-wieser Jan 2, 2025 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Error extends OSError which is already caught below, so there is no need to catch this any more.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yup. Fixed!

@eric-wieser eric-wieser left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! It would be cool to use ExceptionGroup here, but that would probably be backwards incompatible so probably isn't possible.

@berland

berland commented Oct 14, 2025

Copy link
Copy Markdown
Author

@eric-wieser is there anything I can do to make this enter "core review"?

@berland
berland requested a review from giampaolo as a code owner October 14, 2025 13:18
@python-cla-bot

python-cla-bot Bot commented Oct 14, 2025 •

Copy link
Copy Markdown

All commit authors signed the Contributor License Agreement.

CLA signed

Comment thread Lib/test/test_shutil.py Outdated
Comment on lines +1124 to +1127
try:
shutil.copytree(src_dir, target_dir, dirs_exist_ok=True)
self.fail("shutil.Error should have been raised")
except Error as error:

@picnixz picnixz Jan 10, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use self.assertRaisesRegex instead of try-except please or work with the context manager.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think self.assertRaisesRegex is appropriate here, since we're checking a tuple-valued args.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh right. Then just assertRaises

Comment thread Lib/shutil.py Outdated
pass

class ErrorGroup(Error):
"""Raised when multiple exceptions have been caught"""

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
"""Raised when multiple exceptions have been caught"""
"""Raised when multiple exceptions have been caught."""

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for your review @picnixz , this should now be fixed. Will squash the commits later, but kept the review-fix as separate commit for now.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't bother squashing them. We do it ourselves at the end. Squashing commits is not always good since we do incremental reviews. Only force-pushes when (1) there is no review yet (2) there was a real issue with the history

@berland
berland force-pushed the fix_copy_itself_exc_error branch from 3d03a5f to da49c09 Compare January 12, 2026 11:16
@github-actions

Copy link
Copy Markdown

This PR is stale because it has been open for 30 days with no activity.

@github-actions github-actions Bot added the stale Stale PR or inactive for long period of time. label Apr 20, 2026
@berland

berland commented May 18, 2026

Copy link
Copy Markdown
Author

@picnixz @eric-wieser @ZeroIntensity — just wanted to check if there's anything else needed here?

Comment thread Lib/test/test_shutil.py Outdated
Comment on lines +1123 to +1133
def _assert_are_the_same_file_is_raised(self, src_dir, target_dir):
with self.assertRaises(Error) as cm:
shutil.copytree(src_dir, target_dir, dirs_exist_ok=True)

self.assertEqual(len(cm.exception.args[0]), 1)
if sys.platform == "win32":
self.assertIn(
"it is being used by another process", cm.exception.args[0][0][2]
)
else:
self.assertIn("are the same file", cm.exception.args[0][0][2])

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this would be clearer as a context manager, to keep the copytree in the caller.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agree, fixed.

@read-the-docs-community

Copy link
Copy Markdown

Comment thread Lib/test/test_shutil.py Resolved
@github-actions github-actions Bot removed the stale Stale PR or inactive for long period of time. label May 22, 2026
@ahmouse15

Copy link
Copy Markdown

Will this be merged soon?

@vstinner

Copy link
Copy Markdown
Member

ErrorGroup inherits from Error (which inherits from OSError). It has nothing special to format a list of exceptions.

Python has built-in supports for exceptions group, see for example the ExceptionGroup class: https://docs.python.org/dev/builtins/exceptions.html#ExceptionGroup. What do you think of using ExceptionGroup instead of adding ErrorGroup?

@berland

berland commented Nov 21, 2026

Copy link
Copy Markdown
Author

Python has built-in supports for exceptions group, see for example the ExceptionGroup class. What do you think of using ExceptionGroup instead of adding ErrorGroup?

It came up earlier during the review but was then dismissed for backwards compatibility issues. Seeing the ExceptionGroup appeared in 3.11, that should not be an issue, not believeing this fix will be backported even that far. I will give it a go!

berland and others added 7 commits November 21, 2026 15:26
This resolves a bug where a non-recursive error is assumed to be a
list of exceptions and presenting the error as:
```
shutil.Error: ['<', 'D', 'i', 'r', 'E', 'n', 't', 'r', 'y', ' ', ...,
               's', 'a', 'm', 'e', ' ', 'f', 'i', 'l', 'e']
```
Co-authored-by: Eric Wieser <wieser.eric@gmail.com>
copytree() collects failures into a list of (src, dst, msg) tuples. When
a shutil.Error that is not the result of a recursive copytree() call is
raised, for example SameFileError from copy_function, its args[0] is a
string rather than a list of tuples. _copytree() passed it to
errors.extend(), which split the message into single characters.

Record such errors as a single (src, dst, msg) entry instead, and only
flatten args[0] when it is a list.
@berland
berland force-pushed the fix_copy_itself_exc_error branch from f68bba9 to fbcf83b Compare November 21, 2026 17:33
@berland

berland commented Nov 21, 2026

Copy link
Copy Markdown
Author

I rewrote the change once more, and realized that I ended up with the same code as @eric-wieser had in #102827. Avoiding both ErrorGroup and any ExceptionGroup.

@eric-wieser

Copy link
Copy Markdown
Contributor

ExceptionGroup might of course be nice here, but that's an interface change that should surely land separately from a fix to a silly formatting bug!

@eric-wieser

Copy link
Copy Markdown
Contributor

What do you think of using ExceptionGroup instead of adding ErrorGroup?

As I understand it, this would break existing code that uses except shutil.Error. Using class ErrorGroup(Error, ExceptionGroup) would help, but you'd still have to worry about the exception handling block expecting the list of errors in .args[0].

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants