Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid importing IPython if notebook cells do not contain magics #3782

Merged
merged 9 commits into from Jul 17, 2023
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGES.md
Expand Up @@ -30,6 +30,8 @@

<!-- Changes that improve Black's performance. -->

- minimize cost of introspection to detect jupyter dependencies (#3782)

### Output

<!-- Changes to Black's terminal output and error messages -->
Expand Down
27 changes: 9 additions & 18 deletions src/black/handle_ipynb_magics.py
Expand Up @@ -6,6 +6,7 @@
import secrets
import sys
from functools import lru_cache
from importlib.util import find_spec
from typing import Dict, List, Optional, Tuple

if sys.version_info >= (3, 10):
Expand Down Expand Up @@ -57,24 +58,14 @@ class Replacement:

@lru_cache
def jupyter_dependencies_are_installed(*, verbose: bool, quiet: bool) -> bool:
try:
# isort: off
# tokenize_rt is less commonly installed than IPython
# and IPython is expensive to import
import tokenize_rt # noqa:F401
import IPython # noqa:F401

# isort: on
except ModuleNotFoundError:
if verbose or not quiet:
msg = (
"Skipping .ipynb files as Jupyter dependencies are not installed.\n"
'You can fix this by running ``pip install "black[jupyter]"``'
)
out(msg)
return False
else:
return True
retv = find_spec("tokenize_rt") is not None and find_spec("IPython") is not None
if not retv and (verbose or not quiet):
msg = (
"Skipping .ipynb files as Jupyter dependencies are not installed.\n"
'You can fix this by running ``pip install "black[jupyter]"``'
)
out(msg)
return retv


def remove_trailing_semicolon(src: str) -> Tuple[str, bool]:
Expand Down