Skip to content

Add defaultdict to collections; add pprint.py #1134

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

Merged
merged 2 commits into from
Jul 11, 2019
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
6 changes: 6 additions & 0 deletions Lib/collections/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1277,3 +1277,9 @@ def translate(self, *args):
return self.__class__(self.data.translate(*args))
def upper(self): return self.__class__(self.data.upper())
def zfill(self, width): return self.__class__(self.data.zfill(width))

# FIXME: try to implement defaultdict in collections.rs rather than in Python
# I (coolreader18) couldn't figure out some class stuff with __new__ and
# __init__ and __missing__ and subclassing built-in types from Rust, so I went
# with this instead.
from ._defaultdict import *
20 changes: 20 additions & 0 deletions Lib/collections/_defaultdict.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
class defaultdict(dict):
def __new__(cls, *args, **kwargs):
if len(args) >= 1:
default_factory = args[0]
args = args[1:]
else:
default_factory = None
self = dict.__new__(cls, *args, **kwargs)
self.default_factory = default_factory
return self

def __missing__(self, key):
if self.default_factory:
return self.default_factory()
else:
raise KeyError(key)

def __repr__(self):
return f"defaultdict({self.default_factory}, {dict.__repr__(self)})"

Loading