Skip to content

Commit 40ad894

Browse files
matthiasdienercorenting
authored andcommitted
add explicit items()/keys()/values() methods
1 parent b205f6e commit 40ad894

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

immutabledict/__init__.py

+10-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from __future__ import annotations
22

33
from collections import OrderedDict
4-
from typing import Any, Dict, Iterable, Iterator, Mapping, Optional, Type, TypeVar
4+
from typing import Any, Dict, ItemsView, Iterable, Iterator, Mapping, Optional, Type, TypeVar, ValuesView, KeysView
55

66
__version__ = "3.0.0"
77

@@ -73,6 +73,15 @@ def __ror__(self, other: Any) -> Dict[Any, Any]:
7373
def __ior__(self, other: Any) -> immutabledict[_K, _V]:
7474
raise TypeError(f"'{self.__class__.__name__}' object is not mutable")
7575

76+
def items(self) -> ItemsView[_K, _V]:
77+
return self._dict.items()
78+
79+
def keys(self) -> KeysView[_K]:
80+
return self._dict.keys()
81+
82+
def values(self) -> ValuesView[_V]:
83+
return self._dict.values()
84+
7685

7786
class ImmutableOrderedDict(immutabledict[_K, _V]):
7887
"""

tests/test_immutabledict.py

+13
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,19 @@ def test_union_operator_update_with_dict_second(self) -> None:
185185
assert first_dict == {"a": "a", "b": "b"}
186186
assert second_dict == {"a": "A", "c": "c"}
187187

188+
def test_performance(self) -> None:
189+
from timeit import timeit
190+
time_standard = timeit(
191+
"for k, v in d.items(): s += 1", number=3,
192+
setup="s=0; d = {i:i for i in range(1000000)}")
193+
194+
time_immutable = timeit(
195+
"for k, v in d.items(): s += 1", globals=globals(), number=3,
196+
setup="s=0; d = immutabledict({i:i for i in range(1000000)})")
197+
198+
assert time_immutable < 1.2 * time_standard
199+
200+
188201

189202
class TestImmutableOrderedDict:
190203
def test_ordered(self) -> None:

0 commit comments

Comments
 (0)