def chunk(
        self,
        chunks: T_ChunksFreq = {},  # noqa: B006  # {} even though it's technically unsafe, is being used intentionally here (#4667)
        name_prefix: str = "xarray-",
        token: str | None = None,
        lock: bool = False,
        inline_array: bool = False,
        chunked_array_type: str | ChunkManagerEntrypoint | None = None,
        from_array_kwargs=None,
        **chunks_kwargs: T_ChunkDimFreq,
    ) -> Self:
        """Coerce all arrays in this dataset into dask arrays with the given
        chunks.

        Non-dask arrays in this dataset will be converted to dask arrays. Dask
        arrays will be rechunked to the given chunk sizes.

        If neither chunks is not provided for one or more dimensions, chunk
        sizes along that dimension will not be updated; non-dask arrays will be
        converted into dask arrays with a single block.

        Along datetime-like dimensions, a :py:class:`groupers.TimeResampler` object is also accepted.

        Parameters
        ----------
        chunks : int, tuple of int, "auto" or mapping of hashable to int or a TimeResampler, optional
            Chunk sizes along each dimension, e.g., ``5``, ``"auto"``, or
            ``{"x": 5, "y": 5}`` or ``{"x": 5, "time": TimeResampler(freq="YE")}``.
        name_prefix : str, default: "xarray-"
            Prefix for the name of any new dask arrays.
        token : str, optional
            Token uniquely identifying this dataset.
        lock : bool, default: False
            Passed on to :py:func:`dask.array.from_array`, if the array is not
            already as dask array.
        inline_array: bool, default: False
            Passed on to :py:func:`dask.array.from_array`, if the array is not
            already as dask array.
        chunked_array_type: str, optional
            Which chunked array type to coerce this datasets' arrays to.
            Defaults to 'dask' if installed, else whatever is registered via the `ChunkManagerEntryPoint` system.
            Experimental API that should not be relied upon.
        from_array_kwargs: dict, optional
            Additional keyword arguments passed on to the `ChunkManagerEntrypoint.from_array` method used to create
            chunked arrays, via whichever chunk manager is specified through the `chunked_array_type` kwarg.
            For example, with dask as the default chunked array type, this method would pass additional kwargs
            to :py:func:`dask.array.from_array`. Experimental API that should not be relied upon.
        **chunks_kwargs : {dim: chunks, ...}, optional
            The keyword arguments form of ``chunks``.
            One of chunks or chunks_kwargs must be provided

        Returns
        -------
        chunked : xarray.Dataset

        See Also
        --------
        Dataset.chunks
        Dataset.chunksizes
        xarray.unify_chunks
        dask.array.from_array
        """
        from xarray.core.dataarray import DataArray
        from xarray.groupers import TimeResampler

        if chunks is None and not chunks_kwargs:
            warnings.warn(
                "None value for 'chunks' is deprecated. "
                "It will raise an error in the future. Use instead '{}'",
                category=DeprecationWarning,
                stacklevel=2,
            )
            chunks = {}
        chunks_mapping: Mapping[Any, Any]
        if not isinstance(chunks, Mapping) and chunks is not None:
            if isinstance(chunks, tuple | list):
                utils.emit_user_level_warning(
                    "Supplying chunks as dimension-order tuples is deprecated. "
                    "It will raise an error in the future. Instead use a dict with dimensions as keys.",
                    category=DeprecationWarning,
                )
            chunks_mapping = dict.fromkeys(self.dims, chunks)
        else:
            chunks_mapping = either_dict_or_kwargs(chunks, chunks_kwargs, "chunk")

        bad_dims = chunks_mapping.keys() - self.sizes.keys()
        if bad_dims:
            raise ValueError(
                f"chunks keys {tuple(bad_dims)} not found in data dimensions {tuple(self.sizes.keys())}"
            )

        def _resolve_frequency(
            name: Hashable, resampler: TimeResampler
        ) -> tuple[int, ...]:
            variable = self._variables.get(name, None)
            if variable is None:
                raise ValueError(
                    f"Cannot chunk by resampler {resampler!r} for virtual variables."
                )
            elif not _contains_datetime_like_objects(variable):
                raise ValueError(
                    f"chunks={resampler!r} only supported for datetime variables. "
                    f"Received variable {name!r} with dtype {variable.dtype!r} instead."
                )

            assert variable.ndim == 1
            chunks = (
                DataArray(
                    np.ones(variable.shape, dtype=int),
                    dims=(name,),
                    coords={name: variable},
                )
                .resample({name: resampler})
                .sum()
            )
            # When bins (binning) or time periods are missing (resampling)
            # we can end up with NaNs. Drop them.
            if chunks.dtype.kind == "f":
                chunks = chunks.dropna(name).astype(int)
            chunks_tuple: tuple[int, ...] = tuple(chunks.data.tolist())
            return chunks_tuple

        chunks_mapping_ints: Mapping[Any, T_ChunkDim] = {
            name: (
                _resolve_frequency(name, chunks)
                if isinstance(chunks, TimeResampler)
                else chunks
            )
            for name, chunks in chunks_mapping.items()
        }

        chunkmanager = guess_chunkmanager(chunked_array_type)
        if from_array_kwargs is None:
            from_array_kwargs = {}

        variables = {
            k: _maybe_chunk(
                k,
                v,
                chunks_mapping_ints,
                token,
                lock,
                name_prefix,
                inline_array=inline_array,
                chunked_array_type=chunkmanager,
                from_array_kwargs=from_array_kwargs.copy(),
            )
            for k, v in self.variables.items()
        }
        return self._replace(variables)
Coerce all arrays in this dataset into dask arrays with the given
        chunks.

        Non-dask arrays in this dataset will be converted to dask arrays. Dask
        arrays will be rechunked to the given chunk sizes.

        If neither chunks is not provided for one or more dimensions, chunk
        sizes along that dimension will not be updated; non-dask arrays will be
        converted into dask arrays with a single block.

        Along datetime-like dimensions, a :py:class:`groupers.TimeResampler` object is also accepted.

        Parameters
        ----------
        chunks : int, tuple of int, "auto" or mapping of hashable to int or a TimeResampler, optional
            Chunk sizes along each dimension, e.g., ``5``, ``"auto"``, or
            ``{"x": 5, "y": 5}`` or ``{"x": 5, "time": TimeResampler(freq="YE")}``.
        name_prefix : str, default: "xarray-"
            Prefix for the name of any new dask arrays.
        token : str, optional
            Token uniquely identifying this dataset.
        lock : bool, default: False
            Passed on to :py:func:`dask.array.from_array`, if the array is not
            already as dask array.
        inline_array: bool, default: False
            Passed on to :py:func:`dask.array.from_array`, if the array is not
            already as dask array.
        chunked_array_type: str, optional
            Which chunked array type to coerce this datasets' arrays to.
            Defaults to 'dask' if installed, else whatever is registered via the `ChunkManagerEntryPoint` system.
            Experimental API that should not be relied upon.
        from_array_kwargs: dict, optional
            Additional keyword arguments passed on to the `ChunkManagerEntrypoint.from_array` method used to create
            chunked arrays, via whichever chunk manager is specified through the `chunked_array_type` kwarg.
            For example, with dask as the default chunked array type, this method would pass additional kwargs
            to :py:func:`dask.array.from_array`. Experimental API that should not be relied upon.
        **chunks_kwargs : {dim: chunks, ...}, optional
            The keyword arguments form of ``chunks``.
            One of chunks or chunks_kwargs must be provided

        Returns
        -------
        chunked : xarray.Dataset

        See Also
        --------
        Dataset.chunks
        Dataset.chunksizes
        xarray.unify_chunks
        dask.array.from_array
        
xarray/core/dataset.py