@@ -1023,7 +1023,7 @@ _io.TextIOWrapper.__init__
10231023Character and line based layer over a BufferedIOBase object, buffer.
10241024
10251025encoding gives the name of the encoding that the stream will be
1026- decoded or encoded with. It defaults to locale.getpreferredencoding(False ).
1026+ decoded or encoded with. It defaults to locale.getencoding( ).
10271027
10281028errors determines the strictness of encoding and decoding (see
10291029help(codecs.Codec) or the documentation for codecs.register) and
@@ -1055,12 +1055,12 @@ _io_TextIOWrapper___init___impl(textio *self, PyObject *buffer,
10551055 const char * encoding , PyObject * errors ,
10561056 const char * newline , int line_buffering ,
10571057 int write_through )
1058- /*[clinic end generated code: output=72267c0c01032ed2 input=77d8696d1a1f460b ]*/
1058+ /*[clinic end generated code: output=72267c0c01032ed2 input=72590963698f289b ]*/
10591059{
10601060 PyObject * raw , * codec_info = NULL ;
1061- _PyIO_State * state = NULL ;
10621061 PyObject * res ;
10631062 int r ;
1063+ int use_locale_encoding = 0 ; // Use locale encoding even in UTF-8 mode.
10641064
10651065 self -> ok = 0 ;
10661066 self -> detached = 0 ;
@@ -1076,6 +1076,7 @@ _io_TextIOWrapper___init___impl(textio *self, PyObject *buffer,
10761076 }
10771077 else if (strcmp (encoding , "locale" ) == 0 ) {
10781078 encoding = NULL ;
1079+ use_locale_encoding = 1 ;
10791080 }
10801081
10811082 if (errors == Py_None ) {
@@ -1113,10 +1114,15 @@ _io_TextIOWrapper___init___impl(textio *self, PyObject *buffer,
11131114 self -> encodefunc = NULL ;
11141115 self -> b2cratio = 0.0 ;
11151116
1117+ #ifdef MS_WINDOWS
1118+ // os.device_encoding() on Unix is the locale encoding or UTF-8
1119+ // according to UTF-8 Mode.
1120+ // Since UTF-8 mode shouldn't affect `encoding="locale"`, we call
1121+ // os.device_encoding() only on Windows.
11161122 if (encoding == NULL ) {
11171123 /* Try os.device_encoding(fileno) */
11181124 PyObject * fileno ;
1119- state = IO_STATE ();
1125+ _PyIO_State * state = IO_STATE ();
11201126 if (state == NULL )
11211127 goto error ;
11221128 fileno = PyObject_CallMethodNoArgs (buffer , & _Py_ID (fileno ));
@@ -1144,8 +1150,10 @@ _io_TextIOWrapper___init___impl(textio *self, PyObject *buffer,
11441150 Py_CLEAR (self -> encoding );
11451151 }
11461152 }
1153+ #endif
1154+
11471155 if (encoding == NULL && self -> encoding == NULL ) {
1148- if (_PyRuntime .preconfig .utf8_mode ) {
1156+ if (_PyRuntime .preconfig .utf8_mode && ! use_locale_encoding ) {
11491157 _Py_DECLARE_STR (utf_8 , "utf-8" );
11501158 self -> encoding = Py_NewRef (& _Py_STR (utf_8 ));
11511159 }
0 commit comments