python / python/cpython

Migrate to modern win32/winrt API for `localemodule`

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

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

extension-modules OS-windows type-feature
主要言語
Python
スター
77.2k
フォーク
35.9k
PR マージ指標
PR 指標を取得中

説明

Feature or enhancement

Proposal:

AFAIK, CPython has dropped support for Windows 7 since 3.9.0, while _localemodule.c contains compatibility fix for Windows NT pre-4.0. Which flag was introduced since Windows 98.

Here I listed some modern way to get locale name in BCP-47 / RFC 1766 format, is it possible to replace the legacy hex code mapping?

import ctypes
from ctypes import wintypes
from locale import getdefaultlocale, getlocale, LC_CTYPE
import warnings

# Introduced since Windows 10, BCP-47
# depends on:
# - winrt-windows-system-userprofile
# - winrt-windows-foundation
# - winrt-windows-foundation-collections
from winrt.windows.system.userprofile import GlobalizationPreferences

warnings.filterwarnings("ignore", category=DeprecationWarning)

# Load kernel32.dll
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)

# Introduced since Windows Vista, RFC 1766
# Define GetUserDefaultLocaleName signature
# int GetUserDefaultLocaleName(LPWSTR lpLocaleName, int cchLocaleName);
kernel32.GetUserDefaultLocaleName.argtypes = [wintypes.LPWSTR, ctypes.c_int]
kernel32.GetUserDefaultLocaleName.restype = ctypes.c_int

# Allocate buffer for locale name
LOCALE_NAME_MAX_LENGTH = 85  # per Windows docs


def user_default_locale() -> str:
    """
    Get user default locale encoded in BCP-47.
    """
    buffer = ctypes.create_unicode_buffer(LOCALE_NAME_MAX_LENGTH)

    # Call the function
    result = kernel32.GetUserDefaultLocaleName(buffer, LOCALE_NAME_MAX_LENGTH)

    if result == 0:
        # Call failed
        error_code = ctypes.get_last_error()
        raise ctypes.WinError(error_code)

    return buffer.value


def bcp47():
    return GlobalizationPreferences.languages[0]
>>> getdefaultlocale()
('zh_CN', 'cp936')
>>> getlocale(LC_CTYPE)
('Chinese (Simplified)_China', '936')
>>> user_default_locale()
'zh-CN'
>>> bcp47()
'zh-Hans-CN'
Has this already been discussed elsewhere?

Yes

Links to previous discussion of this feature:

gh-90817 gh-130796 https://github.com/python/cpython/issues/123853#issuecomment-3132027944

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

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

はじめの一歩

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

調査の方向性

まず Modules/_localemodule.c から始め、特に Windows NT pre-4.0 用の互換性マッピングを確認してください。gh-90817、gh-130796、issue 123853 にあるリンク先の議論を確認し、その後 GetUserDefaultLocaleName と GlobalizationPreferences を比較してください。プロジェクトが最新の API に合意し、レガシーな 16 進コードのマッピングが一貫して置き換えられて初めて、作業は完了です。

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

評価

技術スタック
c, python
領域
internationalization, operating-systems
issue の種類
機能追加
難易度
5/5
見積もり時間
1週間以上
活発さ
停滞
明瞭さ
説明が足りない
初心者へのやさしさ
25/100

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

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