Skip to content

Commit 60dcd8e

Browse files
avoid duplication and allow for formalized addition of caches (#1227)
Co-authored-by: Martin Durant <[email protected]>
1 parent 07fc4d9 commit 60dcd8e

File tree

2 files changed

+42
-10
lines changed

2 files changed

+42
-10
lines changed

fsspec/caching.py

Lines changed: 34 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -767,14 +767,39 @@ def _read_cache(self, start, end, start_block_number, end_block_number):
767767

768768

769769
caches = {
770-
"none": BaseCache,
770+
# one custom case
771771
None: BaseCache,
772-
"mmap": MMapCache,
773-
"bytes": BytesCache,
774-
"readahead": ReadAheadCache,
775-
"block": BlockCache,
776-
"first": FirstChunkCache,
777-
"all": AllBytes,
778-
"parts": KnownPartsOfAFile,
779-
"background": BackgroundBlockCache,
780772
}
773+
774+
775+
def register_cache(cls, clobber=False):
776+
"""'Register' cache implementation.
777+
778+
Parameters
779+
----------
780+
clobber: bool, optional
781+
If set to True (default is False) - allow to overwrite existing
782+
entry.
783+
784+
Raises
785+
------
786+
ValueError
787+
"""
788+
name = cls.name
789+
if not clobber and name in caches:
790+
raise ValueError(f"Cache with name {name!r} is already known: {caches[name]}")
791+
caches[name] = cls
792+
793+
794+
for c in (
795+
BaseCache,
796+
MMapCache,
797+
BytesCache,
798+
ReadAheadCache,
799+
BlockCache,
800+
FirstChunkCache,
801+
AllBytes,
802+
KnownPartsOfAFile,
803+
BackgroundBlockCache,
804+
):
805+
register_cache(c)

fsspec/tests/test_caches.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
import pytest
55

6-
from fsspec.caching import BlockCache, FirstChunkCache, caches
6+
from fsspec.caching import BlockCache, FirstChunkCache, caches, register_cache
77

88

99
def test_cache_getitem(Cache_imp):
@@ -138,3 +138,10 @@ def wrapped(*a, **kw):
138138
f.read(1)
139139
time.sleep(0.1) # second block is loading
140140
assert len(thread_ids) == 2
141+
142+
143+
def test_register_cache():
144+
# just test that we have them populated and fail to re-add again unless overload
145+
with pytest.raises(ValueError):
146+
register_cache(BlockCache)
147+
register_cache(BlockCache, clobber=True)

0 commit comments

Comments
 (0)