From 98784092c9b3f55e6919a295bcd3a0ed2d754ef4 Mon Sep 17 00:00:00 2001 From: Thor Whalen Date: Mon, 15 Jan 2024 11:43:05 +0100 Subject: [PATCH] fix: common_prefixed --- dol/kv_codecs.py | 25 +++++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/dol/kv_codecs.py b/dol/kv_codecs.py index a69f86fc..03b8e45d 100644 --- a/dol/kv_codecs.py +++ b/dol/kv_codecs.py @@ -417,15 +417,30 @@ def tuple_of_dict(keys): def _affix_encoder(string: str, prefix: str = '', suffix: str = ''): + """Affix a prefix and suffix to a string + >>> _affix_encoder('name', prefix='/folder/', suffix='.txt') + '/folder/name.txt' + """ return f'{prefix}{string}{suffix}' def _affix_decoder(string: str, prefix: str = '', suffix: str = ''): - return string[len(prefix) : -len(suffix)] + """Remove prefix and suffix from string + >>> _affix_decoder('/folder/name.txt', prefix='/folder/', suffix='.txt') + 'name' + """ + end_idx = -len(suffix) or None # if suffix is empty, end_idx should be None + return string[len(prefix) : end_idx] def affix_key_codec(prefix: str = '', suffix: str = ''): - """A factory that creates a key codec that affixes a prefix and suffix to the key""" + """A factory that creates a key codec that affixes a prefix and suffix to the key + + >>> codec = affix_key_codec(prefix='/folder/', suffix='.txt') + >>> codec.encoder('name') + '/folder/name.txt' + >>> codec.decoder('/folder/name.txt') + """ return KeyCodec( encoder=partial(_affix_encoder, prefix=prefix, suffix=suffix), decoder=partial(_affix_decoder, prefix=prefix, suffix=suffix), @@ -451,7 +466,7 @@ def common_prefixed(keys: Iterable[str]): from dol.util import max_common_prefix prefix = max_common_prefix(keys) - return KeyCodecs.prefixed(prefix, simple_str_sep='') + return KeyCodecs.prefixed(prefix) def common_prefix_keys_wrap(s: Mapping): @@ -549,7 +564,9 @@ def key_based( value codec to use.""" def extension_based( - ext_mapping: dict = dflt_ext_mapping, *, default: Optional[Callable] = None, + ext_mapping: dict = dflt_ext_mapping, + *, + default: Optional[Callable] = None, ): """A factory that creates a key-value codec that uses the file extension to determine the value codec to use."""