Skip to content

Fix pickling of exceptions with kw_only attributes#1510

Closed
worksbyfriday wants to merge 1 commit intopython-attrs:mainfrom
worksbyfriday:fix-exc-kw-only-pickle
Closed

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

Conversation

@worksbyfriday
Copy link
Copy Markdown

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>
@hynek
Copy link
Copy Markdown
Member

hynek commented Mar 14, 2026

I'm sorry to be blunt, but this is AI slop. return cls(**kwargs) falls apart the moment private fields come into play. Use whatever tools you want, but use your judgement.

In case you want to give it another try, please note that we now have an AI policy.

@hynek hynek closed this Mar 14, 2026
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

2 participants