diff --git a/src/zarr/core/group.py b/src/zarr/core/group.py index 7a0d2efc09..5cb42db5b4 100644 --- a/src/zarr/core/group.py +++ b/src/zarr/core/group.py @@ -1165,7 +1165,16 @@ async def create_dataset( .. deprecated:: 3.0.0 The h5py compatibility methods will be removed in 3.1.0. Use `AsyncGroup.create_array` instead. """ - return await self.create_array(name, shape=shape, **kwargs) + data = kwargs.pop("data", None) + # create_dataset in zarr 2.x requires shape but not dtype if data is + # provided. Allow this configuration by inferring dtype from data if + # necessary and passing it to create_array + if "dtype" not in kwargs and data is not None: + kwargs["dtype"] = data.dtype + array = await self.create_array(name, shape=shape, **kwargs) + if data is not None: + await array.setitem(slice(None), data) + return array @deprecated("Use AsyncGroup.require_array instead.") async def require_dataset( diff --git a/tests/test_group.py b/tests/test_group.py index a4ce04e822..19a9f9c9bb 100644 --- a/tests/test_group.py +++ b/tests/test_group.py @@ -1137,6 +1137,18 @@ async def test_require_groups(store: LocalStore | MemoryStore, zarr_format: Zarr assert no_group == () +def test_create_dataset_with_data(store: Store, zarr_format: ZarrFormat) -> None: + """Check that deprecated create_dataset method allows input data. + + See https://github.com/zarr-developers/zarr-python/issues/2631. + """ + root = Group.from_store(store=store, zarr_format=zarr_format) + arr = np.random.random((5, 5)) + with pytest.warns(DeprecationWarning): + data = root.create_dataset("random", data=arr, shape=arr.shape) + np.testing.assert_array_equal(np.asarray(data), arr) + + async def test_create_dataset(store: Store, zarr_format: ZarrFormat) -> None: root = await AsyncGroup.from_store(store=store, zarr_format=zarr_format) with pytest.warns(DeprecationWarning):