-
Notifications
You must be signed in to change notification settings - Fork 227
Expand file tree
/
Copy pathPyDefaultDict.java
More file actions
243 lines (216 loc) · 7.77 KB
/
PyDefaultDict.java
File metadata and controls
243 lines (216 loc) · 7.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
/* Copyright (c) Jython Developers */
package org.python.modules._collections;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.python.core.BuiltinDocs;
import org.python.core.Py;
import org.python.core.PyDictionary;
import org.python.core.PyException;
import org.python.core.PyObject;
import org.python.core.PyTuple;
import org.python.core.PyType;
import org.python.core.Traverseproc;
import org.python.core.Visitproc;
import org.python.expose.ExposedDelete;
import org.python.expose.ExposedGet;
import org.python.expose.ExposedMethod;
import org.python.expose.ExposedNew;
import org.python.expose.ExposedSet;
import org.python.expose.ExposedType;
/**
* PyDefaultDict - This is a subclass of the builtin dict(PyDictionary) class. It supports
* one additional method __missing__ and adds one writable instance variable
* defaultFactory. The remaining functionality is the same as for the dict class.
*
* collections.defaultdict([defaultFactory[, ...]]) - returns a new dictionary-like
* object. The first argument provides the initial value for the defaultFactory attribute;
* it defaults to None. All remaining arguments are treated the same as if they were
* passed to the dict constructor, including keyword arguments.
*/
@ExposedType(name = "collections.defaultdict")
public class PyDefaultDict extends PyDictionary implements Traverseproc {
public static final PyType TYPE = PyType.fromClass(PyDefaultDict.class);
/**
* This attribute is used by the __missing__ method; it is initialized from the first
* argument to the constructor, if present, or to None, if absent.
*/
private PyObject defaultFactory = Py.None;
private final LoadingCache<PyObject, PyObject> backingMap;
public ConcurrentMap<PyObject, PyObject> getMap() {
return backingMap.asMap();
}
public PyDefaultDict() {
this(TYPE);
}
public PyDefaultDict(PyType subtype) {
super(subtype, false);
backingMap = CacheBuilder.newBuilder().build(
new CacheLoader<PyObject, PyObject>() {
public PyObject load(PyObject key) {
try {
return __missing__(key);
} catch (RuntimeException ex) {
throw new MissingThrownException(ex);
}
}
});
}
public PyDefaultDict(PyType subtype, Map<PyObject, PyObject> map) {
this(subtype);
getMap().putAll(map);
}
@ExposedMethod
@ExposedNew
final void defaultdict___init__(PyObject[] args, String[] kwds) {
int nargs = args.length - kwds.length;
if (nargs != 0) {
defaultFactory = args[0];
if (!(defaultFactory == Py.None || defaultFactory.isCallable())) {
throw Py.TypeError("first argument must be callable");
}
PyObject newargs[] = new PyObject[args.length - 1];
System.arraycopy(args, 1, newargs, 0, newargs.length);
dict___init__(newargs, kwds);
}
}
public PyObject __missing__(PyObject key) {
return defaultdict___missing__(key);
}
/**
* This method does NOT call __setitem__ instead it relies on the fact that it is
* called within the context of `CacheLoader#load` to actually insert the value
* into the dict.
*/
@ExposedMethod
final PyObject defaultdict___missing__(PyObject key) {
if (defaultFactory == Py.None) {
throw Py.KeyError(key);
}
return defaultFactory.__call__();
}
@Override
public PyObject __reduce__() {
return defaultdict___reduce__();
}
@ExposedMethod
final PyObject defaultdict___reduce__() {
PyTuple args = null;
if (defaultFactory == Py.None) {
args = new PyTuple();
} else {
PyObject[] ob = {defaultFactory};
args = new PyTuple(ob);
}
return new PyTuple(getType(), args, Py.None, Py.None, iteritems());
}
@Override
public PyDictionary copy() {
return defaultdict_copy();
}
@ExposedMethod(names = {"copy", "__copy__"})
final PyDefaultDict defaultdict_copy() {
PyDefaultDict ob = new PyDefaultDict(TYPE, getMap());
ob.defaultFactory = defaultFactory;
return ob;
}
@Override
public String toString() {
return defaultdict_toString();
}
@ExposedMethod(names = "__repr__")
final String defaultdict_toString() {
return String.format("defaultdict(%s, %s)", defaultFactory, super.toString());
}
@ExposedGet(name = "default_factory")
public PyObject getDefaultFactory() {
return defaultFactory;
}
@ExposedSet(name = "default_factory")
public void setDefaultFactory(PyObject value) {
defaultFactory = value;
}
@ExposedDelete(name = "default_factory")
public void delDefaultFactory() {
defaultFactory = Py.None;
}
@Override
public PyObject __finditem__(PyObject key) {
return defaultdict___getitem__(key);
}
@ExposedMethod(doc = BuiltinDocs.dict___getitem___doc)
protected final PyObject defaultdict___getitem__(PyObject key) {
try {
return backingMap.get(key);
} catch (PyException pe) {
/* LoadingCache#get() don't throw any PyException itself and it
* prevents those raised in CacheLoader#load() to get through
* without being wrapped in UncheckedExecutionException, so this
* PyException must be from key#hashCode(). We can propagated it to
* caller as it is. */
throw pe;
} catch (Exception ex) {
Throwable cause = ex.getCause();
if (cause != null && cause instanceof MissingThrownException) {
throw ((MissingThrownException) cause).thrownByMissing;
}
throw Py.KeyError(key);
}
}
public PyObject get(PyObject key, PyObject defaultObj) {
PyObject value = getMap().get(key);
if (value != null) {
return value;
} else {
return defaultObj;
}
}
/* Traverseproc implementation */
@Override
public int traverse(Visitproc visit, Object arg) {
int retVal = super.traverse(visit, arg);
if (retVal != 0) {
return retVal;
}
retVal = visit.visit(defaultFactory, arg);
if (retVal != 0) {
return retVal;
}
if (backingMap != null) {
for (Map.Entry<PyObject, PyObject> ent: backingMap.asMap().entrySet()) {
retVal = visit.visit(ent.getKey(), arg);
if (retVal != 0) {
return retVal;
}
if (ent.getValue() != null) {
retVal = visit.visit(ent.getValue(), arg);
if (retVal != 0) {
return retVal;
}
}
}
}
return 0;
}
@Override
public boolean refersDirectlyTo(PyObject ob) {
if (ob == null) {
return false;
} else if (super.refersDirectlyTo(ob)) {
return true;
}
if (backingMap == null) {
return false;
}
return backingMap.asMap().containsKey(ob) || backingMap.asMap().containsValue(ob);
}
private static class MissingThrownException extends RuntimeException {
final RuntimeException thrownByMissing;
MissingThrownException(RuntimeException thrownByMissing) {
super(thrownByMissing);
this.thrownByMissing = thrownByMissing;
}
}
}