python / python/cpython

locale.getlocale() returns wrong encoding if the locale name doesn't have one

オープン
#151,316 コメント 1 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

stdlib topic-unicode type-bug
主要言語
Python
スター
77.2k
フォーク
35.9k
PR マージ指標
PR 指標を取得中

説明

Bug report

Bug description:

Some locales don't have an encoding especifier, and python (wrongly) assumes it is ISO-8859-1, when it may not be. For example, the following code:

import locale

l = locale.getlocale()
print(f"locale: {l}, encoding: {locale.getencoding()}")
locale.setlocale(locale.LC_ALL, l)

Returns:

$ LANG=en_GB.UTF-8 python3 test.py 
locale: ('en_GB', 'UTF-8'), encoding: UTF-8
$ LANG=en_IN python3 test.py 
locale: ('en_IN', 'ISO8859-1'), encoding: UTF-8
Traceback (most recent call last):
  File "/home/emilio/profesional/freexian-ext/test.py", line 5, in <module>
    locale.setlocale(locale.LC_ALL, l)
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.13/locale.py", line 615, in setlocale
    return _setlocale(category, locale)
locale.Error: unsupported locale setting

Traceback (most recent call last):
  File "/home/emilio/test.py", line 5, in <module>
    locale.setlocale(locale.LC_ALL, l)
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.13/locale.py", line 615, in setlocale
    return _setlocale(category, locale)
locale.Error: unsupported locale setting

The en_IN locale uses UTF-8, which is correctly returned in locale.getencoding(), but not in locale.getlocale(). Using the tuple returned by locale.getlocale() in a setlocale call fails.

This probably affects other locales that use UTF-8 as their encoding but don't especify it in the locale name.

This was tested on Debian stable (trixie) with Python 3.13.

CPython versions tested on:

3.13

Operating systems tested on:

Linux

Linked PRs
  • gh-155549

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

このレポートは locale.py を示しており、再現可能な test.py の例が含まれています。まず、Linux 上で LANG=en_IN を指定して実行し、locale.getlocale() と locale.getencoding() を比較します。名前にエンコーディングが含まれないロケールについて、locale.getlocale() が使用可能な UTF-8 エンコーディングを保持し、その結果を locale.setlocale() に渡しても失敗しなくなれば完了です。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
python
領域
localization
issue の種類
バグ
難易度
3/5
見積もり時間
1〜2日
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
35/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。