Skip to content

Commit

Permalink
add explicit items()/keys()/values() methods
Browse files Browse the repository at this point in the history
  • Loading branch information
matthiasdiener committed Sep 19, 2023
1 parent 9684df3 commit efd6e81
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
11 changes: 10 additions & 1 deletion immutabledict/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from __future__ import annotations

from collections import OrderedDict
from typing import Any, Dict, Iterable, Iterator, Mapping, Optional, Type, TypeVar
from typing import Any, Dict, ItemsView, Iterable, Iterator, Mapping, Optional, Type, TypeVar, ValuesView, KeysView

__version__ = "3.0.0"

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

def items(self) -> ItemsView[_K, _V]:
return self._dict.items()

def keys(self) -> KeysView[_K]:
return self._dict.keys()

def values(self) -> ValuesView[_V]:
return self._dict.values()


class ImmutableOrderedDict(immutabledict[_K, _V]):
"""
Expand Down
13 changes: 13 additions & 0 deletions tests/test_immutabledict.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,19 @@ def test_union_operator_update_with_dict_second(self) -> None:
assert first_dict == {"a": "a", "b": "b"}
assert second_dict == {"a": "A", "c": "c"}

def test_performance(self) -> None:
from timeit import timeit
time_standard = timeit(
"for k, v in d.items(): s += 1", number=3,
setup="s=0; d = {i:i for i in range(1000000)}")

time_immutable = timeit(
"for k, v in d.items(): s += 1", globals=globals(), number=3,
setup="s=0; d = immutabledict({i:i for i in range(1000000)})")

assert time_immutable < 1.2 * time_standard



class TestImmutableOrderedDict:
def test_ordered(self) -> None:
Expand Down

0 comments on commit efd6e81

Please sign in to comment.