diff --git a/pep-0597.rst b/pep-0597.rst index 6d3063da8..9d68e7279 100644 --- a/pep-0597.rst +++ b/pep-0597.rst @@ -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