Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature (v0.2.0): enhance KeyError message + implement fromkeys #10

Merged
merged 8 commits into from Feb 2, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions .coveragerc
Expand Up @@ -15,6 +15,7 @@ exclude_lines =
@(abc\.)?abstractmethod
if TYPE_CHECKING
if sys\.version_info
@overload

fail_under = 95

Expand Down
28 changes: 15 additions & 13 deletions README.md
Expand Up @@ -24,22 +24,24 @@ Install and update using [pip](https://pypi.org/project/case-insensitive-diction
$ pip install -U case-insensitive-dictionary
```

## API Reference

| Method | Description |
| :------------------------ | :-------------------------------------------------------------------------------------------------------------------------------------------------- |
| clear() | Removes all elements from the dictionary. |
| copy() | Returns a copy of the dictionary. |
| get(key, default) | Returns the value (case-insensitively), of the item specified with the key.<br>Falls back to the default value if the specified key does not exist. |
| fromkeys(iterable, value) | Returns a dictionary with the specified keys and the specified value. |
| keys() | Returns the dictionary's keys. |
| values() | Returns the dictionary's values. |
| items() | Returns the key-value pairs. |
| pop(key) | Remove the specified item (case-insensitively).<br>The value of the removed item is the return value. |
| popitem() | Remove the last item that was inserted into the dictionary.<br>For Python version <3.7, popitem() removes a random item. |

## Example

CaseInsensitiveDict:

```py
>>> from case_insensitive_dict import CaseInsensitiveDict

>>> case_insensitive_dict = CaseInsensitiveDict[str, str](data={"Aa": "b"})
>>> case_insensitive_dict.get("aa")
'b'
>>> case_insensitive_dict.get("Aa")
'b'
```

also supports generic keys:

```py
>>> from typing import Union

Expand All @@ -53,7 +55,7 @@ also supports generic keys:

```

and json encoding/decoding:
which also supports json encoding/decoding:

```py
>>> import json
Expand Down
4 changes: 2 additions & 2 deletions pyproject.toml
@@ -1,7 +1,7 @@
[tool.poetry]
name = "case-insensitive-dictionary"
version = "0.1.3"
description = "Case Insensitive Dictionary"
version = "0.2.0"
description = "Typed Python Case Insensitive Dictionary"
authors = ["rikhilrai"]
license = "MIT"
readme = "README.md"
Expand Down
2 changes: 1 addition & 1 deletion src/case_insensitive_dict/__init__.py
Expand Up @@ -8,7 +8,7 @@
from importlib_metadata import PackageNotFoundError # type: ignore[no-redef,misc]

try:
__version__: str = version(__name__)
__version__: str = version('case-insensitive-dictionary')
except PackageNotFoundError:
__version__ = "unknown"

Expand Down
24 changes: 21 additions & 3 deletions src/case_insensitive_dict/case_insensitive_dict.py
Expand Up @@ -6,11 +6,14 @@
from typing import Any
from typing import Dict
from typing import Generic
from typing import Iterable
from typing import Iterator
from typing import Mapping
from typing import Optional
from typing import Tuple
from typing import TypeVar
from typing import Union
from typing import overload

KT = TypeVar('KT') # pylint: disable=invalid-name
VT = TypeVar('VT') # pylint: disable=invalid-name
Expand All @@ -23,13 +26,24 @@


class CaseInsensitiveDict(MutableMapping, Generic[KT, VT]):
@overload
def __init__(self, data: Optional[Mapping[KT, VT]] = None) -> None:
...

@overload
def __init__(self, data: Optional[Iterable[Tuple[KT, VT]]] = None) -> None:
...

def __init__(self, data: Optional[Union[Mapping[KT, VT], Iterable[Tuple[KT, VT]]]] = None) -> None:
# Mapping from lowercased key to tuple of (actual key, value)
self._data: Dict[KT, Tuple[KT, VT]] = {}
if data is None:
data = {}
self.update(data)

def __repr__(self) -> str:
return f'{self.__class__.__name__}({dict(self.items())!r})'

@staticmethod
def _convert_key(key: KT) -> KT:
if isinstance(key, str):
Expand All @@ -40,7 +54,10 @@ def __setitem__(self, key: KT, value: VT) -> None:
self._data[self._convert_key(key=key)] = (key, value)

def __getitem__(self, key: KT) -> VT:
return self._data[self._convert_key(key=key)][1]
try:
return self._data[self._convert_key(key=key)][1]
except KeyError:
raise KeyError(f"Key: {key!r} not found.") from None

def __delitem__(self, key: KT) -> None:
del self._data[self._convert_key(key=key)]
Expand All @@ -63,8 +80,9 @@ def __eq__(self, other: Any) -> bool:
def copy(self) -> CaseInsensitiveDict[KT, VT]:
return CaseInsensitiveDict(data=dict(self._data.values()))

def __repr__(self) -> str:
return f'{self.__class__.__name__}({dict(self.items())!r})'
@classmethod
def fromkeys(cls, iterable: Iterable[KT], value: VT) -> CaseInsensitiveDict[KT, VT]:
return cls([(key, value) for key in iterable])


class CaseInsensitiveDictJSONEncoder(JSONEncoder):
Expand Down