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

add explicit items()/keys()/values() methods #265

Closed
wants to merge 1 commit into from
Closed
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
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