@@ -286,25 +286,30 @@ def decolor(text: str) -> str:
286286 return text
287287
288288
289- def can_colorize (* , file : IO [str ] | IO [bytes ] | None = None , already_colorize : bool = False ) -> bool :
290- if already_colorize :
291- return True
289+ def can_colorize (* , file : IO [str ] | IO [bytes ] | None = None ) -> bool :
290+
291+ def _safe_getenv (k : str , fallback : str | None = None ) -> str | None :
292+ """Exception-safe environment retrieval. See gh-128636."""
293+ try :
294+ return os .environ .get (k , fallback )
295+ except Exception :
296+ return fallback
292297
293298 if file is None :
294299 file = sys .stdout
295300
296301 if not sys .flags .ignore_environment :
297- if os . environ . get ("PYTHON_COLORS" ) == "0" :
302+ if _safe_getenv ("PYTHON_COLORS" ) == "0" :
298303 return False
299- if os . environ . get ("PYTHON_COLORS" ) == "1" :
304+ if _safe_getenv ("PYTHON_COLORS" ) == "1" :
300305 return True
301- if os . environ . get ("NO_COLOR" ):
306+ if _safe_getenv ("NO_COLOR" ):
302307 return False
303308 if not COLORIZE :
304309 return False
305- if os . environ . get ("FORCE_COLOR" ):
310+ if _safe_getenv ("FORCE_COLOR" ):
306311 return True
307- if os . environ . get ("TERM" ) == "dumb" :
312+ if _safe_getenv ("TERM" ) == "dumb" :
308313 return False
309314
310315 if not hasattr (file , "fileno" ):
@@ -334,7 +339,6 @@ def get_theme(
334339 tty_file : IO [str ] | IO [bytes ] | None = None ,
335340 force_color : bool = False ,
336341 force_no_color : bool = False ,
337- already_colorize : bool = False ,
338342) -> Theme :
339343 """Returns the currently set theme, potentially in a zero-color variant.
340344
@@ -349,7 +353,7 @@ def get_theme(
349353 on Windows) can also change in the course of the application life cycle.
350354 """
351355 if force_color or (not force_no_color and
352- can_colorize (file = tty_file , already_colorize = already_colorize )):
356+ can_colorize (file = tty_file )):
353357 return _theme
354358 return theme_no_color
355359
0 commit comments