Skip to content

Commit 1800fee

Browse files
Put ModuleNotFoundError instead of RuntimeError in proper places (#2750)
* Replaced RuntimeError with ModuleNotFoundError * Remove DS_Stores * Replace RuntimeError with ModuleNotFound in proper places * Fix tests * Add test for clearml and a little refactor * Revert changes for two ipynbs * Revert changes to two ipynbs
1 parent 6c7bd54 commit 1800fee

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

49 files changed

+106
-148
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ wheels/
2222
.installed.cfg
2323
*.egg
2424
MANIFEST
25+
**/.DS_Store
2526

2627
# Unit test / coverage reports
2728
htmlcov/

examples/gan/dcgan.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
import torchvision.utils as vutils
2121

2222
except ImportError:
23-
raise ImportError(
23+
raise ModuleNotFoundError(
2424
"Please install torchvision to run this example, for example "
2525
"via conda by running 'conda install -c pytorch torchvision'. "
2626
)

examples/mnist/mnist_save_resume_engine.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
try:
2323
from torch.utils.tensorboard import SummaryWriter
2424
except ImportError:
25-
raise RuntimeError(
25+
raise ModuleNotFoundError(
2626
"This module requires either tensorboardX or torch >= 1.2.0. "
2727
"You may install tensorboardX with command: \n pip install tensorboardX \n"
2828
"or upgrade PyTorch using your package manager of choice (pip or conda)."

examples/mnist/mnist_with_tensorboard.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@
3434
try:
3535
from torch.utils.tensorboard import SummaryWriter
3636
except ImportError:
37-
raise RuntimeError(
37+
raise ModuleNotFoundError(
3838
"This module requires either tensorboardX or torch >= 1.2.0. "
3939
"You may install tensorboardX with command: \n pip install tensorboardX \n"
4040
"or upgrade PyTorch using your package manager of choice (pip or conda)."

examples/mnist/mnist_with_tensorboard_on_tpu.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@
3131
try:
3232
import torch_xla.core.xla_model as xm
3333
except ImportError:
34-
raise RuntimeError(
34+
raise ModuleNotFoundError(
3535
"In order to run PyTorch on TPU we need to install PyTorch XLA:"
3636
"\n\t- curl https://raw.githubusercontent.com/pytorch/xla/master/contrib/scripts/env-setup.py -o xla-setup.py"
3737
"\n\t- python xla-setup.py --version 1.5"

examples/mnist/mnist_with_visdom.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
try:
1616
import visdom
1717
except ImportError:
18-
raise RuntimeError("No visdom package is found. Please install it with command: \n pip install visdom")
18+
raise ModuleNotFoundError("No visdom package is found. Please install it with command: \n pip install visdom")
1919

2020

2121
class Net(nn.Module):

examples/references/classification/imagenet/code/dataflow/vis.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,9 @@
66
try:
77
from image_dataset_viz import render_datapoint
88
except ImportError:
9-
raise RuntimeError("Install it via pip install --upgrade git+https://github.com/vfdev-5/ImageDatasetViz.git")
9+
raise ModuleNotFoundError(
10+
"Please install image-dataset-viz via pip install --upgrade git+https://github.com/vfdev-5/ImageDatasetViz.git"
11+
)
1012

1113

1214
def tensor_to_numpy(t: torch.Tensor) -> np.ndarray:

examples/references/segmentation/pascal_voc2012/vis.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,9 @@
55
try:
66
from image_dataset_viz import render_datapoint
77
except ImportError:
8-
raise RuntimeError("Install it via pip install --upgrade git+https://github.com/vfdev-5/ImageDatasetViz.git")
8+
raise ModuleNotFoundError(
9+
"Please install image-dataset-viz via pip install --upgrade git+https://github.com/vfdev-5/ImageDatasetViz.git"
10+
)
911

1012

1113
def _getvocpallete(num_cls):

examples/reinforcement_learning/actor_critic.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
try:
1414
import gym
1515
except ImportError:
16-
raise RuntimeError("Please install opengym: pip install gym")
16+
raise ModuleNotFoundError("Please install opengym: pip install gym")
1717

1818

1919
SavedAction = namedtuple("SavedAction", ["log_prob", "value"])

examples/reinforcement_learning/reinforce.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
try:
1313
import gym
1414
except ImportError:
15-
raise RuntimeError("Please install opengym: pip install gym")
15+
raise ModuleNotFoundError("Please install opengym: pip install gym")
1616

1717

1818
class Policy(nn.Module):

ignite/contrib/handlers/clearml_logger.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ def __init__(self, **kwargs: Any):
115115
from clearml import Task
116116
from clearml.binding.frameworks.tensorflow_bind import WeightsGradientHistHelper
117117
except ImportError:
118-
raise RuntimeError(
118+
raise ModuleNotFoundError(
119119
"This contrib module requires clearml to be installed. "
120120
"You may install clearml using: \n pip install clearml \n"
121121
)
@@ -842,7 +842,7 @@ def _setup_check_clearml(self, logger: ClearMLLogger, output_uri: str) -> None:
842842
# Backwards-compatibility for legacy Trains SDK
843843
from trains import Task
844844
except ImportError:
845-
raise RuntimeError(
845+
raise ModuleNotFoundError(
846846
"This contrib module requires clearml to be installed. "
847847
"You may install clearml using: \n pip install clearml \n"
848848
)
@@ -917,7 +917,7 @@ def __call__(self, checkpoint: Mapping, filename: str, metadata: Optional[Mappin
917917
# Backwards-compatibility for legacy Trains SDK
918918
from trains.binding.frameworks import WeightsFileHandler
919919
except ImportError:
920-
raise RuntimeError(
920+
raise ModuleNotFoundError(
921921
"This contrib module requires clearml to be installed. "
922922
"You may install clearml using: \n pip install clearml \n"
923923
)

ignite/contrib/handlers/mlflow_logger.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ def __init__(self, tracking_uri: Optional[str] = None):
8888
try:
8989
import mlflow
9090
except ImportError:
91-
raise RuntimeError(
91+
raise ModuleNotFoundError(
9292
"This contrib module requires mlflow to be installed. "
9393
"Please install it with command: \n pip install mlflow"
9494
)

ignite/contrib/handlers/neptune_logger.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -180,7 +180,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None:
180180
try:
181181
import neptune
182182
except ImportError:
183-
raise RuntimeError(
183+
raise ModuleNotFoundError(
184184
"This contrib module requires neptune-client to be installed. "
185185
"You may install neptune with command: \n pip install neptune-client \n"
186186
)

ignite/contrib/handlers/polyaxon_logger.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ def __init__(self, *args: Any, **kwargs: Any):
104104

105105
self.experiment = Experiment(*args, **kwargs)
106106
except ImportError:
107-
raise RuntimeError(
107+
raise ModuleNotFoundError(
108108
"This contrib module requires polyaxon to be installed.\n"
109109
"For Polyaxon v1.x please install it with command: \n pip install polyaxon\n"
110110
"For Polyaxon v0.x please install it with command: \n pip install polyaxon-client"

ignite/contrib/handlers/tensorboard_logger.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,7 @@ def __init__(self, *args: Any, **kwargs: Any):
152152
try:
153153
from torch.utils.tensorboard import SummaryWriter # type: ignore[no-redef]
154154
except ImportError:
155-
raise RuntimeError(
155+
raise ModuleNotFoundError(
156156
"This contrib module requires either tensorboardX or torch >= 1.2.0. "
157157
"You may install tensorboardX with command: \n pip install tensorboardX \n"
158158
"or upgrade PyTorch using your package manager of choice (pip or conda)."

ignite/contrib/handlers/tqdm_logger.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,7 @@ def __init__(
126126
try:
127127
from tqdm.autonotebook import tqdm
128128
except ImportError:
129-
raise RuntimeError(
129+
raise ModuleNotFoundError(
130130
"This contrib module requires tqdm to be installed. "
131131
"Please install it with command: \n pip install tqdm"
132132
)

ignite/contrib/handlers/visdom_logger.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,7 @@ def __init__(
150150
try:
151151
import visdom
152152
except ImportError:
153-
raise RuntimeError(
153+
raise ModuleNotFoundError(
154154
"This contrib module requires visdom package. "
155155
"Please install it with command:\n"
156156
"pip install git+https://github.com/fossasia/visdom.git"
@@ -163,7 +163,7 @@ def __init__(
163163
try:
164164
from concurrent.futures import ThreadPoolExecutor
165165
except ImportError:
166-
raise RuntimeError(
166+
raise ModuleNotFoundError(
167167
"This contrib module requires concurrent.futures module"
168168
"Please install it with command:\n"
169169
"pip install futures"

ignite/contrib/handlers/wandb_logger.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@ def __init__(self, *args: Any, **kwargs: Any):
127127

128128
self._wandb = wandb
129129
except ImportError:
130-
raise RuntimeError(
130+
raise ModuleNotFoundError(
131131
"This contrib module requires wandb to be installed. "
132132
"You man install wandb with the command:\n pip install wandb\n"
133133
)

ignite/contrib/metrics/average_precision.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ def __init__(
7272
try:
7373
from sklearn.metrics import average_precision_score # noqa: F401
7474
except ImportError:
75-
raise RuntimeError("This contrib module requires sklearn to be installed.")
75+
raise ModuleNotFoundError("This contrib module requires scikit-learn to be installed.")
7676

7777
super(AveragePrecision, self).__init__(
7878
average_precision_compute_fn,

ignite/contrib/metrics/cohen_kappa.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ def __init__(
5959
try:
6060
from sklearn.metrics import cohen_kappa_score # noqa: F401
6161
except ImportError:
62-
raise RuntimeError("This contrib module requires sklearn to be installed.")
62+
raise ModuleNotFoundError("This contrib module requires scikit-learn to be installed.")
6363
if weights not in (None, "linear", "quadratic"):
6464
raise ValueError("Kappa Weighting type must be None or linear or quadratic.")
6565

ignite/contrib/metrics/gpu_info.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ def __init__(self) -> None:
3737
try:
3838
from pynvml.smi import nvidia_smi
3939
except ImportError:
40-
raise RuntimeError(
40+
raise ModuleNotFoundError(
4141
"This contrib module requires pynvml to be installed. "
4242
"Please install it with command: \n pip install pynvml"
4343
)

ignite/contrib/metrics/precision_recall_curve.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ def precision_recall_curve_compute_fn(y_preds: torch.Tensor, y_targets: torch.Te
1111
try:
1212
from sklearn.metrics import precision_recall_curve
1313
except ImportError:
14-
raise RuntimeError("This contrib module requires sklearn to be installed.")
14+
raise ModuleNotFoundError("This contrib module requires scikit-learn to be installed.")
1515

1616
y_true = y_targets.cpu().numpy()
1717
y_pred = y_preds.cpu().numpy()

ignite/contrib/metrics/roc_auc.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ def __init__(
8181
try:
8282
from sklearn.metrics import roc_auc_score # noqa: F401
8383
except ImportError:
84-
raise RuntimeError("This contrib module requires sklearn to be installed.")
84+
raise ModuleNotFoundError("This contrib module requires scikit-learn to be installed.")
8585

8686
super(ROC_AUC, self).__init__(
8787
roc_auc_compute_fn, output_transform=output_transform, check_compute_fn=check_compute_fn, device=device
@@ -144,7 +144,7 @@ def __init__(self, output_transform: Callable = lambda x: x, check_compute_fn: b
144144
try:
145145
from sklearn.metrics import roc_curve # noqa: F401
146146
except ImportError:
147-
raise RuntimeError("This contrib module requires sklearn to be installed.")
147+
raise ModuleNotFoundError("This contrib module requires scikit-learn to be installed.")
148148

149149
super(RocCurve, self).__init__(
150150
roc_auc_curve_compute_fn, output_transform=output_transform, check_compute_fn=check_compute_fn

ignite/handlers/lr_finder.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -259,7 +259,7 @@ def plot(
259259
try:
260260
from matplotlib import pyplot as plt
261261
except ImportError:
262-
raise RuntimeError(
262+
raise ModuleNotFoundError(
263263
"This method requires matplotlib to be installed. "
264264
"Please install it with command: \n pip install matplotlib"
265265
)

ignite/handlers/param_scheduler.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,7 @@ def plot_values(cls, num_events: int, **scheduler_kwargs: Mapping) -> Any:
132132
try:
133133
import matplotlib.pyplot as plt
134134
except ImportError:
135-
raise RuntimeError(
135+
raise ModuleNotFoundError(
136136
"This method requires matplotlib to be installed. "
137137
"Please install it with command: \n pip install matplotlib"
138138
)

ignite/handlers/time_profilers.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -295,7 +295,7 @@ def write_results(self, output_path: str) -> None:
295295
try:
296296
import pandas as pd
297297
except ImportError:
298-
raise RuntimeError("Need pandas to write results as files")
298+
raise ModuleNotFoundError("Need pandas to write results as files")
299299

300300
iters_per_epoch = self.total_num_iters // self.max_epochs
301301

@@ -663,7 +663,7 @@ def write_results(self, output_path: str) -> None:
663663
try:
664664
import pandas as pd
665665
except ImportError:
666-
raise RuntimeError("Need pandas to write results as files")
666+
raise ModuleNotFoundError("Need pandas to write results as files")
667667

668668
processing_stats = torch.tensor(self.processing_times, dtype=torch.float32)
669669
dataflow_stats = torch.tensor(self.dataflow_times, dtype=torch.float32)

ignite/metrics/gan/fid.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -25,12 +25,12 @@ def fid_score(
2525
try:
2626
import numpy as np
2727
except ImportError:
28-
raise RuntimeError("fid_score requires numpy to be installed.")
28+
raise ModuleNotFoundError("fid_score requires numpy to be installed.")
2929

3030
try:
3131
import scipy.linalg
3232
except ImportError:
33-
raise RuntimeError("fid_score requires scipy to be installed.")
33+
raise ModuleNotFoundError("fid_score requires scipy to be installed.")
3434

3535
mu1, mu2 = mu1.cpu(), mu2.cpu()
3636
sigma1, sigma2 = sigma1.cpu(), sigma2.cpu()
@@ -175,12 +175,12 @@ def __init__(
175175
try:
176176
import numpy as np # noqa: F401
177177
except ImportError:
178-
raise RuntimeError("This module requires numpy to be installed.")
178+
raise ModuleNotFoundError("This module requires numpy to be installed.")
179179

180180
try:
181181
import scipy # noqa: F401
182182
except ImportError:
183-
raise RuntimeError("This module requires scipy to be installed.")
183+
raise ModuleNotFoundError("This module requires scipy to be installed.")
184184

185185
if num_features is None and feature_extractor is None:
186186
num_features = 1000

ignite/metrics/gan/utils.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ def __init__(self, return_features: bool, device: Union[str, torch.device] = "cp
2222
import torchvision
2323
from torchvision import models
2424
except ImportError:
25-
raise RuntimeError("This module requires torchvision to be installed.")
25+
raise ModuleNotFoundError("This module requires torchvision to be installed.")
2626
super(InceptionModel, self).__init__()
2727
self._device = device
2828
if Version(torchvision.__version__) < Version("0.13.0"):

tests/ignite/contrib/conftest.py

+19
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,25 @@
44
import pytest
55

66

7+
@pytest.fixture
8+
def no_site_packages(request):
9+
import sys
10+
11+
modules = {}
12+
for k in sys.modules:
13+
if request.param in k:
14+
modules[k] = sys.modules[k]
15+
for k in modules:
16+
del sys.modules[k]
17+
18+
prev_path = list(sys.path)
19+
sys.path = [p for p in sys.path if "site-packages" not in p]
20+
yield "no_site_packages"
21+
sys.path = prev_path
22+
for k in modules:
23+
sys.modules[k] = modules[k]
24+
25+
726
@pytest.fixture()
827
def visdom_offline_logfile(dirname):
928

tests/ignite/contrib/handlers/test_clearml_logger.py

+18-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import math
22
import os
33
from collections import defaultdict
4-
from unittest.mock import ANY, call, MagicMock, Mock
4+
from unittest.mock import ANY, call, MagicMock, Mock, patch
55

66
import clearml
77
import pytest
@@ -26,6 +26,23 @@
2626
from ignite.handlers import Checkpoint
2727

2828

29+
def test_no_clearml():
30+
with patch.dict("sys.modules", {"clearml": None, "trains": None}):
31+
with pytest.raises(ModuleNotFoundError, match=r"This contrib module requires clearml to be installed."):
32+
ClearMLSaver()
33+
34+
with pytest.raises(ModuleNotFoundError, match=r"This contrib module requires clearml to be installed."):
35+
ClearMLLogger()
36+
37+
with patch.dict("sys.modules", {"clearml.binding.frameworks.tensorflow_bind": None}):
38+
with pytest.raises(ModuleNotFoundError, match=r"This contrib module requires clearml to be installed."):
39+
ClearMLLogger()
40+
41+
with patch.dict("sys.modules", {"clearml.binding.frameworks": None, "trains.binding.frameworks": None}):
42+
with pytest.raises(ModuleNotFoundError, match=r"This contrib module requires clearml to be installed."):
43+
ClearMLSaver.__call__(None, {}, "")
44+
45+
2946
def test_optimizer_params_handler_wrong_setup():
3047

3148
with pytest.raises(TypeError):

0 commit comments

Comments
 (0)