Skip to content

Fix pickling of exceptions with kw_only attributes#1510

Open
Fridayai700 wants to merge 1 commit intopython-attrs:mainfrom
Fridayai700:fix-exc-kw-only-pickle
Open

Fix pickling of exceptions with kw_only attributes#1510
Fridayai700 wants to merge 1 commit intopython-attrs:mainfrom
Fridayai700:fix-exc-kw-only-pickle

Conversation

@Fridayai700
Copy link

Summary

Fixes the TypeError that occurs when pickling attrs exception classes that use kw_only=True. BaseException.__reduce__ passes all attribute values as positional args, which fails when some attrs are keyword-only.

The fix adds a custom __reduce__ to all attrs exception classes (auto_exc=True) that uses a helper function _reconstruct_exc to pass all init arguments as keyword arguments. This handles:

  • All-kw_only exceptions (kw_only=True on the class)
  • Mixed positional + kw_only exceptions
  • Subclass hierarchies with mixed kw_only inheritance
  • Both slotted and non-slotted exceptions

Fixes #734

Test plan

  • Added module-level test exception classes (slotted and non-slotted variants)
  • test_auto_exc_kw_only_pickle: verifies pickle roundtrip for all-kw_only exceptions
  • test_auto_exc_mixed_kw_only_pickle: verifies pickle roundtrip for mixed positional + kw_only exceptions
  • All 1365 existing tests continue to pass

BaseException.__reduce__ passes all attribute values as positional
args, which fails when some attrs are keyword-only. Add a custom
__reduce__ to exception classes that passes all init arguments as
keyword arguments via a helper function.

Fixes python-attrs#734

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

pickling of Exceptions and kw_only

1 participant

Comments