Repository: Project-MONAI/MONAI
File: monai/data/grid_dataset.py (Python)

Code before:
                out_patch = self.patch_transform(patch, **apply_args)
            if self.with_coordinates and len(others) > 0:  # patch_iter to yield at least 2 items: patch, coords
                yield out_patch, others[0]
            else:
                yield out_patch

    def __iter__(self):
        if self.cache:
            cache_index = None
            for image in super().__iter__():
                key = self.hash_func(image)
                if key in self._hash_keys:
                    # if existing in cache, try to get the index in cache
                    cache_index = self._hash_keys.index(key)
                if cache_index is None:
                    # no cache for this index, execute all the transforms directly
                    yield from self._generate_patches(self.patch_iter(image))

                if self._cache is None:
                    raise RuntimeError("Cache buffer is not initialized, please call `set_data()` before epoch begins.")
                data = self._cache[cache_index]  # type: ignore
                other = self._cache_other[cache_index]  # type: ignore

                # load data from cache and execute from the first random transform
                data = deepcopy(data) if self.copy_cache else data
                yield from self._generate_patches(zip(data, other), start=self.first_random)
        else:
            for image in super().__iter__():
                yield from self._generate_patches(self.patch_iter(image))


class PatchDataset(IterableDataset):
    """
    returns a patch from an image dataset.
    The patches are generated by a user-specified callable `patch_func`,
    and are optionally post-processed by `transform`.
    For example, to generate random patch samples from an image dataset:

    .. code-block:: python

        import numpy as np

        from monai.data import PatchDataset, DataLoader
        from monai.transforms import RandSpatialCropSamples, RandShiftIntensity

        # image dataset
        images = [np.arange(16, dtype=float).reshape(1, 4, 4),
                  np.arange(16, dtype=float).reshape(1, 4, 4)]
        # image patch sampler
        n_samples = 5
        sampler = RandSpatialCropSamples(roi_size=(3, 3), num_samples=n_samples,

Review comment (performance):
```suggestion
                else:
                    if self._cache is None:
                        raise RuntimeError("Cache buffer is not initialized, please call `set_data()` before epoch begins.")
                    data = self._cache[cache_index]  # type: ignore
                    other = self._cache_other[cache_index]  # type: ignore

                    # load data from cache and execute from the first random transform
                    data = deepcopy(data) if self.copy_cache else data
                    yield from self._generate_patches(zip(data, other), start=self.first_random)
```

I think you don't want to execute the rest of the code in this block so need an `else`?

Code after:
            if self.with_coordinates and len(others) > 0:  # patch_iter to yield at least 2 items: patch, coords
                other_cache.append(others[0])
            patch_cache.append(patch)
        return patch_cache, other_cache

    def _generate_patches(self, src, **apply_args):
        """
        yield patches optionally post-processed by transform.

        Args:
            src: a iterable of image patches.
            apply_args: other args for `self.patch_transform`.

        """
        for patch, *others in src:
            out_patch = patch
            if self.patch_transform is not None:
                out_patch = self.patch_transform(patch, **apply_args)
            if self.with_coordinates and len(others) > 0:  # patch_iter to yield at least 2 items: patch, coords
                yield out_patch, others[0]
            else:
                yield out_patch

    def __iter__(self):
        if self.cache:
            cache_index = None
            for image in super().__iter__():
                key = self.hash_func(image)
                if key in self._hash_keys:
                    # if existing in cache, try to get the index in cache
                    cache_index = self._hash_keys.index(key)
                if cache_index is None:
                    # no cache for this index, execute all the transforms directly
                    yield from self._generate_patches(self.patch_iter(image))
                else:
                    if self._cache is None:
                        raise RuntimeError(
                            "Cache buffer is not initialized, please call `set_data()` before epoch begins."
                        )
                    data = self._cache[cache_index]  # type: ignore
                    other = self._cache_other[cache_index]  # type: ignore

                    # load data from cache and execute from the first random transform
                    data = deepcopy(data) if self.copy_cache else data
                    yield from self._generate_patches(zip(data, other), start=self.first_random)
        else:
            for image in super().__iter__():
                yield from self._generate_patches(self.patch_iter(image))


class PatchDataset(IterableDataset):