Loading...
Loading...
Refactor module-level imports of heavy native dependencies (torch, tensorflow, jax) to function-internal lazy imports. Use when a library import triggers SIGSEGV or slow startup in environments where the native dep cannot fully initialize (e.g., CUDA driver absent, triton C-extension segfault, missing GPU). Predicts test-side effects from removed module attributes.
npx skill4agent add nextaltair/altairs-agent-dev-kit lazy-import-refactorimport torchimport tensorflowimport <library>import <ML ライブラリ>find src -name "*.py" | while read f; do
awk -v fn="$f" '/^(import torch|from torch|import torchvision|from torchvision|import tensorflow|from tensorflow)/{print fn":"NR":"$0}' "$f"
donefind tests -name "*.py" | while read f; do
awk -v fn="$f" '/@patch.*\.(torch|tensorflow|jax)|patch\.object.*\.(torch|tensorflow|jax)/{print fn":"NR":"$0}' "$f"
donemodule.torch@patch("path.to.module.torch")# Before (module-level)
import torch
class Foo:
def bar(self, x: torch.Tensor) -> torch.Tensor:
with torch.no_grad():
...
# After (TYPE_CHECKING + function-internal)
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
import torch
class Foo:
def bar(self, x: torch.Tensor) -> torch.Tensor:
import torch # lazy load
with torch.no_grad():
...from __future__ import annotationsimport torchimport torch# Before
@patch("your_package.core.heavy_deps.torch")
def test_foo(mock_torch):
...
# After
def test_foo(monkeypatch):
import sys
from unittest.mock import MagicMock
mock_torch = MagicMock()
monkeypatch.setitem(sys.modules, "torch", mock_torch)
...rules/testing.md-m unitcd <package-path>
uv run pytest -m "not downloads_and_runs_model and not calls_real_webapi"gh pr createhook_pre_pr_submodule_check.pyCI-EQUIV-TESTEDfrom transformers.models.clip import CLIPProcessorimport torchcast(<heavy_lib>.Type, ...)isinstance(x, <heavy_lib>.Type)from __future__ import annotationsimportimport <lib>; assert 'torch' not in sys.modules-m unitstandard