diff --git a/.deepsource.toml b/.deepsource.toml new file mode 100644 index 0000000000..309d06fb8d --- /dev/null +++ b/.deepsource.toml @@ -0,0 +1,22 @@ +version = 1 + +test_patterns = ["tests/**"] + +[[analyzers]] +name = "python" +enabled = true + + [analyzers.meta] + runtime_version = "3.x.x" + +[[analyzers]] +name = "test-coverage" +enabled = true + +[[analyzers]] +name = "docker" +enabled = true + +[[analyzers]] +name = "shell" +enabled = true \ No newline at end of file diff --git a/monai/apps/utils.py b/monai/apps/utils.py index c43dab2ef9..e7ad9c4534 100644 --- a/monai/apps/utils.py +++ b/monai/apps/utils.py @@ -146,7 +146,7 @@ def download_url(url: str, filepath: str, hash_val: Optional[str] = None, hash_t if has_tqdm: pbar.close() except IOError as e: - logging.debug("IO Error - %s" % e) + logging.debug("IO Error - %s", e) finally: if file_size == os.path.getsize(tmp_file_path): if hash_val and not check_hash(tmp_file_path, hash_val, hash_type): diff --git a/monai/data/dataset.py b/monai/data/dataset.py index eb0a4c9bd5..71aedc7413 100644 --- a/monai/data/dataset.py +++ b/monai/data/dataset.py @@ -807,7 +807,7 @@ def __getitem__(self, index: int): def to_list(x): return list(x) if isinstance(x, (tuple, list)) else [x] - data = list() + data = [] for dataset in self.data: data.extend(to_list(dataset[index])) if self.transform is not None: diff --git a/monai/data/decathlon_datalist.py b/monai/data/decathlon_datalist.py index 91a8e481b8..38e217f19b 100644 --- a/monai/data/decathlon_datalist.py +++ b/monai/data/decathlon_datalist.py @@ -136,7 +136,7 @@ def load_decathlon_properties( with open(data_property_file_path) as json_file: json_data = json.load(json_file) - properties = dict() + properties = {} for key in ensure_tuple(property_keys): if key not in json_data: raise KeyError(f"key {key} is not in the data property file.") diff --git a/monai/data/image_reader.py b/monai/data/image_reader.py index 6bf4dc374b..0fd784af05 100644 --- a/monai/data/image_reader.py +++ b/monai/data/image_reader.py @@ -154,7 +154,7 @@ def read(self, data: Union[Sequence[str], str], **kwargs): https://github.com/InsightSoftwareConsortium/ITK/blob/master/Wrapping/Generators/Python/itkExtras.py """ - img_: List[Image] = list() + img_: List[Image] = [] filenames: Sequence[str] = ensure_tuple(data) kwargs_ = self.kwargs.copy() @@ -191,7 +191,7 @@ def get_data(self, img): img: a ITK image object loaded from a image file or a list of ITK image objects. """ - img_array: List[np.ndarray] = list() + img_array: List[np.ndarray] = [] compatible_meta: Dict = {} for i in ensure_tuple(img): @@ -325,7 +325,7 @@ def read(self, data: Union[Sequence[str], str], **kwargs): https://github.com/nipy/nibabel/blob/master/nibabel/loadsave.py """ - img_: List[Nifti1Image] = list() + img_: List[Nifti1Image] = [] filenames: Sequence[str] = ensure_tuple(data) kwargs_ = self.kwargs.copy() @@ -348,7 +348,7 @@ def get_data(self, img): img: a Nibabel image object loaded from a image file or a list of Nibabel image objects. """ - img_array: List[np.ndarray] = list() + img_array: List[np.ndarray] = [] compatible_meta: Dict = {} for i in ensure_tuple(img): @@ -456,7 +456,7 @@ def read(self, data: Union[Sequence[str], str], **kwargs): https://numpy.org/doc/stable/reference/generated/numpy.load.html """ - img_: List[Nifti1Image] = list() + img_: List[Nifti1Image] = [] filenames: Sequence[str] = ensure_tuple(data) kwargs_ = self.kwargs.copy() @@ -485,13 +485,13 @@ def get_data(self, img): img: a Numpy array loaded from a file or a list of Numpy arrays. """ - img_array: List[np.ndarray] = list() + img_array: List[np.ndarray] = [] compatible_meta: Dict = {} if isinstance(img, np.ndarray): img = (img,) for i in ensure_tuple(img): - header = dict() + header = {} if isinstance(i, np.ndarray): header["spatial_shape"] = i.shape img_array.append(i) @@ -540,7 +540,7 @@ def read(self, data: Union[Sequence[str], str, np.ndarray], **kwargs): https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.open """ - img_: List[PILImage.Image] = list() + img_: List[PILImage.Image] = [] filenames: Sequence[str] = ensure_tuple(data) kwargs_ = self.kwargs.copy() @@ -565,7 +565,7 @@ def get_data(self, img): img: a PIL Image object loaded from a file or a list of PIL Image objects. """ - img_array: List[np.ndarray] = list() + img_array: List[np.ndarray] = [] compatible_meta: Dict = {} for i in ensure_tuple(img): diff --git a/monai/data/utils.py b/monai/data/utils.py index e23b1a467e..ca8f3b1017 100644 --- a/monai/data/utils.py +++ b/monai/data/utils.py @@ -712,7 +712,7 @@ def partition_dataset_classes( for i, c in enumerate(classes): class_indices[c].append(i) - class_partition_indices: List[Sequence] = list() + class_partition_indices: List[Sequence] = [] for _, per_class_indices in sorted(class_indices.items()): per_class_partition_indices = partition_dataset( data=per_class_indices, diff --git a/monai/engines/evaluator.py b/monai/engines/evaluator.py index 19ea37a5ee..e0ca59558e 100644 --- a/monai/engines/evaluator.py +++ b/monai/engines/evaluator.py @@ -185,8 +185,8 @@ def _iteration(self, engine: Engine, batchdata: Dict[str, torch.Tensor]) -> Dict batch = self.prepare_batch(batchdata, engine.state.device, engine.non_blocking) if len(batch) == 2: inputs, targets = batch - args: Tuple = tuple() - kwargs: Dict = dict() + args: Tuple = () + kwargs: Dict = {} else: inputs, targets, args, kwargs = batch @@ -290,8 +290,8 @@ def _iteration(self, engine: Engine, batchdata: Dict[str, torch.Tensor]) -> Dict batch = self.prepare_batch(batchdata, engine.state.device, engine.non_blocking) if len(batch) == 2: inputs, targets = batch - args: Tuple = tuple() - kwargs: Dict = dict() + args: Tuple = () + kwargs: Dict = {} else: inputs, targets, args, kwargs = batch diff --git a/monai/engines/trainer.py b/monai/engines/trainer.py index 5b48d0f8dc..5d4f82b0af 100644 --- a/monai/engines/trainer.py +++ b/monai/engines/trainer.py @@ -143,8 +143,8 @@ def _iteration(self, engine: Engine, batchdata: Dict[str, torch.Tensor]): batch = self.prepare_batch(batchdata, engine.state.device, engine.non_blocking) if len(batch) == 2: inputs, targets = batch - args: Tuple = tuple() - kwargs: Dict = dict() + args: Tuple = () + kwargs: Dict = {} else: inputs, targets, args, kwargs = batch diff --git a/monai/networks/nets/autoencoder.py b/monai/networks/nets/autoencoder.py index 27529f264e..e97502da8f 100644 --- a/monai/networks/nets/autoencoder.py +++ b/monai/networks/nets/autoencoder.py @@ -50,7 +50,7 @@ def __init__( self.norm = norm self.dropout = dropout self.num_inter_units = num_inter_units - self.inter_channels = inter_channels if inter_channels is not None else list() + self.inter_channels = inter_channels if inter_channels is not None else [] self.inter_dilations = list(inter_dilations or [1] * len(self.inter_channels)) # The number of channels and strides should match diff --git a/monai/optimizers/utils.py b/monai/optimizers/utils.py index 76fdfad670..9c4bfcf6ee 100644 --- a/monai/optimizers/utils.py +++ b/monai/optimizers/utils.py @@ -75,8 +75,8 @@ def _filter(): return _filter - params = list() - _layers = list() + params = [] + _layers = [] for func, ty, lr in zip(layer_matches, match_types, lr_values): if ty.lower() == "select": layer_params = _get_select(func) diff --git a/monai/transforms/adaptors.py b/monai/transforms/adaptors.py index 5bf2bf038b..434d1f1c05 100644 --- a/monai/transforms/adaptors.py +++ b/monai/transforms/adaptors.py @@ -196,7 +196,7 @@ def _inner(ditems): if len(ret) != len(outputs): raise ValueError("'outputs' must have the same length as the number of elements that were returned") - ret = {k: v for k, v in zip(op, ret)} + ret = dict(zip(op, ret)) else: must_be_types("outputs", op, (str, list, tuple)) if isinstance(op, (list, tuple)): diff --git a/monai/transforms/croppad/array.py b/monai/transforms/croppad/array.py index 667324d09d..9dace83c4d 100644 --- a/monai/transforms/croppad/array.py +++ b/monai/transforms/croppad/array.py @@ -74,7 +74,7 @@ def __init__( def _determine_data_pad_width(self, data_shape: Sequence[int]) -> List[Tuple[int, int]]: self.spatial_size = fall_back_tuple(self.spatial_size, data_shape) if self.method == Method.SYMMETRIC: - pad_width = list() + pad_width = [] for i in range(len(self.spatial_size)): width = max(self.spatial_size[i] - data_shape[i], 0) pad_width.append((width // 2, width - (width // 2))) @@ -601,7 +601,7 @@ def __call__( else: fg_indices, bg_indices = map_binary_to_indices(label, image, self.image_threshold) self.randomize(label, fg_indices, bg_indices, image) - results: List[np.ndarray] = list() + results: List[np.ndarray] = [] if self.centers is not None: for center in self.centers: cropper = SpatialCrop(roi_center=tuple(center), roi_size=self.spatial_size) @@ -680,7 +680,7 @@ def __call__(self, img: np.ndarray) -> np.ndarray: """ See also: :py:class:`monai.transforms.utils.generate_spatial_bounding_box`. """ - bbox = list() + bbox = [] for channel in range(img.shape[0]): start_, end_ = generate_spatial_bounding_box(img, select_fn=self.select_fn, channel_indices=channel) diff --git a/monai/transforms/croppad/dictionary.py b/monai/transforms/croppad/dictionary.py index df87c659ac..ad224e5c33 100644 --- a/monai/transforms/croppad/dictionary.py +++ b/monai/transforms/croppad/dictionary.py @@ -462,7 +462,7 @@ def __call__(self, data: Mapping[Hashable, np.ndarray]) -> List[Dict[Hashable, n self.randomize(d[self.w_key]) _spatial_size = fall_back_tuple(self.spatial_size, d[self.w_key].shape[1:]) - results: List[Dict[Hashable, np.ndarray]] = [dict() for _ in range(self.num_samples)] + results: List[Dict[Hashable, np.ndarray]] = [{} for _ in range(self.num_samples)] for key in data.keys(): if key in self.keys: img = d[key] @@ -575,7 +575,7 @@ def __call__(self, data: Mapping[Hashable, np.ndarray]) -> List[Dict[Hashable, n self.randomize(label, fg_indices, bg_indices, image) assert isinstance(self.spatial_size, tuple) assert self.centers is not None - results: List[Dict[Hashable, np.ndarray]] = [dict() for _ in range(self.num_samples)] + results: List[Dict[Hashable, np.ndarray]] = [{} for _ in range(self.num_samples)] for key in data.keys(): if key in self.keys: img = d[key] diff --git a/monai/transforms/io/array.py b/monai/transforms/io/array.py index 2f9f0b2814..f1b92025a7 100644 --- a/monai/transforms/io/array.py +++ b/monai/transforms/io/array.py @@ -171,8 +171,8 @@ def __call__(self, filename: Union[Sequence[Union[Path, str]], Path, str]): filename: path file or file-like object or a list of files. """ filename = ensure_tuple(filename) - img_array = list() - compatible_meta: Dict = dict() + img_array = [] + compatible_meta: Dict = {} for name in filename: img = nib.load(name) img = correct_nifti_header_if_necessary(img) @@ -240,7 +240,7 @@ def __call__(self, filename: Union[Sequence[Union[Path, str]], Path, str]): filename: path file or file-like object or a list of files. """ filename = ensure_tuple(filename) - img_array = list() + img_array = [] compatible_meta = None for name in filename: img = Image.open(name) @@ -252,7 +252,7 @@ def __call__(self, filename: Union[Sequence[Union[Path, str]], Path, str]): if self.image_only: continue - meta = dict() + meta = {} meta["filename_or_obj"] = name meta["spatial_shape"] = data.shape[:2] meta["format"] = img.format @@ -314,13 +314,13 @@ def __call__(self, filename: Union[Sequence[Union[Path, str]], Path, str]): if name.endswith(".npz"): raise ValueError("Cannot load a sequence of npz files.") filename = ensure_tuple(filename) - data_array: List = list() + data_array: List = [] compatible_meta = None def _save_data_meta(data_array, name, data, compatible_meta): data_array.append(data if self.dtype is None else data.astype(self.dtype)) if not self.data_only: - meta = dict() + meta = {} meta["filename_or_obj"] = name meta["spatial_shape"] = data.shape if not compatible_meta: diff --git a/monai/transforms/spatial/array.py b/monai/transforms/spatial/array.py index 813abe878e..40a9a878ad 100644 --- a/monai/transforms/spatial/array.py +++ b/monai/transforms/spatial/array.py @@ -299,7 +299,7 @@ def __call__(self, img: np.ndarray) -> np.ndarray: Args: img: channel first array, must have shape: (num_channels, H[, W, ..., ]), """ - flipped = list() + flipped = [] for channel in img: flipped.append(np.flip(channel, self.spatial_axis)) return np.stack(flipped).astype(img.dtype) @@ -584,7 +584,7 @@ def __call__(self, img: np.ndarray) -> np.ndarray: Args: img: channel first array, must have shape: (num_channels, H[, W, ..., ]), """ - rotated = list() + rotated = [] for channel in img: rotated.append(np.rot90(channel, self.k, self.spatial_axes)) return np.stack(rotated).astype(img.dtype) diff --git a/monai/transforms/utility/array.py b/monai/transforms/utility/array.py index 79b39b6825..bbb78fb7bb 100644 --- a/monai/transforms/utility/array.py +++ b/monai/transforms/utility/array.py @@ -189,7 +189,7 @@ def __call__(self, img: Union[np.ndarray, torch.Tensor]) -> List[Union[np.ndarra if n_classes <= 1: raise RuntimeError("input image does not contain multiple channels.") - outputs = list() + outputs = [] slices = [slice(None)] * len(img.shape) for i in range(n_classes): slices[channel_dim] = slice(i, i + 1) diff --git a/monai/transforms/utility/dictionary.py b/monai/transforms/utility/dictionary.py index 8e373329ab..21c30f6010 100644 --- a/monai/transforms/utility/dictionary.py +++ b/monai/transforms/utility/dictionary.py @@ -535,7 +535,7 @@ def __call__(self, data): """ d = dict(data) - output = list() + output = [] data_type = None for key in self.keys: if data_type is None: @@ -674,7 +674,7 @@ class ConvertToMultiChannelBasedOnBratsClassesd(MapTransform): def __call__(self, data: Mapping[Hashable, np.ndarray]) -> Dict[Hashable, np.ndarray]: d = dict(data) for key in self.keys: - result = list() + result = [] # merge labels 1 (tumor non-enh) and 4 (tumor enh) to TC result.append(np.logical_or(d[key] == 1, d[key] == 4)) # merge labels 1 (tumor non-enh) and 4 (tumor enh) and 2 (large edema) to WT diff --git a/monai/utils/misc.py b/monai/utils/misc.py index 09a1306217..2b4d078ad7 100644 --- a/monai/utils/misc.py +++ b/monai/utils/misc.py @@ -265,7 +265,7 @@ def _parse_var(s): value = items[1].strip(" \n\r\t'") return key, value - d = dict() + d = {} if items: for item in items: key, value = _parse_var(item) diff --git a/tests/runner.py b/tests/runner.py index 70ddc45b1f..b5d1de5fc1 100644 --- a/tests/runner.py +++ b/tests/runner.py @@ -18,7 +18,7 @@ from monai.utils import PerfContext -results: dict = dict() +results: dict = {} class TimeLoggingTestResult(unittest.TextTestResult): @@ -26,7 +26,7 @@ class TimeLoggingTestResult(unittest.TextTestResult): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) - self.timed_tests = dict() + self.timed_tests = {} def startTest(self, test): # noqa: N802 """Start timer, print test name, do normal test.""" diff --git a/tests/test_compute_confusion_matrix.py b/tests/test_compute_confusion_matrix.py index ca6b09ff36..56ca5371ab 100644 --- a/tests/test_compute_confusion_matrix.py +++ b/tests/test_compute_confusion_matrix.py @@ -220,7 +220,7 @@ def test_value(self, input_data, expected_value): @parameterized.expand(TEST_CASES_COMPUTE_SAMPLE) def test_compute_sample(self, input_data, expected_value): params = input_data.copy() - vals = dict() + vals = {} vals["y_pred"] = params.pop("y_pred") vals["y"] = params.pop("y") metric = ConfusionMatrixMetric(**params) @@ -230,7 +230,7 @@ def test_compute_sample(self, input_data, expected_value): @parameterized.expand(TEST_CASES_COMPUTE_SAMPLE_MULTI_METRICS) def test_compute_sample_multiple_metrics(self, input_data, expected_values): params = input_data.copy() - vals = dict() + vals = {} vals["y_pred"] = params.pop("y_pred") vals["y"] = params.pop("y") metric = ConfusionMatrixMetric(**params) @@ -243,7 +243,7 @@ def test_compute_sample_multiple_metrics(self, input_data, expected_values): @parameterized.expand(TEST_CASES_COMPUTE_SAMPLE_NAN) def test_compute_sample_with_nan(self, input_data, expected_value, expected_not_nans): params = input_data.copy() - vals = dict() + vals = {} vals["y_pred"] = params.pop("y_pred") vals["y"] = params.pop("y") metric = ConfusionMatrixMetric(**params) @@ -254,7 +254,7 @@ def test_compute_sample_with_nan(self, input_data, expected_value, expected_not_ @parameterized.expand([TEST_CASES_CLF]) def test_clf_with_nan(self, input_data, expected_value): params = input_data.copy() - vals = dict() + vals = {} vals["y_pred"] = params.pop("y_pred") vals["y"] = params.pop("y") metric = ConfusionMatrixMetric(**params) diff --git a/tests/test_compute_meandice.py b/tests/test_compute_meandice.py index dab86bc288..64f38dcdb8 100644 --- a/tests/test_compute_meandice.py +++ b/tests/test_compute_meandice.py @@ -184,7 +184,7 @@ def test_nans(self, input_data, expected_value): def test_value_class(self, input_data, expected_value): # same test as for compute_meandice - vals = dict() + vals = {} vals["y_pred"] = input_data.pop("y_pred") vals["y"] = input_data.pop("y") dice_metric = DiceMetric(**input_data, reduction="none") diff --git a/tests/test_delete_itemsd.py b/tests/test_delete_itemsd.py index ad35e804df..7426e39ff0 100644 --- a/tests/test_delete_itemsd.py +++ b/tests/test_delete_itemsd.py @@ -23,7 +23,7 @@ class TestDeleteItemsd(unittest.TestCase): @parameterized.expand([TEST_CASE_1]) def test_memory(self, input_param, expected_key_size): - input_data = dict() + input_data = {} for i in range(50): input_data[str(i)] = [time.time()] * 100000 result = DeleteItemsd(**input_param)(input_data) diff --git a/tests/test_flip.py b/tests/test_flip.py index 5d1a456ece..7a2af02585 100644 --- a/tests/test_flip.py +++ b/tests/test_flip.py @@ -32,7 +32,7 @@ def test_invalid_inputs(self, _, spatial_axis, raises): @parameterized.expand(VALID_CASES) def test_correct_results(self, _, spatial_axis): flip = Flip(spatial_axis=spatial_axis) - expected = list() + expected = [] for channel in self.imt[0]: expected.append(np.flip(channel, spatial_axis)) expected = np.stack(expected) diff --git a/tests/test_flipd.py b/tests/test_flipd.py index 410f9d0743..b8996dee42 100644 --- a/tests/test_flipd.py +++ b/tests/test_flipd.py @@ -32,7 +32,7 @@ def test_invalid_cases(self, _, spatial_axis, raises): @parameterized.expand(VALID_CASES) def test_correct_results(self, _, spatial_axis): flip = Flipd(keys="img", spatial_axis=spatial_axis) - expected = list() + expected = [] for channel in self.imt[0]: expected.append(np.flip(channel, spatial_axis)) expected = np.stack(expected) diff --git a/tests/test_hilbert_transform.py b/tests/test_hilbert_transform.py index 99f027f083..82454c34d0 100644 --- a/tests/test_hilbert_transform.py +++ b/tests/test_hilbert_transform.py @@ -51,7 +51,7 @@ def create_expected_numpy_output(input_datum, **kwargs): # CPU TEST DATA -cpu_input_data = dict() +cpu_input_data = {} cpu_input_data["1D"] = torch.as_tensor(hann_windowed_sine, device=cpu).unsqueeze(0).unsqueeze(0) cpu_input_data["2D"] = ( torch.as_tensor(np.stack([hann_windowed_sine] * 10, axis=1), device=cpu).unsqueeze(0).unsqueeze(0) @@ -110,7 +110,7 @@ def create_expected_numpy_output(input_datum, **kwargs): if torch.cuda.is_available(): gpu = torch.device("cuda") - gpu_input_data = dict() + gpu_input_data = {} gpu_input_data["1D"] = torch.as_tensor(hann_windowed_sine, device=gpu).unsqueeze(0).unsqueeze(0) gpu_input_data["2D"] = ( torch.as_tensor(np.stack([hann_windowed_sine] * 10, axis=1), device=gpu).unsqueeze(0).unsqueeze(0) diff --git a/tests/test_identityd.py b/tests/test_identityd.py index 684469bf3b..8796f28da8 100644 --- a/tests/test_identityd.py +++ b/tests/test_identityd.py @@ -18,7 +18,7 @@ class TestIdentityd(NumpyImageTestCase2D): def test_identityd(self): img = self.imt - data = dict() + data = {} data["img"] = img identity = Identityd(keys=data.keys()) self.assertEqual(data, identity(data)) diff --git a/tests/test_integration_classification_2d.py b/tests/test_integration_classification_2d.py index 3e7387c405..4be59cba41 100644 --- a/tests/test_integration_classification_2d.py +++ b/tests/test_integration_classification_2d.py @@ -80,8 +80,8 @@ def run_training_test(root_dir, train_x, train_y, val_x, val_y, device="cuda:0", # start training validation best_metric = -1 best_metric_epoch = -1 - epoch_loss_values = list() - metric_values = list() + epoch_loss_values = [] + metric_values = [] model_filename = os.path.join(root_dir, "best_metric_model.pth") for epoch in range(epoch_num): print("-" * 10) @@ -137,8 +137,8 @@ def run_inference_test(root_dir, test_x, test_y, device="cuda:0", num_workers=10 model_filename = os.path.join(root_dir, "best_metric_model.pth") model.load_state_dict(torch.load(model_filename)) - y_true = list() - y_pred = list() + y_true = [] + y_pred = [] with eval_mode(model): for test_data in val_loader: test_images, test_labels = test_data[0].to(device), test_data[1].to(device) diff --git a/tests/test_integration_segmentation_3d.py b/tests/test_integration_segmentation_3d.py index 4d0128142f..af97236eda 100644 --- a/tests/test_integration_segmentation_3d.py +++ b/tests/test_integration_segmentation_3d.py @@ -112,8 +112,8 @@ def run_training_test(root_dir, device="cuda:0", cachedataset=0): # start a typical PyTorch training val_interval = 2 best_metric, best_metric_epoch = -1, -1 - epoch_loss_values = list() - metric_values = list() + epoch_loss_values = [] + metric_values = [] writer = SummaryWriter(log_dir=os.path.join(root_dir, "runs")) model_filename = os.path.join(root_dir, "best_metric_model.pth") for epoch in range(6): diff --git a/tests/test_iterable_dataset.py b/tests/test_iterable_dataset.py index aed0694ae3..7b16eaf594 100644 --- a/tests/test_iterable_dataset.py +++ b/tests/test_iterable_dataset.py @@ -32,7 +32,7 @@ class TestIterableDataset(unittest.TestCase): def test_shape(self): expected_shape = (128, 128, 128) test_image = nib.Nifti1Image(np.random.randint(0, 2, size=[128, 128, 128]), np.eye(4)) - test_data = list() + test_data = [] with tempfile.TemporaryDirectory() as tempdir: for i in range(6): nib.save(test_image, os.path.join(tempdir, f"test_image{str(i)}.nii.gz")) diff --git a/tests/test_lambdad.py b/tests/test_lambdad.py index c67a9346a0..8f7e6b1133 100644 --- a/tests/test_lambdad.py +++ b/tests/test_lambdad.py @@ -20,7 +20,7 @@ class TestLambdad(NumpyImageTestCase2D): def test_lambdad_identity(self): img = self.imt - data = dict() + data = {} data["img"] = img def identity_func(x): @@ -33,14 +33,14 @@ def identity_func(x): def test_lambdad_slicing(self): img = self.imt - data = dict() + data = {} data["img"] = img def slice_func(x): return x[:, :, :6, ::-2] lambd = Lambdad(keys=data.keys(), func=slice_func) - expected = dict() + expected = {} expected["img"] = slice_func(data["img"]) self.assertTrue(np.allclose(expected["img"], lambd(data)["img"])) diff --git a/tests/test_load_imaged.py b/tests/test_load_imaged.py index ab5d609056..978c3b6551 100644 --- a/tests/test_load_imaged.py +++ b/tests/test_load_imaged.py @@ -32,7 +32,7 @@ class TestLoadImaged(unittest.TestCase): @parameterized.expand([TEST_CASE_1, TEST_CASE_2]) def test_shape(self, input_param, expected_shape): test_image = nib.Nifti1Image(np.random.rand(128, 128, 128), np.eye(4)) - test_data = dict() + test_data = {} with tempfile.TemporaryDirectory() as tempdir: for key in KEYS: nib.save(test_image, os.path.join(tempdir, key + ".nii.gz")) diff --git a/tests/test_load_niftid.py b/tests/test_load_niftid.py index 8b981d1101..b29b4f221c 100644 --- a/tests/test_load_niftid.py +++ b/tests/test_load_niftid.py @@ -28,7 +28,7 @@ class TestLoadNiftid(unittest.TestCase): @parameterized.expand([TEST_CASE_1]) def test_shape(self, input_param, expected_shape): test_image = nib.Nifti1Image(np.random.randint(0, 2, size=[128, 128, 128]), np.eye(4)) - test_data = dict() + test_data = {} with tempfile.TemporaryDirectory() as tempdir: for key in KEYS: nib.save(test_image, os.path.join(tempdir, key + ".nii.gz")) diff --git a/tests/test_load_pngd.py b/tests/test_load_pngd.py index dc78f92a31..1b84dab983 100644 --- a/tests/test_load_pngd.py +++ b/tests/test_load_pngd.py @@ -29,7 +29,7 @@ class TestLoadPNGd(unittest.TestCase): def test_shape(self, input_param, expected_shape): test_image = np.random.randint(0, 256, size=[128, 128, 3]) with tempfile.TemporaryDirectory() as tempdir: - test_data = dict() + test_data = {} for key in KEYS: Image.fromarray(test_image.astype("uint8")).save(os.path.join(tempdir, key + ".png")) test_data.update({key: os.path.join(tempdir, key + ".png")}) diff --git a/tests/test_map_transform.py b/tests/test_map_transform.py index 8bf9b28a79..803e699a7d 100644 --- a/tests/test_map_transform.py +++ b/tests/test_map_transform.py @@ -17,7 +17,7 @@ TEST_CASES = [["item", ("item",)], [None, (None,)], [["item1", "item2"], ("item1", "item2")]] -TEST_ILL_CASES = [[ValueError, list()], [ValueError, tuple()], [TypeError, [list()]]] +TEST_ILL_CASES = [[ValueError, []], [ValueError, ()], [TypeError, [[]]]] class MapTest(MapTransform): diff --git a/tests/test_rand_flip.py b/tests/test_rand_flip.py index dbd9b0287b..b7a019136c 100644 --- a/tests/test_rand_flip.py +++ b/tests/test_rand_flip.py @@ -32,7 +32,7 @@ def test_invalid_inputs(self, _, spatial_axis, raises): @parameterized.expand(VALID_CASES) def test_correct_results(self, _, spatial_axis): flip = RandFlip(prob=1.0, spatial_axis=spatial_axis) - expected = list() + expected = [] for channel in self.imt[0]: expected.append(np.flip(channel, spatial_axis)) expected = np.stack(expected) diff --git a/tests/test_rand_flipd.py b/tests/test_rand_flipd.py index 4577396771..7bbd15f04c 100644 --- a/tests/test_rand_flipd.py +++ b/tests/test_rand_flipd.py @@ -25,7 +25,7 @@ class TestRandFlipd(NumpyImageTestCase2D): def test_correct_results(self, _, spatial_axis): flip = RandFlipd(keys="img", prob=1.0, spatial_axis=spatial_axis) res = flip({"img": self.imt[0]}) - expected = list() + expected = [] for channel in self.imt[0]: expected.append(np.flip(channel, spatial_axis)) expected = np.stack(expected) diff --git a/tests/test_rand_rotate90.py b/tests/test_rand_rotate90.py index 80c8ef885f..50a1b28e53 100644 --- a/tests/test_rand_rotate90.py +++ b/tests/test_rand_rotate90.py @@ -22,7 +22,7 @@ def test_default(self): rotate = RandRotate90() rotate.set_random_state(123) rotated = rotate(self.imt[0]) - expected = list() + expected = [] for channel in self.imt[0]: expected.append(np.rot90(channel, 0, (0, 1))) expected = np.stack(expected) @@ -32,7 +32,7 @@ def test_k(self): rotate = RandRotate90(max_k=2) rotate.set_random_state(234) rotated = rotate(self.imt[0]) - expected = list() + expected = [] for channel in self.imt[0]: expected.append(np.rot90(channel, 0, (0, 1))) expected = np.stack(expected) @@ -42,7 +42,7 @@ def test_spatial_axes(self): rotate = RandRotate90(spatial_axes=(0, 1)) rotate.set_random_state(234) rotated = rotate(self.imt[0]) - expected = list() + expected = [] for channel in self.imt[0]: expected.append(np.rot90(channel, 0, (0, 1))) expected = np.stack(expected) @@ -52,7 +52,7 @@ def test_prob_k_spatial_axes(self): rotate = RandRotate90(prob=1.0, max_k=2, spatial_axes=(0, 1)) rotate.set_random_state(234) rotated = rotate(self.imt[0]) - expected = list() + expected = [] for channel in self.imt[0]: expected.append(np.rot90(channel, 1, (0, 1))) expected = np.stack(expected) diff --git a/tests/test_rand_rotate90d.py b/tests/test_rand_rotate90d.py index 6dfee43edd..48b3ef3586 100644 --- a/tests/test_rand_rotate90d.py +++ b/tests/test_rand_rotate90d.py @@ -23,7 +23,7 @@ def test_default(self): rotate = RandRotate90d(keys=key) rotate.set_random_state(123) rotated = rotate({key: self.imt[0]}) - expected = list() + expected = [] for channel in self.imt[0]: expected.append(np.rot90(channel, 0, (0, 1))) expected = np.stack(expected) @@ -34,7 +34,7 @@ def test_k(self): rotate = RandRotate90d(keys=key, max_k=2) rotate.set_random_state(234) rotated = rotate({key: self.imt[0]}) - expected = list() + expected = [] for channel in self.imt[0]: expected.append(np.rot90(channel, 0, (0, 1))) expected = np.stack(expected) @@ -45,7 +45,7 @@ def test_spatial_axes(self): rotate = RandRotate90d(keys=key, spatial_axes=(0, 1)) rotate.set_random_state(234) rotated = rotate({key: self.imt[0]}) - expected = list() + expected = [] for channel in self.imt[0]: expected.append(np.rot90(channel, 0, (0, 1))) expected = np.stack(expected) @@ -56,7 +56,7 @@ def test_prob_k_spatial_axes(self): rotate = RandRotate90d(keys=key, prob=1.0, max_k=2, spatial_axes=(0, 1)) rotate.set_random_state(234) rotated = rotate({key: self.imt[0]}) - expected = list() + expected = [] for channel in self.imt[0]: expected.append(np.rot90(channel, 1, (0, 1))) expected = np.stack(expected) diff --git a/tests/test_rand_zoom.py b/tests/test_rand_zoom.py index beb0326f01..35cf30bcb1 100644 --- a/tests/test_rand_zoom.py +++ b/tests/test_rand_zoom.py @@ -34,7 +34,7 @@ def test_correct_results(self, min_zoom, max_zoom, mode, keep_size): ) random_zoom.set_random_state(1234) zoomed = random_zoom(self.imt[0]) - expected = list() + expected = [] for channel in self.imt[0]: expected.append(zoom_scipy(channel, zoom=random_zoom._zoom, mode="nearest", order=0, prefilter=False)) expected = np.stack(expected).astype(np.float32) diff --git a/tests/test_rand_zoomd.py b/tests/test_rand_zoomd.py index 21e827e876..fd50c490d5 100644 --- a/tests/test_rand_zoomd.py +++ b/tests/test_rand_zoomd.py @@ -37,7 +37,7 @@ def test_correct_results(self, min_zoom, max_zoom, mode, align_corners, keep_siz random_zoom.set_random_state(1234) zoomed = random_zoom({key: self.imt[0]}) - expected = list() + expected = [] for channel in self.imt[0]: expected.append(zoom_scipy(channel, zoom=random_zoom._zoom, mode="nearest", order=0, prefilter=False)) expected = np.stack(expected).astype(np.float32) diff --git a/tests/test_resize.py b/tests/test_resize.py index dcf0d89292..22a68bcf85 100644 --- a/tests/test_resize.py +++ b/tests/test_resize.py @@ -39,7 +39,7 @@ def test_correct_results(self, spatial_size, mode): _order = 1 if spatial_size == (32, -1): spatial_size = (32, 64) - expected = list() + expected = [] for channel in self.imt[0]: expected.append( skimage.transform.resize( diff --git a/tests/test_resized.py b/tests/test_resized.py index 71e34ff5a8..d89c866af3 100644 --- a/tests/test_resized.py +++ b/tests/test_resized.py @@ -37,7 +37,7 @@ def test_correct_results(self, spatial_size, mode): _order = 1 if spatial_size == (32, -1): spatial_size = (32, 64) - expected = list() + expected = [] for channel in self.imt[0]: expected.append( skimage.transform.resize( diff --git a/tests/test_rotate.py b/tests/test_rotate.py index af603cadb3..6e43ab90e7 100644 --- a/tests/test_rotate.py +++ b/tests/test_rotate.py @@ -56,7 +56,7 @@ def test_correct_results(self, angle, keep_size, mode, padding_mode, align_corne else: _mode = "constant" - expected = list() + expected = [] for channel in self.imt[0]: expected.append( scipy.ndimage.rotate( @@ -88,7 +88,7 @@ def test_correct_results(self, angle, keep_size, mode, padding_mode, align_corne else: _mode = "constant" - expected = list() + expected = [] for channel in self.imt[0]: expected.append( scipy.ndimage.rotate( diff --git a/tests/test_rotate90.py b/tests/test_rotate90.py index b80404b0b6..a8b4e3f57c 100644 --- a/tests/test_rotate90.py +++ b/tests/test_rotate90.py @@ -21,7 +21,7 @@ class TestRotate90(NumpyImageTestCase2D): def test_rotate90_default(self): rotate = Rotate90() rotated = rotate(self.imt[0]) - expected = list() + expected = [] for channel in self.imt[0]: expected.append(np.rot90(channel, 1, (0, 1))) expected = np.stack(expected) @@ -30,7 +30,7 @@ def test_rotate90_default(self): def test_k(self): rotate = Rotate90(k=2) rotated = rotate(self.imt[0]) - expected = list() + expected = [] for channel in self.imt[0]: expected.append(np.rot90(channel, 2, (0, 1))) expected = np.stack(expected) @@ -39,7 +39,7 @@ def test_k(self): def test_spatial_axes(self): rotate = Rotate90(spatial_axes=(0, 1)) rotated = rotate(self.imt[0]) - expected = list() + expected = [] for channel in self.imt[0]: expected.append(np.rot90(channel, 1, (0, 1))) expected = np.stack(expected) @@ -48,7 +48,7 @@ def test_spatial_axes(self): def test_prob_k_spatial_axes(self): rotate = Rotate90(k=2, spatial_axes=(0, 1)) rotated = rotate(self.imt[0]) - expected = list() + expected = [] for channel in self.imt[0]: expected.append(np.rot90(channel, 2, (0, 1))) expected = np.stack(expected) diff --git a/tests/test_rotate90d.py b/tests/test_rotate90d.py index fde212b073..3d71ead82a 100644 --- a/tests/test_rotate90d.py +++ b/tests/test_rotate90d.py @@ -22,7 +22,7 @@ def test_rotate90_default(self): key = "test" rotate = Rotate90d(keys=key) rotated = rotate({key: self.imt[0]}) - expected = list() + expected = [] for channel in self.imt[0]: expected.append(np.rot90(channel, 1, (0, 1))) expected = np.stack(expected) @@ -32,7 +32,7 @@ def test_k(self): key = None rotate = Rotate90d(keys=key, k=2) rotated = rotate({key: self.imt[0]}) - expected = list() + expected = [] for channel in self.imt[0]: expected.append(np.rot90(channel, 2, (0, 1))) expected = np.stack(expected) @@ -42,7 +42,7 @@ def test_spatial_axes(self): key = "test" rotate = Rotate90d(keys=key, spatial_axes=(0, 1)) rotated = rotate({key: self.imt[0]}) - expected = list() + expected = [] for channel in self.imt[0]: expected.append(np.rot90(channel, 1, (0, 1))) expected = np.stack(expected) @@ -52,7 +52,7 @@ def test_prob_k_spatial_axes(self): key = "test" rotate = Rotate90d(keys=key, k=2, spatial_axes=(0, 1)) rotated = rotate({key: self.imt[0]}) - expected = list() + expected = [] for channel in self.imt[0]: expected.append(np.rot90(channel, 2, (0, 1))) expected = np.stack(expected) diff --git a/tests/test_scale_intensity_range_percentilesd.py b/tests/test_scale_intensity_range_percentilesd.py index 3269d1f6fa..5057c1e32c 100644 --- a/tests/test_scale_intensity_range_percentilesd.py +++ b/tests/test_scale_intensity_range_percentilesd.py @@ -20,7 +20,7 @@ class TestScaleIntensityRangePercentilesd(NumpyImageTestCase2D): def test_scaling(self): img = self.imt - data = dict() + data = {} data["img"] = img lower = 10 upper = 99 @@ -38,7 +38,7 @@ def test_scaling(self): def test_relative_scaling(self): img = self.imt - data = dict() + data = {} data["img"] = img lower = 10 upper = 99 diff --git a/tests/test_select_itemsd.py b/tests/test_select_itemsd.py index ab03777e90..bf63864eb0 100644 --- a/tests/test_select_itemsd.py +++ b/tests/test_select_itemsd.py @@ -23,7 +23,7 @@ class TestSelectItemsd(unittest.TestCase): @parameterized.expand([TEST_CASE_1]) def test_memory(self, input_param, expected_key_size): - input_data = dict() + input_data = {} for i in range(50): input_data[str(i)] = [time.time()] * 100000 result = SelectItemsd(**input_param)(input_data) diff --git a/tests/test_zoom.py b/tests/test_zoom.py index 0639c6ca9b..dcc401f16c 100644 --- a/tests/test_zoom.py +++ b/tests/test_zoom.py @@ -31,7 +31,7 @@ def test_correct_results(self, zoom, mode): _order = 0 if mode.endswith("linear"): _order = 1 - expected = list() + expected = [] for channel in self.imt[0]: expected.append(zoom_scipy(channel, zoom=zoom, mode="nearest", order=_order, prefilter=False)) expected = np.stack(expected).astype(np.float32) diff --git a/tests/test_zoomd.py b/tests/test_zoomd.py index ead302a0c9..b17ecd1bf0 100644 --- a/tests/test_zoomd.py +++ b/tests/test_zoomd.py @@ -37,7 +37,7 @@ def test_correct_results(self, zoom, mode, keep_size): _order = 0 if mode.endswith("linear"): _order = 1 - expected = list() + expected = [] for channel in self.imt[0]: expected.append(zoom_scipy(channel, zoom=zoom, mode="nearest", order=_order, prefilter=False)) expected = np.stack(expected).astype(np.float32)