Skip to content

gh-109714: Improve the OSError constructor - #156430

Open
serhiy-storchaka wants to merge 1 commit into
python:mainfrom
serhiy-storchaka:oserror-default-errno
Open

gh-109714: Improve the OSError constructor#156430
serhiy-storchaka wants to merge 1 commit into
python:mainfrom
serhiy-storchaka:oserror-default-errno

Conversation

@serhiy-storchaka

@serhiy-storchaka serhiy-storchaka commented Aug 26, 2026

Copy link
Copy Markdown
Member

The errno and strerror arguments of the OSError constructor can now be omitted.

errno defaults to the error code which corresponds to the exception class, exposed as the new default_errno class attribute, so that FileNotFoundError() works both with code that tests the errno attribute and with code that uses isinstance().
strerror is derived from the resulting errno, or on Windows from winerror if that was given, whose message is more specific.

filename, winerror and filename2 can now be passed by keyword, as can characters_written for BlockingIOError.

>>> str(FileNotFoundError(filename='cfg.ini'))
"[Errno 2] No such file or directory: 'cfg.ini'"

args is now set to the canonical positional form, so that OSError(*args) reproduces the exception, which is how it is pickled.
It used to be truncated to two items whenever a file name was consumed, so an exception carrying one did not survive pickling.

Incompatible changes:

  • Passing more than five positional arguments is now a TypeError, instead of being silently ignored.
  • args keeps the file names, so OSError(2, 'm', 'f').args is the whole 3-tuple rather than (2, 'm').
  • A file name given explicitly as None is not stored on the exception, so the args of a pickled OSError(2, 'm', None) lose the trailing None.

* The errno argument can now be omitted.  It defaults to the error code
  which corresponds to the exception class.
* The strerror argument can now be omitted.  It is derived from the
  resulting errno, or on Windows from winerror.
* filename, winerror and filename2 can now be passed by keyword, as can
  characters_written for BlockingIOError.
* args is no longer truncated when a file name is given, so that an
  exception carrying one survives pickling.
* Passing more than five positional arguments is now a TypeError.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@read-the-docs-community

Copy link
Copy Markdown

Documentation build overview

📚 cpython-previews | 🛠️ Build #34248045 | 📁 Comparing 71331e7 against main (9036982)

  🔍 Preview build  

3 files changed
± library/exceptions.html
± whatsnew/3.16.html
± whatsnew/changelog.html

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.

1 participant