Skip to content

Commit

Permalink
Improve startuptime: don't import IPython/ipykernal if not in jupyter (
Browse files Browse the repository at this point in the history
…#1001)

Co-authored-by: Delgan <delgan.py@gmail.com>
  • Loading branch information
zakstucke and Delgan committed Oct 16, 2023
1 parent a48a0e2 commit db0c848
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
3 changes: 2 additions & 1 deletion loguru/_colorama.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import builtins
import os
import sys

Expand All @@ -6,7 +7,7 @@ def should_colorize(stream):
if stream is None:
return False

if stream is sys.stdout or stream is sys.stderr:
if getattr(builtins, "__IPYTHON__", False) and (stream is sys.stdout or stream is sys.stderr):
try:
import ipykernel
import IPython
Expand Down
12 changes: 12 additions & 0 deletions tests/test_colorama.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import builtins
import os
import sys
from unittest.mock import MagicMock
Expand Down Expand Up @@ -172,13 +173,24 @@ class Shell:
ipykernel.zmqshell.ZMQInteractiveShell = Shell
ipykernel.iostream.OutStream = out_class

monkeypatch.setattr(builtins, "__IPYTHON__", True, raising=False)
monkeypatch.setitem(sys.modules, "IPython", ipython)
monkeypatch.setitem(sys.modules, "ipykernel", ipykernel)
monkeypatch.setattr(sys, patched, stream, raising=False)

assert should_colorize(stream) is expected


def test_jupyter_missing_lib(monkeypatch):
# Missing ipykernal so jupyter block will err, should handle gracefully
stream = StreamIsattyFalse()

monkeypatch.setattr(builtins, "__IPYTHON__", True, raising=False)
monkeypatch.setattr(sys, "stdout", stream)

assert should_colorize(stream) is False


@pytest.mark.parametrize("patched", ["__stdout__", "__stderr__"])
@pytest.mark.skipif(os.name == "nt", reason="Colorama is required on Windows")
def test_dont_wrap_on_linux(monkeypatch, patched, patch_colorama):
Expand Down

0 comments on commit db0c848

Please sign in to comment.