Skip to content

Commit 3c9045d

Browse files
Merge pull request RustPython#1134 from RustPython/coolreader18/collections-defaultdict
Add defaultdict to collections; add pprint.py
2 parents 8869130 + bf3f09c commit 3c9045d

File tree

3 files changed

+623
-0
lines changed

3 files changed

+623
-0
lines changed

Lib/collections/__init__.py

+6
Original file line numberDiff line numberDiff line change
@@ -1277,3 +1277,9 @@ def translate(self, *args):
12771277
return self.__class__(self.data.translate(*args))
12781278
def upper(self): return self.__class__(self.data.upper())
12791279
def zfill(self, width): return self.__class__(self.data.zfill(width))
1280+
1281+
# FIXME: try to implement defaultdict in collections.rs rather than in Python
1282+
# I (coolreader18) couldn't figure out some class stuff with __new__ and
1283+
# __init__ and __missing__ and subclassing built-in types from Rust, so I went
1284+
# with this instead.
1285+
from ._defaultdict import *

Lib/collections/_defaultdict.py

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
class defaultdict(dict):
2+
def __new__(cls, *args, **kwargs):
3+
if len(args) >= 1:
4+
default_factory = args[0]
5+
args = args[1:]
6+
else:
7+
default_factory = None
8+
self = dict.__new__(cls, *args, **kwargs)
9+
self.default_factory = default_factory
10+
return self
11+
12+
def __missing__(self, key):
13+
if self.default_factory:
14+
return self.default_factory()
15+
else:
16+
raise KeyError(key)
17+
18+
def __repr__(self):
19+
return f"defaultdict({self.default_factory}, {dict.__repr__(self)})"
20+

0 commit comments

Comments
 (0)