aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorGravatar Leon Sandøy <[email protected]>2020-05-28 00:43:58 +0200
committerGravatar Leon Sandøy <[email protected]>2020-05-28 00:44:18 +0200
commitbdb7bbc5e98bd840785def6ac08c9f5a313847cb (patch)
treefc41e55b741db161639f60d5182f14a8a121287c
parentMerge branch 'master' into redis_persistence (diff)
Reduce complexity on some of the typestring stuff.
- Refactor error messages in _to_typestring and _from_typestring to just print the prefix tuples instead of that custom error string. - Create a RedisKeyOrValue type to simplify some annotations. - Simplify partialmethod calls. - Make the signatures for _to_typestring and _from_typestring one-liners - Fix a typo in the errors.
-rw-r--r--bot/utils/redis_cache.py40
1 files changed, 9 insertions, 31 deletions
diff --git a/bot/utils/redis_cache.py b/bot/utils/redis_cache.py
index a71ad2191..0b682d378 100644
--- a/bot/utils/redis_cache.py
+++ b/bot/utils/redis_cache.py
@@ -2,7 +2,6 @@ from __future__ import annotations
import asyncio
import logging
-import typing
from functools import partialmethod
from typing import Any, Dict, ItemsView, Optional, Tuple, Union
@@ -13,6 +12,7 @@ log = logging.getLogger(__name__)
# Type aliases
RedisKeyType = Union[str, int]
RedisValueType = Union[str, int, float]
+RedisKeyOrValue = Union[RedisKeyType, RedisValueType]
# Prefix tuples
PrefixTuple = Tuple[Tuple[str, Any]]
@@ -26,20 +26,6 @@ KEY_PREFIXES = (
("s|", str),
)
-# Makes a nice list like "float, int, and str"
-VALUE_TYPE_LIST = ", ".join(str(_type.__name__) for _type in typing.get_args(RedisValueType))
-VALUE_TYPE_LIST = ", and ".join(VALUE_TYPE_LIST.rsplit(", ", 1))
-
-KEY_TYPE_LIST = ", ".join(str(_type.__name__) for _type in typing.get_args(RedisKeyType))
-KEY_TYPE_LIST = ", and ".join(KEY_TYPE_LIST.rsplit(", ", 1))
-
-# Makes a list like "'f|', 'i|', and 's|'"
-VALUE_PREFIX_LIST = ", ".join([f"'{prefix}'" for prefix, _ in VALUE_PREFIXES])
-VALUE_PREFIX_LIST = ", and ".join(VALUE_PREFIX_LIST.rsplit(", ", 1))
-
-KEY_PREFIX_LIST = ", ".join([f"'{prefix}'" for prefix, _ in KEY_PREFIXES])
-KEY_PREFIX_LIST = ", and ".join(KEY_PREFIX_LIST.rsplit(", ", 1))
-
class RedisCache:
"""
@@ -116,23 +102,15 @@ class RedisCache:
self._namespace = namespace
@staticmethod
- def _to_typestring(
- key_or_value: Union[RedisKeyType, RedisValueType],
- prefixes: PrefixTuple,
- types_string: str
- ) -> str:
+ def _to_typestring(key_or_value: RedisKeyOrValue, prefixes: PrefixTuple) -> str:
"""Turn a valid Redis type into a typestring."""
for prefix, _type in prefixes:
if isinstance(key_or_value, _type):
return f"{prefix}{key_or_value}"
- raise TypeError(f"RedisCache._from_typestring only supports the types {types_string}.")
+ raise TypeError(f"RedisCache._to_typestring only supports the following: {prefixes}.")
@staticmethod
- def _from_typestring(
- key_or_value: Union[bytes, str],
- prefixes: PrefixTuple,
- prefixes_string: str,
- ) -> Union[RedisKeyType, RedisValueType]:
+ def _from_typestring(key_or_value: Union[bytes, str], prefixes: PrefixTuple) -> RedisKeyOrValue:
"""Deserialize a typestring into a valid Redis type."""
# Stuff that comes out of Redis will be bytestrings, so let's decode those.
if isinstance(key_or_value, bytes):
@@ -142,7 +120,7 @@ class RedisCache:
for prefix, _type in prefixes:
if key_or_value.startswith(prefix):
return _type(key_or_value[len(prefix):])
- raise TypeError(f"RedisCache._to_typestring only supports the prefixes {prefixes_string}.")
+ raise TypeError(f"RedisCache._from_typestring only supports the following: {prefixes}.")
# Add some nice partials to call our generic typestring converters.
# These are basically methods that will fill in some of the parameters for you, so that
@@ -150,10 +128,10 @@ class RedisCache:
# at `prefixes` and `types_string` pre-filled.
#
# See https://docs.python.org/3/library/functools.html#functools.partialmethod
- _key_to_typestring = partialmethod(_to_typestring, prefixes=KEY_PREFIXES, types_string=KEY_TYPE_LIST)
- _value_to_typestring = partialmethod(_to_typestring, prefixes=VALUE_PREFIXES, types_string=VALUE_TYPE_LIST)
- _key_from_typestring = partialmethod(_from_typestring, prefixes=KEY_PREFIXES, prefixes_string=KEY_PREFIX_LIST)
- _value_from_typestring = partialmethod(_from_typestring, prefixes=VALUE_PREFIXES, prefixes_string=VALUE_PREFIX_LIST)
+ _key_to_typestring = partialmethod(_to_typestring, prefixes=KEY_PREFIXES)
+ _value_to_typestring = partialmethod(_to_typestring, prefixes=VALUE_PREFIXES)
+ _key_from_typestring = partialmethod(_from_typestring, prefixes=KEY_PREFIXES)
+ _value_from_typestring = partialmethod(_from_typestring, prefixes=VALUE_PREFIXES)
def _dict_from_typestring(self, dictionary: Dict) -> Dict:
"""Turns all contents of a dict into valid Redis types."""