Skip to content

Commit 335be1a

Browse files
committed
Error on invalid store mode
1 parent a941224 commit 335be1a

File tree

2 files changed

+15
-4
lines changed

2 files changed

+15
-4
lines changed

src/zarr/storage/_common.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import json
44
from pathlib import Path
5-
from typing import TYPE_CHECKING, Any, Literal
5+
from typing import TYPE_CHECKING, Any, Literal, Self
66

77
from zarr.abc.store import ByteRequest, Store
88
from zarr.core.buffer import Buffer, default_buffer_prototype
@@ -48,9 +48,7 @@ def read_only(self) -> bool:
4848
return self.store.read_only
4949

5050
@classmethod
51-
async def open(
52-
cls, store: Store, path: str, mode: AccessModeLiteral | None = None
53-
) -> StorePath:
51+
async def open(cls, store: Store, path: str, mode: AccessModeLiteral | None = None) -> Self:
5452
"""
5553
Open StorePath based on the provided mode.
5654
@@ -67,6 +65,9 @@ async def open(
6765
------
6866
FileExistsError
6967
If the mode is 'w-' and the store path already exists.
68+
ValueError
69+
If the mode is not "r" and the store is read-only, or
70+
if the mode is "r" and the store is not read-only.
7071
"""
7172

7273
await store._ensure_open()
@@ -78,6 +79,8 @@ async def open(
7879

7980
if store.read_only and mode != "r":
8081
raise ValueError(f"Store is read-only but mode is '{mode}'")
82+
if not store.read_only and mode == "r":
83+
raise ValueError(f"Store is not read-only but mode is '{mode}'")
8184

8285
match mode:
8386
case "w-":

tests/test_store/test_core.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import pytest
55
from _pytest.compat import LEGACY_PATH
66

7+
import zarr
78
from zarr import Group
89
from zarr.core.common import AccessModeLiteral, ZarrFormat
910
from zarr.storage import FsspecStore, LocalStore, MemoryStore, StoreLike, StorePath
@@ -251,3 +252,10 @@ def test_relativize_path_invalid() -> None:
251252
msg = f"The first component of {path} does not start with {prefix}."
252253
with pytest.raises(ValueError, match=msg):
253254
_relativize_path(path="a/b/c", prefix="b")
255+
256+
257+
def test_invalid_open_mode() -> None:
258+
store = MemoryStore()
259+
zarr.create((100,), store=store, zarr_format=2, path="a")
260+
with pytest.raises(ValueError, match="Store is not read-only but mode is 'r'"):
261+
zarr.open_array(store=store, path="a", zarr_format=2, mode="r")

0 commit comments

Comments
 (0)