PEP 597: Add io.LOCALE_ENCODING constant (#1585)

This commit is contained in:
Inada Naoki 2020-09-07 13:22:24 +09:00 committed by GitHub
parent fc8c265188
commit 54d2135162
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 26 additions and 3 deletions

View File

@ -21,6 +21,9 @@ This PEP proposes:
* Add ``encoding="locale"`` option to ``TextIOWrapper``. It behaves
like ``encoding=None`` but don't raise a warning.
* Add ``io.LOCALE_ENCODING = "locale"`` constant to avoid confusing
``LookupError``. unknown encoding: locale``.
Motivation
==========
@ -92,6 +95,26 @@ This option can be used to use the locale encoding explicitly and
suppress the ``PendingDeprecationWarning``.
``io.LOCALE_ENCODING``
----------------------
``io`` module has ``io.LOCALE_ENCODING = "locale"`` constant. This
constant can be used to avoid confusing ``LookupError: unknown
encoding: locale`` error when the code is run in Python older than
3.10 accidentally.
The constant can be used to test that ``encoding="locale"`` option
is supported too.
::
# Want to suppress the Warning in dev mode but still need support
# old Python versions.
locale_encoding = getattr(io, "LOCALE_ENCODING", None)
with open(filename, encoding=locale_encoding) as f:
...
``io.text_encoding``
--------------------
@ -121,7 +144,7 @@ it. Pure Python implementation will be like this::
"'encoding' option is not specified. The default encoding "
"might be changed to 'utf-8' in the future",
PendingDeprecationWarning, stacklevel + 2)
encoding = "locale"
encoding = LOCALE_ENCODING
return encoding
``pathlib.Path.read_text()`` can use this function like this::
@ -139,8 +162,8 @@ subprocess module doesn't warn
------------------------------
While the subprocess module uses TextIOWrapper, it doesn't raise
``PendingDeprecationWarning``. It uses the "locale" encoding by
default.
``PendingDeprecationWarning``. It uses the ``io.LOCALE_ENCODING``
by default.
Rationale