Skip to content

Commit 54d2135

Browse files
authored
PEP 597: Add io.LOCALE_ENCODING constant (#1585)
1 parent fc8c265 commit 54d2135

File tree

1 file changed

+26
-3
lines changed

1 file changed

+26
-3
lines changed

pep-0597.rst

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,9 @@ This PEP proposes:
2121
* Add ``encoding="locale"`` option to ``TextIOWrapper``. It behaves
2222
like ``encoding=None`` but don't raise a warning.
2323

24+
* Add ``io.LOCALE_ENCODING = "locale"`` constant to avoid confusing
25+
``LookupError``. unknown encoding: locale``.
26+
2427

2528
Motivation
2629
==========
@@ -92,6 +95,26 @@ This option can be used to use the locale encoding explicitly and
9295
suppress the ``PendingDeprecationWarning``.
9396

9497

98+
``io.LOCALE_ENCODING``
99+
----------------------
100+
101+
``io`` module has ``io.LOCALE_ENCODING = "locale"`` constant. This
102+
constant can be used to avoid confusing ``LookupError: unknown
103+
encoding: locale`` error when the code is run in Python older than
104+
3.10 accidentally.
105+
106+
The constant can be used to test that ``encoding="locale"`` option
107+
is supported too.
108+
109+
::
110+
111+
# Want to suppress the Warning in dev mode but still need support
112+
# old Python versions.
113+
locale_encoding = getattr(io, "LOCALE_ENCODING", None)
114+
with open(filename, encoding=locale_encoding) as f:
115+
...
116+
117+
95118
``io.text_encoding``
96119
--------------------
97120

@@ -121,7 +144,7 @@ it. Pure Python implementation will be like this::
121144
"'encoding' option is not specified. The default encoding "
122145
"might be changed to 'utf-8' in the future",
123146
PendingDeprecationWarning, stacklevel + 2)
124-
encoding = "locale"
147+
encoding = LOCALE_ENCODING
125148
return encoding
126149

127150
``pathlib.Path.read_text()`` can use this function like this::
@@ -139,8 +162,8 @@ subprocess module doesn't warn
139162
------------------------------
140163

141164
While the subprocess module uses TextIOWrapper, it doesn't raise
142-
``PendingDeprecationWarning``. It uses the "locale" encoding by
143-
default.
165+
``PendingDeprecationWarning``. It uses the ``io.LOCALE_ENCODING``
166+
by default.
144167

145168

146169
Rationale

0 commit comments

Comments
 (0)