Skip to content

Please help with defaultdict implementation #778

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

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
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
28 changes: 28 additions & 0 deletions transcrypt/modules/collections.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
"""Python's collections module -- for Transcrypt."""


class defaultdict(dict):
"""Dictionary that takes a factory parameter and always returns a value."""

def __init__(self, default_factory=None, *args, **kwargs): # noqa
if not callable(default_factory) and default_factory is not None:
raise TypeError("first argument must be callable or None")
super().__init__(*args, **kwargs)
self.default_factory = default_factory

def __repr__(self):
return "defaultdict({}, {})".format(
self.default_factory, super().__repr__(self)
)

def __missing__(self, key: str):
if self.default_factory is None:
raise KeyError(key)
self[key] = self.default_factory()
return super().__getitem__(key)

def __getitem__(self, key: str):
try:
return super().__getitem__(key)
except KeyError:
return self.__missing__(key)