Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Reorder env variable checks
  • Loading branch information
pablogsal committed Dec 5, 2023
commit ff19eecfcfe0d9d9d5a7aeb54c8645659c8c7979
8 changes: 4 additions & 4 deletions Lib/test/test_traceback.py
Original file line number Diff line number Diff line change
Expand Up @@ -4314,8 +4314,8 @@ def foo():
self.assertEqual(actual, expected)

def test_colorized_detection_checks_for_environment_variables(self):
with unittest.mock.patch("sys.stderr") as stderr_mock:
stderr_mock.isatty.return_value = True
with unittest.mock.patch("os.isatty") as isatty_mock:
isatty_mock.return_value = True
with unittest.mock.patch("os.environ", {'TERM': 'dumb'}):
self.assertEqual(traceback._can_colorize(), False)
with unittest.mock.patch("os.environ", {'PY_COLORS': '1'}):
Expand All @@ -4325,12 +4325,12 @@ def test_colorized_detection_checks_for_environment_variables(self):
with unittest.mock.patch("os.environ", {'NO_COLOR': '1'}):
self.assertEqual(traceback._can_colorize(), False)
with unittest.mock.patch("os.environ", {'NO_COLOR': '1', "PY_COLORS": '1'}):
self.assertEqual(traceback._can_colorize(), True)
self.assertEqual(traceback._can_colorize(), False)
with unittest.mock.patch("os.environ", {'FORCE_COLOR': '1'}):
self.assertEqual(traceback._can_colorize(), True)
with unittest.mock.patch("os.environ", {'FORCE_COLOR': '1', 'NO_COLOR': '1'}):
self.assertEqual(traceback._can_colorize(), False)
stderr_mock.isatty.return_value = False
isatty_mock.return_value = False
self.assertEqual(traceback._can_colorize(), False)

if __name__ == "__main__":
Expand Down
18 changes: 11 additions & 7 deletions Lib/traceback.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Extract, format and print information about Python stack traces."""

import os
import io
import collections.abc
import itertools
import linecache
Expand Down Expand Up @@ -141,19 +142,22 @@ def _can_colorize():
except (ImportError, AttributeError):
return False

if not _COLORIZE:
if "NO_COLOR" in os.environ:
return False
if os.environ.get("PY_COLORS") == "1":
return True
if os.environ.get("PY_COLORS") == "0":
return False
if "NO_COLOR" in os.environ:
if not _COLORIZE:
return False
if "FORCE_COLOR" in os.environ:
return True
return (
hasattr(sys.stderr, "isatty") and sys.stderr.isatty() and os.environ.get("TERM") != "dumb"
)
if os.environ.get("PY_COLORS") == "1":
return True
if os.environ.get("TERM") == "dumb":
return False
try:
return os.isatty(sys.stderr.fileno())
except io.UnsupportedOperation:
return sys.stderr.isatty()

def _print_exception_bltin(exc, /):
file = sys.stderr if sys.stderr is not None else sys.__stderr__
Expand Down