Coverage for src/blob_dict/dict/in_memory.py: 0%

42 statements  

« prev     ^ index     » next       coverage.py v7.8.1, created at 2025-05-23 02:51 -0700

1from collections.abc import Iterator, MutableMapping 

2from datetime import timedelta 

3from typing import Any, Literal, override 

4 

5from ttl_dict import TTLDict 

6 

7from ..blob import BytesBlob 

8from . import BlobDictBase 

9 

10 

11class InMemoryBlobDict(BlobDictBase): 

12 __EXTERNAL_DICT_TTL_ERROR_MESSAGE: str = "Cannot specify `ttl` for external `data_dict`" 

13 

14 def __init__( 

15 self, 

16 data_dict: MutableMapping[str, BytesBlob] | None = None, 

17 *, 

18 ttl: timedelta | None = None, 

19 ) -> None: 

20 super().__init__() 

21 

22 if data_dict is not None and ttl is not None: 

23 raise ValueError(InMemoryBlobDict.__EXTERNAL_DICT_TTL_ERROR_MESSAGE) 

24 

25 self.__dict: MutableMapping[str, BytesBlob] = ( 

26 ( 

27 {} if ttl is None 

28 else TTLDict[str, BytesBlob](ttl) 

29 ) if data_dict is None 

30 else data_dict 

31 ) 

32 

33 @override 

34 def __len__(self) -> int: 

35 return len(self.__dict) 

36 

37 @override 

38 def __contains__(self, key: Any) -> bool: 

39 return str(key) in self.__dict 

40 

41 @override 

42 def get[T: Any]( 

43 self, 

44 key: str, 

45 /, 

46 default: BytesBlob | T = None, 

47 ) -> BytesBlob | T: 

48 return self.__dict.get(key, default) 

49 

50 @override 

51 def __getitem__(self, key: str, /) -> BytesBlob: 

52 return self.__dict[key] 

53 

54 @override 

55 def __iter__(self) -> Iterator[str]: 

56 yield from ( 

57 key for key in self.__dict 

58 ) 

59 

60 @override 

61 def clear(self) -> None: 

62 self.__dict.clear() 

63 

64 @override 

65 def pop[T: Any]( 

66 self, 

67 key: str, 

68 /, 

69 default: BytesBlob | T | Literal["__DEFAULT"] = "__DEFAULT", 

70 ) -> BytesBlob | T: 

71 if default == "__DEFAULT": 

72 return self.__dict.pop(key) 

73 

74 return self.__dict.pop(key, default) 

75 

76 @override 

77 def __delitem__(self, key: str, /) -> None: 

78 del self.__dict[key] 

79 

80 @override 

81 def __setitem__(self, key: str, blob: BytesBlob, /) -> None: 

82 self.__dict[key] = blob