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

Adds __new__ method, removes init method #263

Merged
merged 3 commits into from
Oct 6, 2023
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions immutabledict/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,16 +30,20 @@ class immutabledict(Mapping[_K, _V]):
"""

dict_cls: Type[Dict[Any, Any]] = dict
_dict: Dict[_K, _V]
_hash: Optional[int]

@classmethod
def fromkeys(
cls, seq: Iterable[_K], value: Optional[_V] = None
) -> immutabledict[_K, _V]:
return cls(cls.dict_cls.fromkeys(seq, value))

def __init__(self, *args: Any, **kwargs: Any) -> None:
self._dict = self.dict_cls(*args, **kwargs)
self._hash: Optional[int] = None
def __new__(cls, *args: Any) -> immutabledict[_K, _V]:
inst = super().__new__(cls)
setattr(inst, "_dict", cls.dict_cls(*args))
setattr(inst, "_hash", None)
return inst

def __getitem__(self, key: _K) -> _V:
return self._dict[key]
Expand Down
4 changes: 4 additions & 0 deletions tests/test_immutabledict.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ class Two(Base):
my_dict = second_dict
assert my_dict == second_dict

def test_new_init_methods(self) -> None:
assert "__new__" in immutabledict.__dict__
assert "__init__" not in immutabledict.__dict__

def test_cannot_assign_value(self) -> None:
with pytest.raises(AttributeError):
immutabledict().setitem("key", "value") # type: ignore
Expand Down