✅ Use Ruff rules to ensure safe lazy-loading of `rich` (#1297)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Nathan McDougall · committed by GitHub · parent 0fc0dda · Browse files · 24 files·+85 added−102 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
- Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>
Diff stats
24 files+85 added−102 removed
- tests:+58 added−74 removed
- other:+27 added−28 removed
Provenance
- Commit
661b49e- Tree
bceb8d2- Author
Nathan McDougall <nathan.j.mcdougall@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
0fc0dda
24 files changed+85 added−102 removed
modified:tests/assets/type_error_no_rich_short_disable.py+1 added-1 removed
1 import typer2 import typer.main3 4-typer.main.rich = None4+typer.main.HAS_RICH = False5 6 7 app = typer.Typer(pretty_exceptions_short=False)8 8 unmodified linesmodified:tests/assets/type_error_no_rich.py+1 added-1 removed
1 import typer2 import typer.main3 4-typer.main.rich = None4+typer.main.HAS_RICH = False5 6 7 def main(name: str = "morty"):8 print(name + 3)4 unmodified linesmodified:tests/test_tutorial/test_arguments/test_envvar/test_tutorial001_an.py+4 added-4 removed
1 import subprocess2 import sys3 4+import pytest5 import typer6 import typer.core7 from typer.testing import CliRunner8 13 unmodified lines22 assert "env var: AWESOME_NAME" in result.output23 assert "default: World" in result.output24 25 25-def test_help_no_rich():26- rich = typer.core.rich27- typer.core.rich = None26+def test_help_no_rich(monkeypatch: pytest.MonkeyPatch):27+ monkeypatch.setattr(typer.core, "HAS_RICH", False)28+29 result = runner.invoke(app, ["--help"])30 assert result.exit_code == 031 assert "[OPTIONS] [NAME]" in result.output32 assert "Arguments" in result.output33 assert "env var: AWESOME_NAME" in result.output34 assert "default: World" in result.output34- typer.core.rich = rich35 36 37 def test_call_arg():38 result = runner.invoke(app, ["Wednesday"])23 unmodified linesmodified:tests/test_tutorial/test_arguments/test_envvar/test_tutorial001.py+3 added-4 removed
1 import subprocess2 import sys3 4+import pytest5 import typer6 import typer.core7 from typer.testing import CliRunner8 13 unmodified lines22 assert "env var: AWESOME_NAME" in result.output23 assert "default: World" in result.output24 25 25-def test_help_no_rich():26- rich = typer.core.rich27- typer.core.rich = None26+def test_help_no_rich(monkeypatch: pytest.MonkeyPatch):27+ monkeypatch.setattr(typer.core, "HAS_RICH", False)28 result = runner.invoke(app, ["--help"])29 assert result.exit_code == 030 assert "[OPTIONS] [NAME]" in result.output31 assert "Arguments" in result.output32 assert "env var: AWESOME_NAME" in result.output33 assert "default: World" in result.output34- typer.core.rich = rich34 35 36 def test_call_arg():37 result = runner.invoke(app, ["Wednesday"])23 unmodified linesmodified:tests/test_tutorial/test_arguments/test_help/test_tutorial001_an.py+3 added-4 removed
1 import subprocess2 import sys3 4+import pytest5 import typer6 import typer.core7 from typer.testing import CliRunner8 14 unmodified lines23 assert "The name of the user to greet" in result.output24 assert "[required]" in result.output25 26 26-def test_help_no_rich():27- rich = typer.core.rich28- typer.core.rich = None27+def test_help_no_rich(monkeypatch: pytest.MonkeyPatch):28+ monkeypatch.setattr(typer.core, "HAS_RICH", False)29 result = runner.invoke(app, ["--help"])30 assert result.exit_code == 031 assert "[OPTIONS] NAME" in result.output32 assert "Arguments" in result.output33 assert "NAME" in result.output34 assert "The name of the user to greet" in result.output35 assert "[required]" in result.output36- typer.core.rich = rich36 37 38 def test_call_arg():39 result = runner.invoke(app, ["Camila"])11 unmodified linesmodified:tests/test_tutorial/test_arguments/test_help/test_tutorial001.py+3 added-4 removed
1 import subprocess2 import sys3 4+import pytest5 import typer6 import typer.core7 from typer.testing import CliRunner8 14 unmodified lines23 assert "The name of the user to greet" in result.output24 assert "[required]" in result.output25 26 26-def test_help_no_rich():27- rich = typer.core.rich28- typer.core.rich = None27+def test_help_no_rich(monkeypatch: pytest.MonkeyPatch):28+ monkeypatch.setattr(typer.core, "HAS_RICH", False)29 result = runner.invoke(app, ["--help"])30 assert result.exit_code == 031 assert "[OPTIONS] NAME" in result.output32 assert "Arguments" in result.output33 assert "NAME" in result.output34 assert "The name of the user to greet" in result.output35 assert "[required]" in result.output36- typer.core.rich = rich36 37 38 def test_call_arg():39 result = runner.invoke(app, ["Camila"])11 unmodified linesmodified:tests/test_tutorial/test_arguments/test_help/test_tutorial008_an.py+3 added-4 removed
1 import subprocess2 import sys3 4+import pytest5 import typer6 import typer.core7 from typer.testing import CliRunner8 13 unmodified lines22 assert "Arguments" not in result.output23 assert "[default: World]" not in result.output24 25 25-def test_help_no_rich():26- rich = typer.core.rich27- typer.core.rich = None26+def test_help_no_rich(monkeypatch: pytest.MonkeyPatch):27+ monkeypatch.setattr(typer.core, "HAS_RICH", False)28 result = runner.invoke(app, ["--help"])29 assert result.exit_code == 030 assert "[OPTIONS] [NAME]" in result.output31 assert "Say hi to NAME very gently, like Dirk." in result.output32 assert "Arguments" not in result.output33 assert "[default: World]" not in result.output34- typer.core.rich = rich34 35 36 def test_call_arg():37 result = runner.invoke(app, ["Camila"])11 unmodified linesmodified:tests/test_tutorial/test_arguments/test_help/test_tutorial008.py+3 added-4 removed
1 import subprocess2 import sys3 4+import pytest5 import typer6 import typer.core7 from typer.testing import CliRunner8 13 unmodified lines22 assert "Arguments" not in result.output23 assert "[default: World]" not in result.output24 25 25-def test_help_no_rich():26- rich = typer.core.rich27- typer.core.rich = None26+def test_help_no_rich(monkeypatch: pytest.MonkeyPatch):27+ monkeypatch.setattr(typer.core, "HAS_RICH", False)28 result = runner.invoke(app, ["--help"])29 assert result.exit_code == 030 assert "[OPTIONS] [NAME]" in result.output31 assert "Say hi to NAME very gently, like Dirk." in result.output32 assert "Arguments" not in result.output33 assert "[default: World]" not in result.output34- typer.core.rich = rich34 35 36 def test_call_arg():37 result = runner.invoke(app, ["Camila"])11 unmodified linesmodified:tests/test_tutorial/test_arguments/test_optional/test_tutorial001_an.py+3 added-4 removed
1 import subprocess2 import sys3 4+import pytest5 import typer6 import typer.core7 from typer.testing import CliRunner8 16 unmodified lines25 result = runner.invoke(app, standalone_mode=False)26 assert result.exit_code != 027 28 28-def test_call_no_arg_no_rich():29+def test_call_no_arg_no_rich(monkeypatch: pytest.MonkeyPatch):30 # Mainly for coverage30- rich = typer.core.rich31- typer.core.rich = None31+ monkeypatch.setattr(typer.core, "HAS_RICH", False)32 result = runner.invoke(app)33 assert result.exit_code != 034 assert "Error: Missing argument 'NAME'" in result.output35- typer.core.rich = rich35 36 37 def test_call_arg():38 result = runner.invoke(app, ["Camila"])11 unmodified linesmodified:tests/test_tutorial/test_arguments/test_optional/test_tutorial001.py+3 added-4 removed
1 import subprocess2 import sys3 4+import pytest5 import typer6 import typer.core7 from typer.testing import CliRunner8 16 unmodified lines25 result = runner.invoke(app, standalone_mode=False)26 assert result.exit_code != 027 28 28-def test_call_no_arg_no_rich():29+def test_call_no_arg_no_rich(monkeypatch: pytest.MonkeyPatch):30 # Mainly for coverage30- rich = typer.core.rich31- typer.core.rich = None31+ monkeypatch.setattr(typer.core, "HAS_RICH", False)32 result = runner.invoke(app)33 assert result.exit_code != 034 assert "Error: Missing argument 'NAME'" in result.output35- typer.core.rich = rich35 36 37 def test_call_arg():38 result = runner.invoke(app, ["Camila"])11 unmodified linesmodified:tests/test_tutorial/test_arguments/test_optional/test_tutorial003.py+3 added-4 removed
1 import subprocess2 import sys3 4+import pytest5 import typer6 import typer.core7 from typer.testing import CliRunner8 16 unmodified lines25 result = runner.invoke(app, standalone_mode=False)26 assert result.exit_code != 027 28 28-def test_call_no_arg_no_rich():29+def test_call_no_arg_no_rich(monkeypatch: pytest.MonkeyPatch):30 # Mainly for coverage30- rich = typer.core.rich31- typer.core.rich = None31+ monkeypatch.setattr(typer.core, "HAS_RICH", False)32 result = runner.invoke(app)33 assert result.exit_code != 034 assert "Error: Missing argument 'NAME'" in result.output35- typer.core.rich = rich35 36 37 def test_call_arg():38 result = runner.invoke(app, ["Camila"])11 unmodified linesmodified:tests/test_tutorial/test_commands/test_callback/test_tutorial001.py+3 added-4 removed
1 import subprocess2 import sys3 4+import pytest5 import typer.core6 from typer.testing import CliRunner7 8 from docs_src.commands.callback import tutorial001 as mod10 unmodified lines19 assert "--verbose" in result.output20 assert "--no-verbose" in result.output21 22 22-def test_help_no_rich():23- rich = typer.core.rich24- typer.core.rich = None23+def test_help_no_rich(monkeypatch: pytest.MonkeyPatch):24+ monkeypatch.setattr(typer.core, "HAS_RICH", False)25 result = runner.invoke(app, ["--help"])26 assert result.exit_code == 027 assert "Manage users in the awesome CLI app." in result.output28 assert "--verbose" in result.output29 assert "--no-verbose" in result.output30- typer.core.rich = rich30 31 32 def test_create():33 result = runner.invoke(app, ["create", "Camila"])41 unmodified linesmodified:tests/test_tutorial/test_options/test_required/test_tutorial001_an.py+3 added-4 removed
1 import subprocess2 import sys3 4+import pytest5 import typer6 import typer.core7 from typer.testing import CliRunner8 24 unmodified lines33 assert "TEXT" in result.output34 assert "[required]" in result.output35 36 36-def test_help_no_rich():37- rich = typer.core.rich38- typer.core.rich = None37+def test_help_no_rich(monkeypatch: pytest.MonkeyPatch):38+ monkeypatch.setattr(typer.core, "HAS_RICH", False)39 result = runner.invoke(app, ["--help"])40 assert result.exit_code == 041 assert "--lastname" in result.output42 assert "TEXT" in result.output43 assert "[required]" in result.output44- typer.core.rich = rich44 45 46 def test_script():47 result = subprocess.run(5 unmodified linesmodified:tests/test_tutorial/test_options/test_required/test_tutorial001.py+3 added-4 removed
1 import subprocess2 import sys3 4+import pytest5 import typer6 import typer.core7 from typer.testing import CliRunner8 24 unmodified lines33 assert "TEXT" in result.output34 assert "[required]" in result.output35 36 36-def test_help_no_rich():37- rich = typer.core.rich38- typer.core.rich = None37+def test_help_no_rich(monkeypatch: pytest.MonkeyPatch):38+ monkeypatch.setattr(typer.core, "HAS_RICH", False)39 result = runner.invoke(app, ["--help"])40 assert result.exit_code == 041 assert "--lastname" in result.output42 assert "TEXT" in result.output43 assert "[required]" in result.output44- typer.core.rich = rich44 45 46 def test_script():47 result = subprocess.run(5 unmodified linesmodified:tests/test_tutorial/test_parameter_types/test_bool/test_tutorial002_an.py+3 added-4 removed
1 import subprocess2 import sys3 4+import pytest5 import typer6 import typer.core7 from typer.testing import CliRunner8 12 unmodified lines21 assert "--reject" in result.output22 assert "--no-accept" not in result.output23 24 24-def test_help_no_rich():25- rich = typer.core.rich26- typer.core.rich = None25+def test_help_no_rich(monkeypatch: pytest.MonkeyPatch):26+ monkeypatch.setattr(typer.core, "HAS_RICH", False)27 result = runner.invoke(app, ["--help"])28 assert result.exit_code == 029 assert "--accept" in result.output30 assert "--reject" in result.output31 assert "--no-accept" not in result.output32- typer.core.rich = rich32 33 34 def test_main():35 result = runner.invoke(app)29 unmodified linesmodified:tests/test_tutorial/test_parameter_types/test_bool/test_tutorial002.py+3 added-4 removed
1 import subprocess2 import sys3 4+import pytest5 import typer6 import typer.core7 from typer.testing import CliRunner8 12 unmodified lines21 assert "--reject" in result.output22 assert "--no-accept" not in result.output23 24 24-def test_help_no_rich():25- rich = typer.core.rich26- typer.core.rich = None25+def test_help_no_rich(monkeypatch: pytest.MonkeyPatch):26+ monkeypatch.setattr(typer.core, "HAS_RICH", False)27 result = runner.invoke(app, ["--help"])28 assert result.exit_code == 029 assert "--accept" in result.output30 assert "--reject" in result.output31 assert "--no-accept" not in result.output32- typer.core.rich = rich32 33 34 def test_main():35 result = runner.invoke(app)29 unmodified linesmodified:tests/test_tutorial/test_parameter_types/test_number/test_tutorial001_an.py+3 added-4 removed
1 import subprocess2 import sys3 4+import pytest5 import typer6 import typer.core7 from typer.testing import CliRunner8 13 unmodified lines22 assert "--score" in result.output23 assert "FLOAT RANGE" in result.output24 25 25-def test_help_no_rich():26- rich = typer.core.rich27- typer.core.rich = None26+def test_help_no_rich(monkeypatch: pytest.MonkeyPatch):27+ monkeypatch.setattr(typer.core, "HAS_RICH", False)28 result = runner.invoke(app, ["--help"])29 assert result.exit_code == 030 assert "--age" in result.output31 assert "INTEGER RANGE" in result.output32 assert "--score" in result.output33 assert "FLOAT RANGE" in result.output34- typer.core.rich = rich34 35 36 def test_params():37 result = runner.invoke(app, ["5", "--age", "20", "--score", "90"])43 unmodified linesmodified:tests/test_tutorial/test_parameter_types/test_number/test_tutorial001.py+3 added-4 removed
1 import subprocess2 import sys3 4+import pytest5 import typer6 import typer.core7 from typer.testing import CliRunner8 13 unmodified lines22 assert "--score" in result.output23 assert "FLOAT RANGE" in result.output24 25 25-def test_help_no_rich():26- rich = typer.core.rich27- typer.core.rich = None26+def test_help_no_rich(monkeypatch: pytest.MonkeyPatch):27+ monkeypatch.setattr(typer.core, "HAS_RICH", False)28 result = runner.invoke(app, ["--help"])29 assert result.exit_code == 030 assert "--age" in result.output31 assert "INTEGER RANGE" in result.output32 assert "--score" in result.output33 assert "FLOAT RANGE" in result.output34- typer.core.rich = rich34 35 36 def test_params():37 result = runner.invoke(app, ["5", "--age", "20", "--score", "90"])43 unmodified linesmodified:tests/test_tutorial/test_terminating/test_tutorial003.py+3 added-4 removed
1 import subprocess2 import sys3 4+import pytest5 import typer6 import typer.core7 from typer.testing import CliRunner8 23 unmodified lines32 result = runner.invoke(app, ["root"], standalone_mode=False)33 assert result.exit_code == 134 35 35-def test_root_no_rich():36+def test_root_no_rich(monkeypatch: pytest.MonkeyPatch):37 # Mainly for coverage37- rich = typer.core.rich38- typer.core.rich = None38+ monkeypatch.setattr(typer.core, "HAS_RICH", False)39 result = runner.invoke(app, ["root"])40 assert result.exit_code == 141 assert "The root user is reserved" in result.output42 assert "Aborted!" in result.output43- typer.core.rich = rich43 44 45 def test_script():46 result = subprocess.run(5 unmodified linesmodified:tests/test_corner_cases.py+4 added-4 removed
1+import pytest2 import typer.core3 from typer.testing import CliRunner4 5 from tests.assets import corner_cases as mod10 unmodified lines16 assert "TEST_LASTNAME" in result.output17 assert "(dynamic)" in result.output18 19 19-def test_hidden_option_no_rich():20- rich = typer.core.rich21- typer.core.rich = None20+def test_hidden_option_no_rich(monkeypatch: pytest.MonkeyPatch):21+ monkeypatch.setattr(typer.core, "HAS_RICH", False)22+23 result = runner.invoke(mod.app, ["--help"])24 assert result.exit_code == 025 assert "Say hello" in result.output26 assert "--name" not in result.output27 assert "/lastname" in result.output28 assert "TEST_LASTNAME" in result.output29 assert "(dynamic)" in result.output29- typer.core.rich = rich30 31 32 def test_coverage_call():33 result = runner.invoke(mod.app)2 unmodified linesmodified:typer/cli.py+2 added-10 removed
8 unmodified lines9 import typer.core10 from click import Command, Group, Option11 12 from . import __version__13+from .core import HAS_RICH14 14-try:15- import rich16-17- has_rich = True18-19-except ImportError: # pragma: no cover20- has_rich = False21- rich = None # type: ignore22-15 default_app_names = ("app", "cli", "main")16 default_func_names = ("main", "cli", "app")17 18 app = typer.Typer()244 unmodified lines263 return docs264 265 266 def _parse_html(input_text: str) -> str:275- if not has_rich: # pragma: no cover267+ if not HAS_RICH: # pragma: no cover268 return input_text269 from . import rich_utils270 271 return rich_utils.rich_to_html(input_text)37 unmodified linesmodified:typer/core.py+10 added-11 removed
1 import errno2+import importlib.util3 import inspect4 import os5 import sys6 from enum import Enum23 unmodified lines30 from ._typing import Literal31 32 MarkupMode = Literal["markdown", "rich", None]33 33-try:34- import rich34+HAS_RICH = importlib.util.find_spec("rich") is not None35 36+if HAS_RICH:37 DEFAULT_MARKUP_MODE: MarkupMode = "rich"37-38-except ImportError: # pragma: no cover38+else: # pragma: no cover39- rich = None # type: ignore39 DEFAULT_MARKUP_MODE = None40 41 42 # Copy from click.parser._split_opt165 unmodified lines208 except click.ClickException as e:209 if not standalone_mode:210 raise211 # Typer override213- if rich and rich_markup_mode is not None:212+ if HAS_RICH and rich_markup_mode is not None:213 from . import rich_utils214 215 rich_utils.rich_format_error(e)216 else:23 unmodified lines240 except click.Abort:241 if not standalone_mode:242 raise243 # Typer override245- if rich and rich_markup_mode is not None:244+ if HAS_RICH and rich_markup_mode is not None:245 from . import rich_utils246 247 rich_utils.rich_abort_error()248 else:119 unmodified lines368 extra.append(_("required"))369 if extra:370 extra_str = "; ".join(extra)371 extra_str = f"[{extra_str}]"373- if rich is not None:372+ if HAS_RICH:373 # This is needed for when we want to export to HTML374 from . import rich_utils375 376 extra_str = rich_utils.escape_before_html_export(extra_str)207 unmodified lines584 585 if extra:586 extra_str = "; ".join(extra)587 extra_str = f"[{extra_str}]"589- if rich is not None:588+ if HAS_RICH:589 # This is needed for when we want to export to HTML590 from . import rich_utils591 592 extra_str = rich_utils.escape_before_html_export(extra_str)134 unmodified lines727 **extra,728 )729 730 def format_help(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:732- if not rich or self.rich_markup_mode is None:731+ if not HAS_RICH or self.rich_markup_mode is None:732 return super().format_help(ctx, formatter)733 from . import rich_utils734 735 return rich_utils.rich_format_help(56 unmodified lines792 **extra,793 )794 795 def format_help(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:797- if not rich or self.rich_markup_mode is None:796+ if not HAS_RICH or self.rich_markup_mode is None:797 return super().format_help(ctx, formatter)798 from . import rich_utils799 800 return rich_utils.rich_format_help(10 unmodified linesmodified:typer/main.py+2 added-7 removed
19 unmodified lines20 from ._typing import get_args, get_origin, is_union21 from .completion import get_completion_inspect_parameters22 from .core import (23 DEFAULT_MARKUP_MODE,24+ HAS_RICH,25 MarkupMode,26 TyperArgument,27 TyperCommand,28 TyperGroup,20 unmodified lines49 TyperPath,50 )51 from .utils import get_params_from_function52 52-try:53- import rich54-55-except ImportError: # pragma: no cover56- rich = None # type: ignore57-53 _original_except_hook = sys.excepthook54 _typer_developer_exception_attr_name = "__typer_developer_exception__"55 56 14 unmodified lines71 typer_path = os.path.dirname(__file__)72 click_path = os.path.dirname(click.__file__)73 internal_dir_names = [typer_path, click_path]74 exc = exc_value80- if rich:75+ if HAS_RICH:76 from . import rich_utils77 78 rich_tb = rich_utils.get_traceback(exc, exception_config, internal_dir_names)79 console_stderr = rich_utils._get_rich_console(stderr=True)1052 unmodified linesmodified:pyproject.toml+13 added
162 unmodified lines163 "I", # isort164 "B", # flake8-bugbear165 "C4", # flake8-comprehensions166 "UP", # pyupgrade167+ "TID", # flake8-tidy-imports168 ]169 ignore = [170 "E501", # line too long, handled by black171 "B008", # do not perform function calls in argument defaults172 "C901", # too complex173 "W191", # indentation contains tabs174+ "TID252", # relative imports okay175 ]176 177 [tool.ruff.lint.per-file-ignores]178 # "__init__.py" = ["F401"]179+# rich_utils is allowed to use rich imports180+"typer/rich_utils.py" = ["TID251"]181 # This file is more readable without yield from182 "docs_src/progressbar/tutorial004.py" = ["UP028", "B007"]183 # Default mutable data structure184 "docs_src/options_autocompletion/tutorial006_an.py" = ["B006"]10 unmodified lines195 # Local variable `delete` is assigned to but never used196 "docs_src/prompt/tutorial003.py" = ["F841"]197 # Loop control variable `x` not used within loop body198 "docs_src/using_click/tutorial001.py" = ["B007"]199+# No need to worry about rich imports in docs200+"docs_src/*" = ["TID"]201 202 [tool.ruff.lint.isort]203 known-third-party = ["typer", "click"]204 # For docs_src/subcommands/tutorial003/1 unmodified line206 207 [tool.ruff.lint.pyupgrade]208 # Preserve types, even if a file imports `from __future__ import annotations`.209 keep-runtime-typing = true210+211+[tool.ruff.lint.flake8-tidy-imports]212+# Import rich_utils from within functions (lazy), not at the module level (TID253)213+banned-module-level-imports = ["typer.rich_utils"]214+215+[tool.ruff.lint.flake8-tidy-imports.banned-api]216+"rich".msg = "Use 'typer.rich_utils' instead of importing from 'rich' directly."