1"""
2Unopinionated display configuration.
3"""
4
5from __future__ import annotations
6
7import locale
8import sys
9
10from pandas._config import config as cf
11
12# -----------------------------------------------------------------------------
13# Global formatting options
14_initial_defencoding: str | None = None
15
16
17def detect_console_encoding() -> str:
18 """
19 Try to find the most capable encoding supported by the console.
20 slightly modified from the way IPython handles the same issue.
21 """
22 global _initial_defencoding
23
24 encoding = None
25 try:
26 encoding = sys.stdout.encoding or sys.stdin.encoding
27 except (AttributeError, OSError):
28 pass
29
30 # try again for something better
31 if not encoding or "ascii" in encoding.lower():
32 try:
33 encoding = locale.getpreferredencoding()
34 except locale.Error:
35 # can be raised by locale.setlocale(), which is
36 # called by getpreferredencoding
37 # (on some systems, see stdlib locale docs)
38 pass
39
40 # when all else fails. this will usually be "ascii"
41 if not encoding or "ascii" in encoding.lower():
42 encoding = sys.getdefaultencoding()
43
44 # GH#3360, save the reported defencoding at import time
45 # MPL backends may change it. Make available for debugging.
46 if not _initial_defencoding:
47 _initial_defencoding = sys.getdefaultencoding()
48
49 return encoding
50
51
52pc_encoding_doc = """
53: str/unicode
54 Defaults to the detected encoding of the console.
55 Specifies the encoding to be used for strings returned by to_string,
56 these are generally strings meant to be displayed on the console.
57"""
58
59with cf.config_prefix("display"):
60 cf.register_option(
61 "encoding", detect_console_encoding(), pc_encoding_doc, validator=cf.is_text
62 )