aldict 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
aldict/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .alias_dict import AliasDict as AliasDict
2
+ from .exception import AliasError as AliasError
3
+ from .exception import AliasValueError as AliasValueError
aldict/alias_dict.py ADDED
@@ -0,0 +1,92 @@
1
+ from collections import UserDict, defaultdict
2
+
3
+ from aldict.exception import AliasError, AliasValueError
4
+
5
+
6
+ class AliasDict(UserDict):
7
+ """Custom Dict class supporting key-aliases pointing to shared values"""
8
+
9
+ def __init__(self, dict_):
10
+ self._alias_dict = {}
11
+ super().__init__(self, **dict_)
12
+
13
+ def add_alias(self, key, *aliases):
14
+ if key not in self.data.keys():
15
+ raise KeyError(key)
16
+ for alias in aliases:
17
+ if alias == key:
18
+ raise AliasValueError(f"Key and corresponding alias cannot be equal: '{key}'")
19
+ self._alias_dict[alias] = key
20
+
21
+ def remove_alias(self, *aliases):
22
+ for alias in aliases:
23
+ try:
24
+ self._alias_dict.__delitem__(alias)
25
+ except KeyError as e:
26
+ raise AliasError(alias) from e
27
+
28
+ def clear_aliases(self):
29
+ self._alias_dict.clear()
30
+
31
+ def aliases(self):
32
+ return self._alias_dict.keys()
33
+
34
+ def aliased_keys(self):
35
+ result = defaultdict(list)
36
+ for alias, key in self._alias_dict.items():
37
+ result[key].append(alias)
38
+ return result.items()
39
+
40
+ def origin_keys(self):
41
+ return self.data.keys()
42
+
43
+ def keys(self):
44
+ return dict(**self.data, **self._alias_dict).keys()
45
+
46
+ def values(self):
47
+ return self.data.values()
48
+
49
+ def items(self):
50
+ return dict(**self.data, **{k: self.data[v] for k, v in self._alias_dict.items()}).items()
51
+
52
+ def __missing__(self, key):
53
+ try:
54
+ return super().__getitem__(self._alias_dict[key])
55
+ except AttributeError as e:
56
+ raise KeyError(key) from e
57
+
58
+ def __setitem__(self, key, value):
59
+ try:
60
+ key = self._alias_dict[key]
61
+ except KeyError:
62
+ pass
63
+ super().__setitem__(key, value)
64
+
65
+ def __delitem__(self, key):
66
+ try:
67
+ self.data.__delitem__(key)
68
+ except KeyError:
69
+ # in case we try to delete alias e.g. via pop()
70
+ pass
71
+ self._alias_dict = {k: v for k, v in self._alias_dict.items() if v != key}
72
+
73
+ def __contains__(self, item):
74
+ return item in set(self.keys())
75
+
76
+ def __iter__(self):
77
+ for item in self.keys():
78
+ yield item
79
+
80
+ def __len__(self):
81
+ return len(self.keys())
82
+
83
+ def __repr__(self):
84
+ return f"AliasDict({self.items()})"
85
+
86
+ def __eq__(self, other):
87
+ if not isinstance(other, AliasDict):
88
+ raise TypeError(f"{other} is not an AliasDict")
89
+ return self.data == other.data and self._alias_dict == other._alias_dict
90
+
91
+ def __hash__(self):
92
+ return hash((self.data, self._alias_dict))
aldict/exception.py ADDED
@@ -0,0 +1,6 @@
1
+ class AliasError(KeyError):
2
+ pass
3
+
4
+
5
+ class AliasValueError(ValueError):
6
+ pass
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Kaloyan Ivanov
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,104 @@
1
+ Metadata-Version: 2.1
2
+ Name: aldict
3
+ Version: 1.0.0
4
+ Summary: Multi-key dictionary, supports adding and manipulating key-aliases pointing to shared values
5
+ Author-email: Kaloyan Ivanov <kaloyan.ivanov88@gmail.com>
6
+ Project-URL: repository, https://github.com/kaliv0/aldict
7
+ Keywords: multi-key dictionary,multidict,alias-dict
8
+ Requires-Python: >=3.11
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Provides-Extra: dev
12
+ Requires-Dist: pytest>=8.3.4; extra == "dev"
13
+ Requires-Dist: ruff>=0.8.3; extra == "dev"
14
+ Requires-Dist: build>=1.2.2; extra == "dev"
15
+ Requires-Dist: twine>=6.0.1; extra == "dev"
16
+
17
+ <p align="center">
18
+ <img src="https://github.com/kaliv0/aldict/blob/main/assets/alter-ego.jpg?raw=true" width="250" alt="Alter Ego">
19
+ </p>
20
+
21
+ ---
22
+ # Aldict
23
+
24
+ [![tests](https://img.shields.io/github/actions/workflow/status/kaliv0/aldict/ci.yml)](https://github.com/kaliv0/aldict/actions/workflows/ci.yml)
25
+ ![Python 3.x](https://img.shields.io/badge/python-^3.11-blue?style=flat-square&logo=Python&logoColor=white)
26
+ [![PyPI](https://img.shields.io/pypi/v/aldict.svg)](https://pypi.org/project/aldict/)
27
+ [![License](https://img.shields.io/badge/License-MIT-yellow?style=flat-square)](https://github.com/kaliv0/aldict/blob/main/LICENSE)
28
+
29
+ Multi-key dictionary, supports adding and manipulating key-aliases pointing to shared values
30
+
31
+ ---
32
+ ## How to use
33
+
34
+ - add_alias
35
+ <br>(pass <i>key</i> as first parameter and <i>alias(es)</i> as variadic params)
36
+ ```python
37
+ ad = AliasDict({"a": 1, "b": 2})
38
+ ad.add_alias("a", "aa")
39
+ ad.add_alias("b", "bb", "Bbb")
40
+ assert ad["a"] == ad["aa"] == 1
41
+ assert ad["b"] == ad["bb"] == ad["Bbb"] == 2
42
+ ```
43
+ - remove_alias
44
+ <br>(pass <i>alias(es)</i> to be removed as variadic parameters)
45
+ ```python
46
+ ad.remove_alias("aa")
47
+ ad.remove_alias("bb", "Bbb")
48
+ assert len(ad.aliases()) == 0
49
+ ```
50
+ - clear_aliases
51
+ <br>(remove all <i>aliases</i> at once)
52
+ ```python
53
+ ad.clear_aliases()
54
+ assert len(ad.aliases()) == 0
55
+ ```
56
+ - update alias
57
+ <br>(point <i>alias</i> to different <i>key</i>)
58
+ ```python
59
+ ad = AliasDict({"a": 1, "b": 2})
60
+ ad.add_alias("a", "ab")
61
+ assert list(ad.items()) == [('a', 1), ('b', 2), ('ab', 1)]
62
+
63
+ ad.add_alias("b", "ab")
64
+ assert list(ad.items()) == [('a', 1), ('b', 2), ('ab', 2)]
65
+ ```
66
+ - read all aliases
67
+ ```python
68
+ ad = AliasDict({"a": 1, "b": 2})
69
+ ad.add_alias("a", "aa")
70
+ ad.add_alias("b", "bb", "B")
71
+ ad.add_alias("a", "ab", "A")
72
+ assert list(ad.aliases()) == ['aa', 'bb', 'B', 'ab', 'A']
73
+ ```
74
+ - aliased_keys
75
+ <br>(read <i>keys</i> with corresponding <i>alias(es)</i>)
76
+ ```python
77
+ assert dict(ad.aliased_keys()) == {'a': ['aa', 'ab', 'A'], 'b': ['bb', 'B']}
78
+ ```
79
+ - read dictviews
80
+ <br>(<i>dict.keys()</i> and <i>dict.items()</i> include <i>aliased</i> versions)
81
+ ```python
82
+ ad = AliasDict({"x": 10, "y": 20})
83
+ ad.add_alias("x", "Xx")
84
+ ad.add_alias("y", "Yy", "xyz")
85
+
86
+ ad.keys()
87
+ ad.values()
88
+ ad.items()
89
+ ```
90
+ ```shell
91
+ dict_keys(['x', 'y', 'Xx', 'Yy', 'xyz'])
92
+ dict_values([10, 20])
93
+ dict_items([('x', 10), ('y', 20), ('Xx', 10), ('Yy', 20), ('xyz', 20)])
94
+ ```
95
+ - remove key and aliases
96
+ ```python
97
+ ad.pop("y")
98
+ assert list(ad.items()) == [('x', 10), ('Xx', 10)]
99
+ ```
100
+ - origin_keys
101
+ <br>(get original <i>keys</i> only)
102
+ ```python
103
+ assert list(ad.origin_keys()) == ['x', 'y']
104
+ ```
@@ -0,0 +1,8 @@
1
+ aldict/__init__.py,sha256=0l5cJ5LuzCZhZfx-IOk2dEsq6nJQTShr6oGmufIa9i4,153
2
+ aldict/alias_dict.py,sha256=OItYhSFBKCrmjHlL_2yPuwtD7G68oQ3fW31UX_e-q54,2670
3
+ aldict/exception.py,sha256=rFNmv9HuUOn2toPVYpVPQq6SOsl8nvwtJpGhPkK1puQ,83
4
+ aldict-1.0.0.dist-info/LICENSE,sha256=frOVyHZrx5o-fh5xC-kggT3MaLdp6yxV_YGpVXFHFSQ,1071
5
+ aldict-1.0.0.dist-info/METADATA,sha256=SXO3ueZ7ut4vfdbCJpWa2pvfppvakjYX5DbIUlo45j8,3152
6
+ aldict-1.0.0.dist-info/WHEEL,sha256=PZUExdf71Ui_so67QXpySuHtCi3-J3wvF4ORK6k_S8U,91
7
+ aldict-1.0.0.dist-info/top_level.txt,sha256=pXwIKxRsbW2_Lh1HM-4cG2xE44RBzMz07GaY2EONV5M,7
8
+ aldict-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (75.6.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ aldict