1"""
2Utilities for dealing with text encodings
3"""
4
5from __future__ import annotations
6
7# -----------------------------------------------------------------------------
8# Copyright (C) 2008-2012 The IPython Development Team
9#
10# Distributed under the terms of the BSD License. The full license is in
11# the file COPYING, distributed as part of this software.
12# -----------------------------------------------------------------------------
13
14# -----------------------------------------------------------------------------
15# Imports
16# -----------------------------------------------------------------------------
17import sys
18import locale
19import warnings
20from typing import Any
21
22
23# to deal with the possibility of sys.std* not being a stream at all
24def get_stream_enc(stream: Any, default: str | None = None) -> str | None:
25 """Return the given stream's encoding or a default.
26
27 There are cases where ``sys.std*`` might not actually be a stream, so
28 check for the encoding attribute prior to returning it, and return
29 a default if it doesn't exist or evaluates as False. ``default``
30 is None if not provided.
31 """
32 if not hasattr(stream, "encoding") or not stream.encoding:
33 return default
34 else:
35 return stream.encoding
36
37
38_sentinel: object = object()
39
40
41# Less conservative replacement for sys.getdefaultencoding, that will try
42# to match the environment.
43# Defined here as central function, so if we find better choices, we
44# won't need to make changes all over IPython.
45def getdefaultencoding(prefer_stream: object | bool = _sentinel) -> str:
46 """Return IPython's guess for the default encoding for bytes as text.
47
48 If prefer_stream is True (default), asks for stdin.encoding first,
49 to match the calling Terminal, but that is often None for subprocesses.
50
51 Then fall back on locale.getpreferredencoding(),
52 which should be a sensible platform default (that respects LANG environment),
53 and finally to sys.getdefaultencoding() which is the most conservative option,
54 and usually UTF8 as of Python 3.
55 """
56 if prefer_stream is not _sentinel:
57 warnings.warn(
58 "getpreferredencoding(prefer_stream=) argument is deprecated since "
59 "IPython 9.0, getdefaultencoding() will take no argument in the "
60 "future. If you rely on `prefer_stream`, please open an issue on "
61 "the IPython repo.",
62 DeprecationWarning,
63 stacklevel=2,
64 )
65 prefer_stream = True
66 enc: str | None = None
67 if prefer_stream:
68 enc = get_stream_enc(sys.stdin)
69 if not enc or enc == "ascii":
70 try:
71 # There are reports of getpreferredencoding raising errors
72 # in some cases, which may well be fixed, but let's be conservative here.
73 enc = locale.getpreferredencoding()
74 except Exception:
75 pass
76 enc = enc or sys.getdefaultencoding()
77 # On windows `cp0` can be returned to indicate that there is no code page.
78 # Since cp0 is an invalid encoding return instead cp1252 which is the
79 # Western European default.
80 if enc == "cp0":
81 warnings.warn(
82 "Invalid code page cp0 detected - using cp1252 instead."
83 "If cp1252 is incorrect please ensure a valid code page "
84 "is defined for the process.",
85 RuntimeWarning,
86 )
87 return "cp1252"
88 return enc
89
90
91DEFAULT_ENCODING = getdefaultencoding()