Migrate to modern win32/winrt API for `localemodule`
未關閉
還沒有人認領這個 Issue。
extension-modules
OS-windows
type-feature
- 主要語言
- Python
- 星號
- 77.2k
- 分支
- 36k
- 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?
- GlobalizationPreferences since Windows 10 (build 10240)
- GetUserDefaultLocaleName since Windows Vista / Windows Server 2008
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
貢獻指南
從這裡開始
- 先讀完整個 Issue,再讀專案的貢獻指南。
- 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
- Fork 儲存庫,在一個分支上完成修改。
- 送出 Pull Request,並在描述裡引用這個 Issue 編號。
研究方向
從 Modules/_localemodule.c 開始,尤其檢查 Windows NT pre-4.0 的相容性對映。查看 gh-90817、gh-130796 和 issue 123853 中的相關討論,然後將 GetUserDefaultLocaleName 與 GlobalizationPreferences 進行比較。只有在專案就現代 API 達成共識,並且舊版十六進位碼對映得到一致替換後,這項工作才算完成。
由索引模型根據 Issue 內容生成。
評估
- 技術堆疊
- c, python
- 領域
- internationalization, operating-systems
- Issue 類型
- 功能
- 難度
- 5/5
- 預估耗時
- 一週以上
- 活躍度
- 停滯
- 描述清晰度
- 需要釐清
- 新手友好度
- 25/100