-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
Expand file tree
/
Copy pathrun-dicts.test
More file actions
515 lines (435 loc) · 11.9 KB
/
run-dicts.test
File metadata and controls
515 lines (435 loc) · 11.9 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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
# Test cases for dicts (compile and run)
[case testDictStuff]
from typing import Dict, Any, List, Set, Tuple
from defaultdictwrap import make_dict
def f(x: int) -> int:
dict1 = {} # type: Dict[int, int]
dict1[1] = 1
dict2 = {} # type: Dict[int, int]
dict2[x] = 2
dict1.update(dict2)
l = [(5, 2)] # type: Any
dict1.update(l)
d2 = {6: 4} # type: Any
dict1.update(d2)
return dict1[1]
def g() -> int:
d = make_dict()
d['a'] = 10
d['a'] += 10
d['b'] += 10
l = [('c', 2)] # type: Any
d.update(l)
d2 = {'d': 4} # type: Any
d.update(d2)
return d['a'] + d['b']
def h() -> None:
d = {} # type: Dict[Any, Any]
d[{}]
def update_dict(x: Dict[Any, Any], y: Any):
x.update(y)
def make_dict1(x: Any) -> Dict[Any, Any]:
return dict(x)
def make_dict2(x: Dict[Any, Any]) -> Dict[Any, Any]:
return dict(x)
def u(x: int) -> int:
d = {} # type: Dict[str, int]
d.update(x=x)
return d['x']
def get_content(d: Dict[int, int]) -> Tuple[List[int], List[int], List[Tuple[int, int]]]:
return list(d.keys()), list(d.values()), list(d.items())
def get_content_set(d: Dict[int, int]) -> Tuple[Set[int], Set[int], Set[Tuple[int, int]]]:
return set(d.keys()), set(d.values()), set(d.items())
[file defaultdictwrap.py]
from typing import Dict
from collections import defaultdict # type: ignore
def make_dict() -> Dict[str, int]:
return defaultdict(int)
[file driver.py]
from collections import OrderedDict
from native import (
f, g, h, u, make_dict1, make_dict2, update_dict, get_content, get_content_set
)
assert f(1) == 2
assert f(2) == 1
assert g() == 30
# Make sure we get a TypeError from indexing with unhashable and not KeyError
try:
h()
except TypeError:
pass
else:
assert False
d = {'a': 1, 'b': 2}
assert make_dict1(d) == d
assert make_dict1(d.items()) == d
assert make_dict2(d) == d
# object.__dict__ is a "mappingproxy" and not a dict
assert make_dict1(object.__dict__) == dict(object.__dict__)
d = {}
update_dict(d, object.__dict__)
assert d == dict(object.__dict__)
assert u(10) == 10
assert get_content({1: 2}) == ([1], [2], [(1, 2)])
od = OrderedDict([(1, 2), (3, 4)])
assert get_content(od) == ([1, 3], [2, 4], [(1, 2), (3, 4)])
od.move_to_end(1)
assert get_content(od) == ([3, 1], [4, 2], [(3, 4), (1, 2)])
assert get_content_set({1: 2}) == ({1}, {2}, {(1, 2)})
assert get_content_set(od) == ({1, 3}, {2, 4}, {(1, 2), (3, 4)})
[typing fixtures/typing-full.pyi]
[case testDictIterationMethodsRun]
from typing import Dict, TypedDict, Union
class ExtensionDict(TypedDict):
python: str
c: str
def print_dict_methods(d1: Dict[int, int],
d2: Dict[int, int],
d3: Dict[int, int]) -> None:
for k in d1.keys():
print(k)
for k, v in d2.items():
print(k)
print(v)
for v in d3.values():
print(v)
def print_dict_methods_special(d1: Union[Dict[int, int], Dict[str, str]],
d2: ExtensionDict) -> None:
for k in d1.keys():
print(k)
for k, v in d1.items():
print(k)
print(v)
for v2 in d2.values():
print(v2)
for k2, v2 in d2.items():
print(k2)
print(v2)
def clear_during_iter(d: Dict[int, int]) -> None:
for k in d:
d.clear()
class Custom(Dict[int, int]): pass
[file driver.py]
from native import print_dict_methods, print_dict_methods_special, Custom, clear_during_iter
from collections import OrderedDict
print_dict_methods({}, {}, {})
print_dict_methods({1: 2}, {3: 4, 5: 6}, {7: 8})
print('==')
c = Custom({0: 1})
print_dict_methods(c, c, c)
print('==')
d = OrderedDict([(1, 2), (3, 4)])
print_dict_methods(d, d, d)
print('==')
print_dict_methods_special({1: 2}, {"python": ".py", "c": ".c"})
d.move_to_end(1)
print_dict_methods(d, d, d)
clear_during_iter({}) # OK
try:
clear_during_iter({1: 2, 3: 4})
except RuntimeError as e:
assert str(e) == "dictionary changed size during iteration"
else:
assert False
try:
clear_during_iter(d)
except RuntimeError as e:
assert str(e) in (
"OrderedDict changed size during iteration",
# Error message changed in Python 3.13 and some 3.12 patch version
"OrderedDict mutated during iteration",
)
else:
assert False
class CustomMad(dict):
def __iter__(self):
return self
def __next__(self):
raise ValueError
m = CustomMad()
try:
clear_during_iter(m)
except ValueError:
pass
else:
assert False
class CustomBad(dict):
def items(self):
return [(1, 2, 3)] # Oops
b = CustomBad()
try:
print_dict_methods(b, b, b)
except TypeError as e:
assert str(e) == "a tuple of length 2 expected"
else:
assert False
[typing fixtures/typing-full.pyi]
[out]
1
3
4
5
6
8
==
0
0
1
1
==
1
3
1
2
3
4
2
4
==
1
1
2
.py
.c
python
.py
c
.c
3
1
3
4
1
2
4
2
[case testDictMethods]
from collections import defaultdict
from typing import Dict, Optional, List, Set
def test_dict_clear() -> None:
d = {'a': 1, 'b': 2}
d.clear()
assert d == {}
dd: Dict[str, int] = defaultdict(int)
dd['a'] = 1
dd.clear()
assert dd == {}
def test_dict_copy() -> None:
d: Dict[str, int] = {}
assert d.copy() == d
d = {'a': 1, 'b': 2}
assert d.copy() == d
assert d.copy() is not d
dd: Dict[str, int] = defaultdict(int)
dd['a'] = 1
assert dd.copy() == dd
assert isinstance(dd.copy(), defaultdict)
class MyDict(dict):
def __init__(self, *args, **kwargs):
self.update(*args, **kwargs)
def setdefault(self, k, v=None):
if v is None:
if k in self.keys():
return self[k]
else:
return None
else:
return super().setdefault(k, v) + 10
def test_dict_setdefault() -> None:
d: Dict[str, Optional[int]] = {'a': 1, 'b': 2}
assert d.setdefault('a', 2) == 1
assert d.setdefault('b', 2) == 2
assert d.setdefault('c', 3) == 3
assert d['a'] == 1
assert d['c'] == 3
assert d.setdefault('a') == 1
assert d.setdefault('e') == None
assert d.setdefault('e', 100) == None
def test_dict_subclass_setdefault() -> None:
d = MyDict()
d['a'] = 1
assert d.setdefault('a', 2) == 11
assert d.setdefault('b', 2) == 12
assert d.setdefault('c', 3) == 13
assert d['a'] == 1
assert d['c'] == 3
assert d.setdefault('a') == 1
assert d.setdefault('e') == None
assert d.setdefault('e', 100) == 110
def test_dict_empty_collection_setdefault() -> None:
d1: Dict[str, List[int]] = {'a': [1, 2, 3]}
assert d1.setdefault('a', []) == [1, 2, 3]
assert d1.setdefault('b', []) == []
assert 'b' in d1
d1.setdefault('b', []).append(3)
assert d1['b'] == [3]
assert d1.setdefault('c', [1]) == [1]
d2: Dict[str, Dict[str, int]] = {'a': {'a': 1}}
assert d2.setdefault('a', {}) == {'a': 1}
assert d2.setdefault('b', {}) == {}
assert 'b' in d2
d2.setdefault('b', {})['aa'] = 2
d2.setdefault('b', {})['bb'] = 3
assert d2['b'] == {'aa': 2, 'bb': 3}
assert d2.setdefault('c', {'cc': 1}) == {'cc': 1}
d3: Dict[str, Set[str]] = {'a': set('a')}
assert d3.setdefault('a', set()) == {'a'}
assert d3.setdefault('b', set()) == set()
d3.setdefault('b', set()).add('b')
d3.setdefault('b', set()).add('c')
assert d3['b'] == {'b', 'c'}
assert d3.setdefault('c', set('d')) == {'d'}
[case testDictToBool]
from typing import Dict, List
def is_true(x: dict) -> bool:
if x:
return True
else:
return False
def is_false(x: dict) -> bool:
if not x:
return True
else:
return False
def test_dict_to_bool() -> None:
assert is_false({})
assert not is_true({})
tmp_list: List[Dict] = [{2: bool}, {'a': 'b'}]
for x in tmp_list:
assert is_true(x)
assert not is_false(x)
[case testIsInstance]
from copysubclass import subc
def test_built_in() -> None:
assert isinstance({}, dict)
assert isinstance({'one': 1, 'two': 2}, dict)
assert isinstance({1: 1, 'two': 2}, dict)
assert isinstance(subc(), dict)
assert isinstance(subc({'a': 1, 'b': 2}), dict)
assert isinstance(subc({1: 'a', 2: 'b'}), dict)
assert not isinstance(set(), dict)
assert not isinstance((), dict)
assert not isinstance((1,2,3), dict)
assert not isinstance({'a','b'}, dict)
assert not isinstance(int() + 1, dict)
assert not isinstance(str() + 'a', dict)
def test_user_defined() -> None:
from userdefineddict import dict
assert isinstance(dict(), dict)
assert not isinstance({1: dict()}, dict)
[file copysubclass.py]
from typing import Any
class subc(dict[Any, Any]):
pass
[file userdefineddict.py]
class dict:
pass
[case testDunderDictAccessAfterDel]
from mypy_extensions import mypyc_attr
@mypyc_attr(allow_interpreted_subclasses=True)
class NormDict(dict[str, str]):
def __init__(self, attr: int = 42) -> None:
super().__init__()
self.attr = attr
class SubNormDict(NormDict):
def __init__(self, attr: int = 43) -> None:
super().__init__(attr)
def test_dict_access() -> None:
n = NormDict(1)
d = n.__dict__
assert d["attr"] == 1
del n
assert d["attr"] == 1
def test_subclass_dict_access() -> None:
s = SubNormDict(1)
d = s.__dict__
assert d["attr"] == 1
del s
assert d["attr"] == 1
[file driver.py]
from native import NormDict, SubNormDict, test_dict_access, test_subclass_dict_access
class InterpretedNormDict(NormDict):
pass
def test_dict_access_interpreted() -> None:
n = NormDict()
d = n.__dict__
assert d["attr"] == 42
del n
assert d["attr"] == 42
def test_subclass_dict_access_interpreted() -> None:
s = SubNormDict()
d = s.__dict__
assert d["attr"] == 43
del s
assert d["attr"] == 43
def test_allow_interpreted_subclass_dict_access() -> None:
s = InterpretedNormDict()
d = s.__dict__
assert d["attr"] == 42
del s
assert d["attr"] == 42
test_dict_access()
test_dict_access_interpreted()
test_subclass_dict_access()
test_subclass_dict_access_interpreted()
test_allow_interpreted_subclass_dict_access()
[fixture fixtures/typing-full.pyi]
[case testCycleInDictSubclass]
import gc
from mypy_extensions import mypyc_attr
events: list[str] = []
@mypyc_attr(allow_interpreted_subclasses=True)
class CyclicDict(dict):
def __init__(self) -> None:
self["self"] = self
def __del__(self) -> None:
events.append("deleted")
class SubCyclicDict(CyclicDict):
def __init__(self) -> None:
super().__init__()
def __del__(self) -> None:
events.append("sub deleted")
def test_cyclic_dict_cleanup() -> None:
global events
events = []
c = CyclicDict()
del c
gc.collect()
assert events == ["deleted"], events
def test_sub_cyclic_dict_cleanup() -> None:
global events
events = []
c = SubCyclicDict()
del c
gc.collect()
assert events == ["sub deleted"], events
[file driver.py]
import gc
import native
from native import CyclicDict, SubCyclicDict, test_cyclic_dict_cleanup, test_sub_cyclic_dict_cleanup
class InterpretedCyclicDict(CyclicDict):
def __del__(self) -> None:
native.events.append("interpreted deleted")
def test_cyclic_dict_cleanup_interpreted() -> None:
native.events = []
c = CyclicDict()
del c
gc.collect()
assert native.events == ["deleted"], events
def test_sub_cyclic_dict_cleanup_interpreted() -> None:
native.events = []
c = SubCyclicDict()
del c
gc.collect()
assert native.events == ["sub deleted"], events
def test_allow_interpreted_subclass_cyclic_dict_cleanup() -> None:
native.events = []
c = InterpretedCyclicDict()
del c
gc.collect()
assert native.events == ["interpreted deleted"], events
test_cyclic_dict_cleanup()
test_sub_cyclic_dict_cleanup()
test_cyclic_dict_cleanup_interpreted()
test_sub_cyclic_dict_cleanup_interpreted()
test_allow_interpreted_subclass_cyclic_dict_cleanup()