← Back to DAGDA | Support | Source: https://github.com/ncoghlan/cpython/commit/188e7807b6d9e49377aacbb287c074e5cabf70c5
Skip to content

Commit 188e780

Browse files
committed
Update to latest version of PEP 538
- move all required logic inside the shared library - explicitly setting one of the coercion target locales now also automatically enables "surrogateescape" on sys.stdin and sys.stdout
1 parent 6a00ce6 commit 188e780

4 files changed

Lines changed: 196 additions & 140 deletions

File tree

‎Doc/using/cmdline.rst‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -734,10 +734,13 @@ conflict.
734734

735735
If setting one of these locale categories succeeds, then the matching
736736
environment variables will be set (both ``LC_ALL`` and ``LANG`` for the
737-
``LC_ALL`` category, and ``LC_CTYPE`` for the ``LC_CTYPE`` category),
738-
and (if :envvar:`PYTHONIOENCODING` is not explicitly set), the text encoding
739-
and error handling for Python's standard streams in the current process
740-
will be set to ``utf-8`` and ``surrogateescape`` respectively.
737+
``LC_ALL`` category, and ``LC_CTYPE`` for the ``LC_CTYPE`` category) in
738+
the current process environment before the Python runtime is initialized.
739+
740+
Configuring one of these locales (either explicitly or via the above
741+
implicit locale coercion) will automatically set the error handler for
742+
:data:`sys.stdin` and :data:`sys.stdout` to ``surrogateescape``. This
743+
behavior can be overridden using :envvar:`PYTHONIOENCODING` as usual.
741744

742745
Availability: \*nix
743746

‎Lib/test/test_c_locale_coercion.py‎

Lines changed: 47 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
)
1616

1717
# In order to get the warning messages to match up as expected, the candidate
18-
# order here must much the target locale order in Programs/python.c
18+
# order here must much the target locale order in Python/pylifecycle.c
1919
_C_UTF8_LOCALES = (
2020
# Entries: (Target locale, target category, expected env var updates)
2121
("C.UTF-8", "LC_ALL", "LC_ALL & LANG"),
@@ -63,9 +63,13 @@ def get_expected_details(cls, expected_fsencoding):
6363
return dict(cls(expected_fsencoding, *stream_info)._asdict())
6464

6565
@staticmethod
66-
def _replace_ascii_alias(data):
67-
"""ASCII may be reported as ANSI_X3.4-1968, so replace it in output"""
68-
return data.replace(b"ANSI_X3.4-1968", b"ascii")
66+
def _handle_output_variations(data):
67+
"""Adjust the output to handle platform specific idiosyncrasies
68+
69+
* Some platforms report ASCII as ANSI_X3.4-1968
70+
* Some platforms report UTF-8 instead of utf-8
71+
"""
72+
return data.replace(b"ANSI_X3.4-1968", b"ascii").lower()
6973

7074
@classmethod
7175
def get_child_details(cls, env_vars):
@@ -87,7 +91,7 @@ def get_child_details(cls, env_vars):
8791
if not result.rc == 0:
8892
result.fail(py_cmd)
8993
# All subprocess outputs in this test case should be pure ASCII
90-
adjusted_output = cls._replace_ascii_alias(result.out)
94+
adjusted_output = cls._handle_output_variations(result.out)
9195
stdout_lines = adjusted_output.decode("ascii").rstrip().splitlines()
9296
child_encoding_details = dict(cls(*stdout_lines)._asdict())
9397
stderr_lines = result.err.decode("ascii").rstrip().splitlines()
@@ -99,15 +103,24 @@ def get_child_details(cls, env_vars):
99103
"C locale coercion disabled at build time")
100104
class LocaleOverrideTests(unittest.TestCase):
101105

106+
available_targets = []
107+
102108
@classmethod
103109
def setUpClass(cls):
110+
first_target_locale = first_env_updates = None
111+
available_targets = cls.available_targets
112+
# Find the target locales available in the current system
104113
for target_locale, target_category, env_updates in _C_UTF8_LOCALES:
105114
if _set_locale_in_subprocess(target_locale, target_category):
106-
break
107-
else:
115+
available_targets.append(target_locale)
116+
if first_target_locale is None:
117+
first_target_locale = target_locale
118+
first_env_updates = env_updates
119+
if not available_targets:
108120
raise unittest.SkipTest("No C-with-UTF-8 locale available")
121+
# Expect coercion to use the first available locale
109122
cls.EXPECTED_COERCION_WARNING = CLI_COERCION_WARNING_FMT.format(
110-
env_updates, target_locale
123+
first_env_updates, first_target_locale
111124
)
112125

113126
def _check_child_encoding_details(self,
@@ -141,11 +154,12 @@ def _check_c_locale_coercion(self, expected_fsencoding, coerce_c_locale):
141154
"""
142155

143156
# Check for expected warning on stderr if C locale is coerced
157+
self.maxDiff = None
158+
144159
expected_warning = []
145160
if coerce_c_locale != "0":
146161
expected_warning.append(self.EXPECTED_COERCION_WARNING)
147162

148-
self.maxDiff = None
149163
base_var_dict = {
150164
"LANG": "",
151165
"LC_CTYPE": "",
@@ -166,7 +180,7 @@ def _check_c_locale_coercion(self, expected_fsencoding, coerce_c_locale):
166180

167181

168182
def test_test_PYTHONCOERCECLOCALE_not_set(self):
169-
# This should coerce to the C.UTF-8 locale by default
183+
# This should coerce to the first available target locale by default
170184
self._check_c_locale_coercion("utf-8", coerce_c_locale=None)
171185

172186
def test_PYTHONCOERCECLOCALE_not_zero(self):
@@ -179,6 +193,29 @@ def test_PYTHONCOERCECLOCALE_set_to_zero(self):
179193
# The setting "0" should result in the locale coercion being disabled
180194
self._check_c_locale_coercion("ascii", coerce_c_locale="0")
181195

196+
def test_external_target_locale_configuration(self):
197+
# Explicitly setting a target locale should give the same behaviour as
198+
# is seen when implicitly coercing to that target locale
199+
self.maxDiff = None
200+
201+
expected_warning = []
202+
expected_fsencoding = "utf-8"
203+
204+
base_var_dict = {
205+
"LANG": "",
206+
"LC_CTYPE": "",
207+
"LC_ALL": "",
208+
}
209+
for env_var in base_var_dict:
210+
for locale_to_set in self.available_targets:
211+
with self.subTest(env_var=env_var,
212+
configured_locale=locale_to_set):
213+
var_dict = base_var_dict.copy()
214+
var_dict[env_var] = locale_to_set
215+
self._check_child_encoding_details(var_dict,
216+
expected_fsencoding,
217+
expected_warning)
218+
182219

183220
# Details of the shared library warning emitted at runtime
184221
LIBRARY_C_LOCALE_WARNING = (

‎Programs/python.c‎

Lines changed: 5 additions & 109 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ wmain(int argc, wchar_t **argv)
1515
}
1616
#else
1717

18-
/* Helpers to better handle the legacy C locale
18+
/* Access private pylifecycle helper API to better handle the legacy C locale
1919
*
2020
* The legacy C locale assumes ASCII as the default text encoding, which
2121
* causes problems not only for the CPython runtime, but also other
@@ -27,107 +27,8 @@ wmain(int argc, wchar_t **argv)
2727
* See the documentation of the PYTHONCOERCECLOCALE setting for more details.
2828
*
2929
*/
30-
31-
#ifdef PY_COERCE_C_LOCALE
32-
/* Access private pylifecycle API to check PYTHONCOERCECLOCALE */
33-
extern int _Py_CLocaleCoercionIsExpected(void);
34-
35-
static const char *_C_LOCALE_COERCION_WARNING =
36-
"Python detected LC_CTYPE=C: %.20s coerced to %.20s (set another locale "
37-
"or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
38-
39-
typedef struct _CandidateLocale {
40-
const char *locale_name;
41-
int category;
42-
} _LocaleCoercionTarget;
43-
44-
static _LocaleCoercionTarget _TARGET_LOCALES[] = {
45-
{ "C.UTF-8", LC_ALL },
46-
{ "C.utf8", LC_ALL },
47-
{ "UTF-8", LC_CTYPE },
48-
{ NULL, 0 }
49-
};
50-
51-
void
52-
_coerce_default_locale_settings(const _LocaleCoercionTarget *target)
53-
{
54-
const char *newloc = target->locale_name;
55-
int category = target->category;
56-
57-
/* Reset locale back to currently configured defaults */
58-
setlocale(LC_ALL, "");
59-
60-
/* Set the relevant locale environment variables */
61-
if (category == LC_ALL) {
62-
const char *env_vars_updated = "LC_ALL & LANG";
63-
if (setenv("LC_ALL", newloc, 1)) {
64-
fprintf(stderr,
65-
"Error setting LC_ALL, skipping C locale coercion\n");
66-
return;
67-
}
68-
if (setenv("LANG", newloc, 1)) {
69-
fprintf(stderr,
70-
"Error setting LANG during C locale coercion\n");
71-
env_vars_updated = "LC_ALL";
72-
}
73-
fprintf(stderr, _C_LOCALE_COERCION_WARNING, env_vars_updated, newloc);
74-
} else if (category == LC_CTYPE) {
75-
if (setenv("LC_CTYPE", newloc, 1)) {
76-
fprintf(stderr,
77-
"Error setting LC_CTYPE, skipping C locale coercion\n");
78-
return;
79-
}
80-
fprintf(stderr, _C_LOCALE_COERCION_WARNING, "LC_CTYPE", newloc);
81-
} else {
82-
fprintf(stderr, "Locale coercion must target LC_ALL or LC_CTYPE\n");
83-
return;
84-
}
85-
86-
/* Set standard stream encoding if PYTHONIOENCODING is not set
87-
*
88-
* We avoid setting PYTHONIOENCODING, as that can confuse Python 2
89-
* instances in subprocesses that inherit the environment (as Python
90-
* 2 has no 'surrogateescape' error handler).
91-
*
92-
* If PEP 540 is also implemented, this check will be replaced with
93-
* unconditionally setting PYTHONUTF8=1
94-
*/
95-
const char *io_encoding = getenv("PYTHONIOENCODING");
96-
if ((io_encoding == NULL) || (strnlen(io_encoding, 1) == 0)) {
97-
Py_SetStandardStreamEncoding("utf-8", "surrogateescape");
98-
}
99-
100-
/* Reconfigure with the overridden environment variables */
101-
setlocale(LC_ALL, "");
102-
}
103-
104-
void
105-
_handle_legacy_c_locale(void)
106-
{
107-
/* We ignore the Python -E and -I flags here, as we need to sort out
108-
* the locale settings *before* we try to do anything with the command
109-
* line arguments. For cross-platform debugging purposes, we also need
110-
* to give end users a way to force even scripts that are otherwise
111-
* isolated from their environment to use the legacy ASCII-centric C
112-
* locale.
113-
*/
114-
if (_Py_CLocaleCoercionIsExpected()) {
115-
/* PYTHONCOERCECLOCALE is not set, or is not set to exactly "0" */
116-
const _LocaleCoercionTarget *target = NULL;
117-
for (target = _TARGET_LOCALES; target->locale_name; target++) {
118-
const char *reconfigured_locale = setlocale(target->category,
119-
target->locale_name);
120-
if (reconfigured_locale != NULL) {
121-
/* Successfully configured locale, so make it the default */
122-
_coerce_default_locale_settings(target);
123-
return;
124-
}
125-
}
126-
127-
}
128-
/* No C locale warning here, as Py_Initialize will emit one later */
129-
}
130-
#endif
30+
extern int _Py_LegacyLocaleDetected(void);
31+
extern void _Py_CoerceLegacyLocale(void);
13132

13233
int
13334
main(int argc, char **argv)
@@ -177,14 +78,9 @@ main(int argc, char **argv)
17778
setlocale(LC_ALL, "");
17879
#endif
17980

180-
#ifdef PY_COERCE_C_LOCALE
181-
/* When the LC_CTYPE category still claims to be using the C locale,
182-
assume configuration error and try for a UTF-8 based locale instead */
183-
const char *ctype_loc = setlocale(LC_CTYPE, NULL);
184-
if (ctype_loc != NULL && strcmp(ctype_loc, "C") == 0) {
185-
_handle_legacy_c_locale();
81+
if (_Py_LegacyLocaleDetected()) {
82+
_Py_CoerceLegacyLocale();
18683
}
187-
#endif
18884

18985
/* Convert from char to wchar_t based on the locale settings */
19086
for (i = 0; i < argc; i++) {

0 commit comments

Comments
 (0)