more match + less asserts

This commit is contained in:
AF 2022-12-02 12:55:53 +00:00
parent 0e55f88adb
commit 2aac64f65c

View File

@ -6,9 +6,10 @@ import os
import pathlib
import threading
import warnings
from collections.abc import Hashable
from functools import wraps
from io import StringIO, UnsupportedOperation
from typing import IO, Any, Callable, Hashable, TypeVar
from typing import IO, Any, Callable, TypeVar
__all__ = (
'KVFactory',
@ -140,16 +141,15 @@ class KVJson(KVFactory):
def _load_key(self, key: Any, /) -> Hashable:
"""note: unstable signature."""
if isinstance(key, Hashable):
match key:
case Hashable():
return key
elif isinstance(key, list):
case list():
return tuple(map(self._load_key, key))
elif isinstance(key, dict):
case dict():
return tuple((self._load_key(k), self._load_key(v)) for k, v in key.items())
else:
raise TypeError(
'unknown KVJson key type, cannot convert to hashable'
)
case _:
raise TypeError('unknown KVJson key type, cannot convert to hashable')
def fromline(self, line: str, /) -> tuple[Any, Any]:
d = json.loads(line)
@ -207,7 +207,8 @@ def nightly(decorated: TDecoratedNightly = None, prefix: str = '', stacklevel=2)
decorated.__init_subclass__, prefix, stacklevel=3
)
return decorated # type: ignore
assert callable(decorated)
if not callable(decorated):
raise TypeError
message = f"{prefix}{decorated.__name__}"
@ -470,12 +471,13 @@ class DbConnection(VirtualConnection):
await self._reload()
async def _handle_request(self, request: Request, /) -> None:
if isinstance(request, LineRequest):
match request:
case LineRequest():
await self._write(request.line, request)
elif isinstance(request, CommitRequest):
case CommitRequest():
await self._commit_buffer()
request.set_result(None)
else:
case _:
raise UnknownRequestType
async def _background_cycle(self, /) -> None:
@ -588,7 +590,8 @@ intended for heavy tasks."""
self._start_task()
async def _initialize(self, /) -> None:
assert self.__not_running
if not self.__not_running:
raise RuntimeError
self.__not_running = False
await self._initialize_running()
@ -604,7 +607,8 @@ note: unstable signature."""
await self._commit_buffer()
if not self.__buffer_future.done():
self.__buffer_future.set_exception(RequestToClosedConnection())
assert isinstance(self.__buffer_future.exception(), RequestToClosedConnection)
if not isinstance(self.__buffer_future.exception(), RequestToClosedConnection):
raise RuntimeError
del self.__buffer_requested
del self.__buffer_future
del self.__buffer
@ -614,7 +618,8 @@ note: unstable signature."""
await self.__queue.join()
self.__task.cancel()
del self.__task
assert self.__queue.empty()
if not self.__queue.empty():
raise RuntimeError
del self.__queue
await self._close_buffer()
@ -971,7 +976,8 @@ class Transaction:
self.__running = False
def __enter__(self) -> TransactionView:
assert not self.__running
if self.__running:
raise RuntimeError
self.__running = True
self.__view = TransactionView({}, self.__connection)
return self.__view