Debian Codegraph @

Lib/test/test_functools.py

raw
1 import abc
2 import builtins
3 import collections
4 import collections.abc
5 import copy
6 from itertools import permutations
7 import pickle
8 from random import choice
9 import sys
10 from test import support
11 import threading
12 import time
13 import typing
14 import unittest
15 import unittest.mock
16 import weakref
17 import gc
18 from weakref import proxy
19 import contextlib
20 from inspect import Signature
21
22 from test.support import import_helper
23 from test.support import threading_helper
24
25 import functools
26
27 py_functools = import_helper.import_fresh_module('functools',
28 blocked=['_functools'])
29 c_functools = import_helper.import_fresh_module('functools',
30 fresh=['_functools'])
31
32 decimal = import_helper.import_fresh_module('decimal', fresh=['_decimal'])
33
34
35 @contextlib.contextmanager
36 def replaced_module(name, replacement):
37 original_module = sys.modules[name]
38 sys.modules[name] = replacement
39 try:
40 yield
41 finally:
42 sys.modules[name] = original_module
43
44 def capture(*args, **kw):
45 """capture all positional and keyword arguments"""
46 return args, kw
47
48
49 def signature(part):
50 """ return the signature of a partial object """
51 return (part.func, part.args, part.keywords, part.__dict__)
52
53 class MyTuple(tuple):
54 pass
55
56 class BadTuple(tuple):
57 def __add__(self, other):
58 return list(self) + list(other)
59
60 class MyDict(dict):
61 pass
62
63
64 class TestPartial:
65
66 def test_basic_examples(self):
67 p = self.partial(capture, 1, 2, a=10, b=20)
68 self.assertTrue(callable(p))
69 self.assertEqual(p(3, 4, b=30, c=40),
70 ((1, 2, 3, 4), dict(a=10, b=30, c=40)))
71 p = self.partial(map, lambda x: x*10)
72 self.assertEqual(list(p([1,2,3,4])), [10, 20, 30, 40])
73
74 def test_attributes(self):
75 p = self.partial(capture, 1, 2, a=10, b=20)
76 # attributes should be readable
77 self.assertEqual(p.func, capture)
78 self.assertEqual(p.args, (1, 2))
79 self.assertEqual(p.keywords, dict(a=10, b=20))
80
81 def test_argument_checking(self):
82 self.assertRaises(TypeError, self.partial) # need at least a func arg
83 try:
84 self.partial(2)()
85 except TypeError:
86 pass
87 else:
88 self.fail('First arg not checked for callability')
89
90 def test_protection_of_callers_dict_argument(self):
91 # a caller's dictionary should not be altered by partial
92 def func(a=10, b=20):
93 return a
94 d = {'a':3}
95 p = self.partial(func, a=5)
96 self.assertEqual(p(**d), 3)
97 self.assertEqual(d, {'a':3})
98 p(b=7)
99 self.assertEqual(d, {'a':3})
100
101 def test_kwargs_copy(self):
102 # Issue #29532: Altering a kwarg dictionary passed to a constructor
103 # should not affect a partial object after creation
104 d = {'a': 3}
105 p = self.partial(capture, **d)
106 self.assertEqual(p(), ((), {'a': 3}))
107 d['a'] = 5
108 self.assertEqual(p(), ((), {'a': 3}))
109
110 def test_arg_combinations(self):
111 # exercise special code paths for zero args in either partial
112 # object or the caller
113 p = self.partial(capture)
114 self.assertEqual(p(), ((), {}))
115 self.assertEqual(p(1,2), ((1,2), {}))
116 p = self.partial(capture, 1, 2)
117 self.assertEqual(p(), ((1,2), {}))
118 self.assertEqual(p(3,4), ((1,2,3,4), {}))
119
120 def test_kw_combinations(self):
121 # exercise special code paths for no keyword args in
122 # either the partial object or the caller
123 p = self.partial(capture)
124 self.assertEqual(p.keywords, {})
125 self.assertEqual(p(), ((), {}))
126 self.assertEqual(p(a=1), ((), {'a':1}))
127 p = self.partial(capture, a=1)
128 self.assertEqual(p.keywords, {'a':1})
129 self.assertEqual(p(), ((), {'a':1}))
130 self.assertEqual(p(b=2), ((), {'a':1, 'b':2}))
131 # keyword args in the call override those in the partial object
132 self.assertEqual(p(a=3, b=2), ((), {'a':3, 'b':2}))
133
134 def test_positional(self):
135 # make sure positional arguments are captured correctly
136 for args in [(), (0,), (0,1), (0,1,2), (0,1,2,3)]:
137 p = self.partial(capture, *args)
138 expected = args + ('x',)
139 got, empty = p('x')
140 self.assertTrue(expected == got and empty == {})
141
142 def test_keyword(self):
143 # make sure keyword arguments are captured correctly
144 for a in ['a', 0, None, 3.5]:
145 p = self.partial(capture, a=a)
146 expected = {'a':a,'x':None}
147 empty, got = p(x=None)
148 self.assertTrue(expected == got and empty == ())
149
150 def test_no_side_effects(self):
151 # make sure there are no side effects that affect subsequent calls
152 p = self.partial(capture, 0, a=1)
153 args1, kw1 = p(1, b=2)
154 self.assertTrue(args1 == (0,1) and kw1 == {'a':1,'b':2})
155 args2, kw2 = p()
156 self.assertTrue(args2 == (0,) and kw2 == {'a':1})
157
158 def test_error_propagation(self):
159 def f(x, y):
160 x / y
161 self.assertRaises(ZeroDivisionError, self.partial(f, 1, 0))
162 self.assertRaises(ZeroDivisionError, self.partial(f, 1), 0)
163 self.assertRaises(ZeroDivisionError, self.partial(f), 1, 0)
164 self.assertRaises(ZeroDivisionError, self.partial(f, y=0), 1)
165
166 def test_weakref(self):
167 f = self.partial(int, base=16)
168 p = proxy(f)
169 self.assertEqual(f.func, p.func)
170 f = None
171 support.gc_collect() # For PyPy or other GCs.
172 self.assertRaises(ReferenceError, getattr, p, 'func')
173
174 def test_with_bound_and_unbound_methods(self):
175 data = list(map(str, range(10)))
176 join = self.partial(str.join, '')
177 self.assertEqual(join(data), '0123456789')
178 join = self.partial(''.join)
179 self.assertEqual(join(data), '0123456789')
180
181 def test_nested_optimization(self):
182 partial = self.partial
183 inner = partial(signature, 'asdf')
184 nested = partial(inner, bar=True)
185 flat = partial(signature, 'asdf', bar=True)
186 self.assertEqual(signature(nested), signature(flat))
187
188 def test_nested_optimization_bug(self):
189 partial = self.partial
190 class Builder:
191 def __call__(self, tag, *children, **attrib):
192 return (tag, children, attrib)
193
194 def __getattr__(self, tag):
195 return partial(self, tag)
196
197 B = Builder()
198 m = B.m
199 assert m(1, 2, a=2) == ('m', (1, 2), dict(a=2))
200
201 def test_nested_partial_with_attribute(self):
202 # see issue 25137
203 partial = self.partial
204
205 def foo(bar):
206 return bar
207
208 p = partial(foo, 'first')
209 p2 = partial(p, 'second')
210 p2.new_attr = 'spam'
211 self.assertEqual(p2.new_attr, 'spam')
212
213 def test_repr(self):
214 args = (object(), object())
215 args_repr = ', '.join(repr(a) for a in args)
216 kwargs = {'a': object(), 'b': object()}
217 kwargs_reprs = ['a={a!r}, b={b!r}'.format_map(kwargs),
218 'b={b!r}, a={a!r}'.format_map(kwargs)]
219 name = f"{self.partial.__module__}.{self.partial.__qualname__}"
220
221 f = self.partial(capture)
222 self.assertEqual(f'{name}({capture!r})', repr(f))
223
224 f = self.partial(capture, *args)
225 self.assertEqual(f'{name}({capture!r}, {args_repr})', repr(f))
226
227 f = self.partial(capture, **kwargs)
228 self.assertIn(repr(f),
229 [f'{name}({capture!r}, {kwargs_repr})'
230 for kwargs_repr in kwargs_reprs])
231
232 f = self.partial(capture, *args, **kwargs)
233 self.assertIn(repr(f),
234 [f'{name}({capture!r}, {args_repr}, {kwargs_repr})'
235 for kwargs_repr in kwargs_reprs])
236
237 def test_recursive_repr(self):
238 name = f"{self.partial.__module__}.{self.partial.__qualname__}"
239
240 f = self.partial(capture)
241 f.__setstate__((f, (), {}, {}))
242 try:
243 self.assertEqual(repr(f), '%s(...)' % (name,))
244 finally:
245 f.__setstate__((capture, (), {}, {}))
246
247 f = self.partial(capture)
248 f.__setstate__((capture, (f,), {}, {}))
249 try:
250 self.assertEqual(repr(f), '%s(%r, ...)' % (name, capture,))
251 finally:
252 f.__setstate__((capture, (), {}, {}))
253
254 f = self.partial(capture)
255 f.__setstate__((capture, (), {'a': f}, {}))
256 try:
257 self.assertEqual(repr(f), '%s(%r, a=...)' % (name, capture,))
258 finally:
259 f.__setstate__((capture, (), {}, {}))
260
261 def test_pickle(self):
262 with replaced_module('functools', self.module):
263 f = self.partial(signature, ['asdf'], bar=[True])
264 f.attr = []
265 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
266 f_copy = pickle.loads(pickle.dumps(f, proto))
267 self.assertEqual(signature(f_copy), signature(f))
268
269 def test_copy(self):
270 f = self.partial(signature, ['asdf'], bar=[True])
271 f.attr = []
272 f_copy = copy.copy(f)
273 self.assertEqual(signature(f_copy), signature(f))
274 self.assertIs(f_copy.attr, f.attr)
275 self.assertIs(f_copy.args, f.args)
276 self.assertIs(f_copy.keywords, f.keywords)
277
278 def test_deepcopy(self):
279 f = self.partial(signature, ['asdf'], bar=[True])
280 f.attr = []
281 f_copy = copy.deepcopy(f)
282 self.assertEqual(signature(f_copy), signature(f))
283 self.assertIsNot(f_copy.attr, f.attr)
284 self.assertIsNot(f_copy.args, f.args)
285 self.assertIsNot(f_copy.args[0], f.args[0])
286 self.assertIsNot(f_copy.keywords, f.keywords)
287 self.assertIsNot(f_copy.keywords['bar'], f.keywords['bar'])
288
289 def test_setstate(self):
290 f = self.partial(signature)
291 f.__setstate__((capture, (1,), dict(a=10), dict(attr=[])))
292
293 self.assertEqual(signature(f),
294 (capture, (1,), dict(a=10), dict(attr=[])))
295 self.assertEqual(f(2, b=20), ((1, 2), {'a': 10, 'b': 20}))
296
297 f.__setstate__((capture, (1,), dict(a=10), None))
298
299 self.assertEqual(signature(f), (capture, (1,), dict(a=10), {}))
300 self.assertEqual(f(2, b=20), ((1, 2), {'a': 10, 'b': 20}))
301
302 f.__setstate__((capture, (1,), None, None))
303 #self.assertEqual(signature(f), (capture, (1,), {}, {}))
304 self.assertEqual(f(2, b=20), ((1, 2), {'b': 20}))
305 self.assertEqual(f(2), ((1, 2), {}))
306 self.assertEqual(f(), ((1,), {}))
307
308 f.__setstate__((capture, (), {}, None))
309 self.assertEqual(signature(f), (capture, (), {}, {}))
310 self.assertEqual(f(2, b=20), ((2,), {'b': 20}))
311 self.assertEqual(f(2), ((2,), {}))
312 self.assertEqual(f(), ((), {}))
313
314 def test_setstate_errors(self):
315 f = self.partial(signature)
316
317 self.assertRaises(TypeError, f.__setstate__, (capture, (), {}))
318 self.assertRaises(TypeError, f.__setstate__, (capture, (), {}, {}, None))
319 self.assertRaises(TypeError, f.__setstate__, [capture, (), {}, None])
320 self.assertRaises(TypeError, f.__setstate__, (None, (), {}, None))
321 self.assertRaises(TypeError, f.__setstate__, (capture, None, {}, None))
322 self.assertRaises(TypeError, f.__setstate__, (capture, [], {}, None))
323 self.assertRaises(TypeError, f.__setstate__, (capture, (), [], None))
324 self.assertRaises(TypeError, f.__setstate__, (capture, (), {}, ()))
325 self.assertRaises(TypeError, f.__setstate__, (capture, (), {}, 'test'))
326
327 def test_setstate_subclasses(self):
328 f = self.partial(signature)
329 f.__setstate__((capture, MyTuple((1,)), MyDict(a=10), None))
330 s = signature(f)
331 self.assertEqual(s, (capture, (1,), dict(a=10), {}))
332 self.assertIs(type(s[1]), tuple)
333 self.assertIs(type(s[2]), dict)
334 r = f()
335 self.assertEqual(r, ((1,), {'a': 10}))
336 self.assertIs(type(r[0]), tuple)
337 self.assertIs(type(r[1]), dict)
338
339 f.__setstate__((capture, BadTuple((1,)), {}, None))
340 s = signature(f)
341 self.assertEqual(s, (capture, (1,), {}, {}))
342 self.assertIs(type(s[1]), tuple)
343 r = f(2)
344 self.assertEqual(r, ((1, 2), {}))
345 self.assertIs(type(r[0]), tuple)
346
347 def test_recursive_pickle(self):
348 with replaced_module('functools', self.module):
349 f = self.partial(capture)
350 f.__setstate__((f, (), {}, {}))
351 try:
352 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
353 # gh-117008: Small limit since pickle uses C stack memory
354 with support.infinite_recursion(100):
355 with self.assertRaises(RecursionError):
356 pickle.dumps(f, proto)
357 finally:
358 f.__setstate__((capture, (), {}, {}))
359
360 f = self.partial(capture)
361 f.__setstate__((capture, (f,), {}, {}))
362 try:
363 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
364 f_copy = pickle.loads(pickle.dumps(f, proto))
365 try:
366 self.assertIs(f_copy.args[0], f_copy)
367 finally:
368 f_copy.__setstate__((capture, (), {}, {}))
369 finally:
370 f.__setstate__((capture, (), {}, {}))
371
372 f = self.partial(capture)
373 f.__setstate__((capture, (), {'a': f}, {}))
374 try:
375 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
376 f_copy = pickle.loads(pickle.dumps(f, proto))
377 try:
378 self.assertIs(f_copy.keywords['a'], f_copy)
379 finally:
380 f_copy.__setstate__((capture, (), {}, {}))
381 finally:
382 f.__setstate__((capture, (), {}, {}))
383
384 # Issue 6083: Reference counting bug
385 def test_setstate_refcount(self):
386 class BadSequence:
387 def __len__(self):
388 return 4
389 def __getitem__(self, key):
390 if key == 0:
391 return max
392 elif key == 1:
393 return tuple(range(1000000))
394 elif key in (2, 3):
395 return {}
396 raise IndexError
397
398 f = self.partial(object)
399 self.assertRaises(TypeError, f.__setstate__, BadSequence())
400
401 def test_partial_as_method(self):
402 class A:
403 meth = self.partial(capture, 1, a=2)
404 cmeth = classmethod(self.partial(capture, 1, a=2))
405 smeth = staticmethod(self.partial(capture, 1, a=2))
406
407 a = A()
408 self.assertEqual(A.meth(3, b=4), ((1, 3), {'a': 2, 'b': 4}))
409 self.assertEqual(A.cmeth(3, b=4), ((1, A, 3), {'a': 2, 'b': 4}))
410 self.assertEqual(A.smeth(3, b=4), ((1, 3), {'a': 2, 'b': 4}))
411 with self.assertWarns(FutureWarning) as w:
412 self.assertEqual(a.meth(3, b=4), ((1, 3), {'a': 2, 'b': 4}))
413 self.assertEqual(w.filename, __file__)
414 self.assertEqual(a.cmeth(3, b=4), ((1, A, 3), {'a': 2, 'b': 4}))
415 self.assertEqual(a.smeth(3, b=4), ((1, 3), {'a': 2, 'b': 4}))
416
417 def test_partial_genericalias(self):
418 alias = self.partial[int]
419 self.assertIs(alias.__origin__, self.partial)
420 self.assertEqual(alias.__args__, (int,))
421 self.assertEqual(alias.__parameters__, ())
422
423
424 @unittest.skipUnless(c_functools, 'requires the C _functools module')
425 class TestPartialC(TestPartial, unittest.TestCase):
426 if c_functools:
427 module = c_functools
428 partial = c_functools.partial
429
430 def test_attributes_unwritable(self):
431 # attributes should not be writable
432 p = self.partial(capture, 1, 2, a=10, b=20)
433 self.assertRaises(AttributeError, setattr, p, 'func', map)
434 self.assertRaises(AttributeError, setattr, p, 'args', (1, 2))
435 self.assertRaises(AttributeError, setattr, p, 'keywords', dict(a=1, b=2))
436
437 p = self.partial(hex)
438 try:
439 del p.__dict__
440 except TypeError:
441 pass
442 else:
443 self.fail('partial object allowed __dict__ to be deleted')
444
445 def test_manually_adding_non_string_keyword(self):
446 p = self.partial(capture)
447 # Adding a non-string/unicode keyword to partial kwargs
448 p.keywords[1234] = 'value'
449 r = repr(p)
450 self.assertIn('1234', r)
451 self.assertIn("'value'", r)
452 with self.assertRaises(TypeError):
453 p()
454
455 def test_keystr_replaces_value(self):
456 p = self.partial(capture)
457
458 class MutatesYourDict(object):
459 def __str__(self):
460 p.keywords[self] = ['sth2']
461 return 'astr'
462
463 # Replacing the value during key formatting should keep the original
464 # value alive (at least long enough).
465 p.keywords[MutatesYourDict()] = ['sth']
466 r = repr(p)
467 self.assertIn('astr', r)
468 self.assertIn("['sth']", r)
469
470
471 class TestPartialPy(TestPartial, unittest.TestCase):
472 module = py_functools
473 partial = py_functools.partial
474
475
476 if c_functools:
477 class CPartialSubclass(c_functools.partial):
478 pass
479
480 class PyPartialSubclass(py_functools.partial):
481 pass
482
483 @unittest.skipUnless(c_functools, 'requires the C _functools module')
484 class TestPartialCSubclass(TestPartialC):
485 if c_functools:
486 partial = CPartialSubclass
487
488 # partial subclasses are not optimized for nested calls
489 test_nested_optimization = None
490
491 class TestPartialPySubclass(TestPartialPy):
492 partial = PyPartialSubclass
493
494 class TestPartialMethod(unittest.TestCase):
495
496 class A(object):
497 nothing = functools.partialmethod(capture)
498 positional = functools.partialmethod(capture, 1)
499 keywords = functools.partialmethod(capture, a=2)
500 both = functools.partialmethod(capture, 3, b=4)
501 spec_keywords = functools.partialmethod(capture, self=1, func=2)
502
503 nested = functools.partialmethod(positional, 5)
504
505 over_partial = functools.partialmethod(functools.partial(capture, c=6), 7)
506
507 static = functools.partialmethod(staticmethod(capture), 8)
508 cls = functools.partialmethod(classmethod(capture), d=9)
509
510 a = A()
511
512 def test_arg_combinations(self):
513 self.assertEqual(self.a.nothing(), ((self.a,), {}))
514 self.assertEqual(self.a.nothing(5), ((self.a, 5), {}))
515 self.assertEqual(self.a.nothing(c=6), ((self.a,), {'c': 6}))
516 self.assertEqual(self.a.nothing(5, c=6), ((self.a, 5), {'c': 6}))
517
518 self.assertEqual(self.a.positional(), ((self.a, 1), {}))
519 self.assertEqual(self.a.positional(5), ((self.a, 1, 5), {}))
520 self.assertEqual(self.a.positional(c=6), ((self.a, 1), {'c': 6}))
521 self.assertEqual(self.a.positional(5, c=6), ((self.a, 1, 5), {'c': 6}))
522
523 self.assertEqual(self.a.keywords(), ((self.a,), {'a': 2}))
524 self.assertEqual(self.a.keywords(5), ((self.a, 5), {'a': 2}))
525 self.assertEqual(self.a.keywords(c=6), ((self.a,), {'a': 2, 'c': 6}))
526 self.assertEqual(self.a.keywords(5, c=6), ((self.a, 5), {'a': 2, 'c': 6}))
527
528 self.assertEqual(self.a.both(), ((self.a, 3), {'b': 4}))
529 self.assertEqual(self.a.both(5), ((self.a, 3, 5), {'b': 4}))
530 self.assertEqual(self.a.both(c=6), ((self.a, 3), {'b': 4, 'c': 6}))
531 self.assertEqual(self.a.both(5, c=6), ((self.a, 3, 5), {'b': 4, 'c': 6}))
532
533 self.assertEqual(self.A.both(self.a, 5, c=6), ((self.a, 3, 5), {'b': 4, 'c': 6}))
534
535 self.assertEqual(self.a.spec_keywords(), ((self.a,), {'self': 1, 'func': 2}))
536
537 def test_nested(self):
538 self.assertEqual(self.a.nested(), ((self.a, 1, 5), {}))
539 self.assertEqual(self.a.nested(6), ((self.a, 1, 5, 6), {}))
540 self.assertEqual(self.a.nested(d=7), ((self.a, 1, 5), {'d': 7}))
541 self.assertEqual(self.a.nested(6, d=7), ((self.a, 1, 5, 6), {'d': 7}))
542
543 self.assertEqual(self.A.nested(self.a, 6, d=7), ((self.a, 1, 5, 6), {'d': 7}))
544
545 def test_over_partial(self):
546 self.assertEqual(self.a.over_partial(), ((self.a, 7), {'c': 6}))
547 self.assertEqual(self.a.over_partial(5), ((self.a, 7, 5), {'c': 6}))
548 self.assertEqual(self.a.over_partial(d=8), ((self.a, 7), {'c': 6, 'd': 8}))
549 self.assertEqual(self.a.over_partial(5, d=8), ((self.a, 7, 5), {'c': 6, 'd': 8}))
550
551 self.assertEqual(self.A.over_partial(self.a, 5, d=8), ((self.a, 7, 5), {'c': 6, 'd': 8}))
552
553 def test_bound_method_introspection(self):
554 obj = self.a
555 self.assertIs(obj.both.__self__, obj)
556 self.assertIs(obj.nested.__self__, obj)
557 self.assertIs(obj.over_partial.__self__, obj)
558 self.assertIs(obj.cls.__self__, self.A)
559 self.assertIs(self.A.cls.__self__, self.A)
560
561 def test_unbound_method_retrieval(self):
562 obj = self.A
563 self.assertFalse(hasattr(obj.both, "__self__"))
564 self.assertFalse(hasattr(obj.nested, "__self__"))
565 self.assertFalse(hasattr(obj.over_partial, "__self__"))
566 self.assertFalse(hasattr(obj.static, "__self__"))
567 self.assertFalse(hasattr(self.a.static, "__self__"))
568
569 def test_descriptors(self):
570 for obj in [self.A, self.a]:
571 with self.subTest(obj=obj):
572 self.assertEqual(obj.static(), ((8,), {}))
573 self.assertEqual(obj.static(5), ((8, 5), {}))
574 self.assertEqual(obj.static(d=8), ((8,), {'d': 8}))
575 self.assertEqual(obj.static(5, d=8), ((8, 5), {'d': 8}))
576
577 self.assertEqual(obj.cls(), ((self.A,), {'d': 9}))
578 self.assertEqual(obj.cls(5), ((self.A, 5), {'d': 9}))
579 self.assertEqual(obj.cls(c=8), ((self.A,), {'c': 8, 'd': 9}))
580 self.assertEqual(obj.cls(5, c=8), ((self.A, 5), {'c': 8, 'd': 9}))
581
582 def test_overriding_keywords(self):
583 self.assertEqual(self.a.keywords(a=3), ((self.a,), {'a': 3}))
584 self.assertEqual(self.A.keywords(self.a, a=3), ((self.a,), {'a': 3}))
585
586 def test_invalid_args(self):
587 with self.assertRaises(TypeError):
588 class B(object):
589 method = functools.partialmethod(None, 1)
590 with self.assertRaises(TypeError):
591 class B:
592 method = functools.partialmethod()
593 with self.assertRaises(TypeError):
594 class B:
595 method = functools.partialmethod(func=capture, a=1)
596
597 def test_repr(self):
598 self.assertEqual(repr(vars(self.A)['nothing']),
599 'functools.partialmethod({})'.format(capture))
600 self.assertEqual(repr(vars(self.A)['positional']),
601 'functools.partialmethod({}, 1)'.format(capture))
602 self.assertEqual(repr(vars(self.A)['keywords']),
603 'functools.partialmethod({}, a=2)'.format(capture))
604 self.assertEqual(repr(vars(self.A)['spec_keywords']),
605 'functools.partialmethod({}, self=1, func=2)'.format(capture))
606 self.assertEqual(repr(vars(self.A)['both']),
607 'functools.partialmethod({}, 3, b=4)'.format(capture))
608
609 def test_abstract(self):
610 class Abstract(abc.ABCMeta):
611
612 @abc.abstractmethod
613 def add(self, x, y):
614 pass
615
616 add5 = functools.partialmethod(add, 5)
617
618 self.assertTrue(Abstract.add.__isabstractmethod__)
619 self.assertTrue(Abstract.add5.__isabstractmethod__)
620
621 for func in [self.A.static, self.A.cls, self.A.over_partial, self.A.nested, self.A.both]:
622 self.assertFalse(getattr(func, '__isabstractmethod__', False))
623
624 def test_positional_only(self):
625 def f(a, b, /):
626 return a + b
627
628 p = functools.partial(f, 1)
629 self.assertEqual(p(2), f(1, 2))
630
631
632 class TestUpdateWrapper(unittest.TestCase):
633
634 def check_wrapper(self, wrapper, wrapped,
635 assigned=functools.WRAPPER_ASSIGNMENTS,
636 updated=functools.WRAPPER_UPDATES):
637 # Check attributes were assigned
638 for name in assigned:
639 self.assertIs(getattr(wrapper, name), getattr(wrapped, name))
640 # Check attributes were updated
641 for name in updated:
642 wrapper_attr = getattr(wrapper, name)
643 wrapped_attr = getattr(wrapped, name)
644 for key in wrapped_attr:
645 if name == "__dict__" and key == "__wrapped__":
646 # __wrapped__ is overwritten by the update code
647 continue
648 self.assertIs(wrapped_attr[key], wrapper_attr[key])
649 # Check __wrapped__
650 self.assertIs(wrapper.__wrapped__, wrapped)
651
652
653 def _default_update(self):
654 def f[T](a:'This is a new annotation'):
655 """This is a test"""
656 pass
657 f.attr = 'This is also a test'
658 f.__wrapped__ = "This is a bald faced lie"
659 def wrapper(b:'This is the prior annotation'):
660 pass
661 functools.update_wrapper(wrapper, f)
662 return wrapper, f
663
664 def test_default_update(self):
665 wrapper, f = self._default_update()
666 self.check_wrapper(wrapper, f)
667 T, = f.__type_params__
668 self.assertIs(wrapper.__wrapped__, f)
669 self.assertEqual(wrapper.__name__, 'f')
670 self.assertEqual(wrapper.__qualname__, f.__qualname__)
671 self.assertEqual(wrapper.attr, 'This is also a test')
672 self.assertEqual(wrapper.__annotations__['a'], 'This is a new annotation')
673 self.assertNotIn('b', wrapper.__annotations__)
674 self.assertEqual(wrapper.__type_params__, (T,))
675
676 @unittest.skipIf(sys.flags.optimize >= 2,
677 "Docstrings are omitted with -O2 and above")
678 def test_default_update_doc(self):
679 wrapper, f = self._default_update()
680 self.assertEqual(wrapper.__doc__, 'This is a test')
681
682 def test_no_update(self):
683 def f():
684 """This is a test"""
685 pass
686 f.attr = 'This is also a test'
687 def wrapper():
688 pass
689 functools.update_wrapper(wrapper, f, (), ())
690 self.check_wrapper(wrapper, f, (), ())
691 self.assertEqual(wrapper.__name__, 'wrapper')
692 self.assertNotEqual(wrapper.__qualname__, f.__qualname__)
693 self.assertEqual(wrapper.__doc__, None)
694 self.assertEqual(wrapper.__annotations__, {})
695 self.assertFalse(hasattr(wrapper, 'attr'))
696
697 def test_selective_update(self):
698 def f():
699 pass
700 f.attr = 'This is a different test'
701 f.dict_attr = dict(a=1, b=2, c=3)
702 def wrapper():
703 pass
704 wrapper.dict_attr = {}
705 assign = ('attr',)
706 update = ('dict_attr',)
707 functools.update_wrapper(wrapper, f, assign, update)
708 self.check_wrapper(wrapper, f, assign, update)
709 self.assertEqual(wrapper.__name__, 'wrapper')
710 self.assertNotEqual(wrapper.__qualname__, f.__qualname__)
711 self.assertEqual(wrapper.__doc__, None)
712 self.assertEqual(wrapper.attr, 'This is a different test')
713 self.assertEqual(wrapper.dict_attr, f.dict_attr)
714
715 def test_missing_attributes(self):
716 def f():
717 pass
718 def wrapper():
719 pass
720 wrapper.dict_attr = {}
721 assign = ('attr',)
722 update = ('dict_attr',)
723 # Missing attributes on wrapped object are ignored
724 functools.update_wrapper(wrapper, f, assign, update)
725 self.assertNotIn('attr', wrapper.__dict__)
726 self.assertEqual(wrapper.dict_attr, {})
727 # Wrapper must have expected attributes for updating
728 del wrapper.dict_attr
729 with self.assertRaises(AttributeError):
730 functools.update_wrapper(wrapper, f, assign, update)
731 wrapper.dict_attr = 1
732 with self.assertRaises(AttributeError):
733 functools.update_wrapper(wrapper, f, assign, update)
734
735 @support.requires_docstrings
736 @unittest.skipIf(sys.flags.optimize >= 2,
737 "Docstrings are omitted with -O2 and above")
738 def test_builtin_update(self):
739 # Test for bug #1576241
740 def wrapper():
741 pass
742 functools.update_wrapper(wrapper, max)
743 self.assertEqual(wrapper.__name__, 'max')
744 self.assertTrue(wrapper.__doc__.startswith('max('))
745 self.assertEqual(wrapper.__annotations__, {})
746
747 def test_update_type_wrapper(self):
748 def wrapper(*args): pass
749
750 functools.update_wrapper(wrapper, type)
751 self.assertEqual(wrapper.__name__, 'type')
752 self.assertEqual(wrapper.__annotations__, {})
753 self.assertEqual(wrapper.__type_params__, ())
754
755
756 class TestWraps(TestUpdateWrapper):
757
758 def _default_update(self):
759 def f():
760 """This is a test"""
761 pass
762 f.attr = 'This is also a test'
763 f.__wrapped__ = "This is still a bald faced lie"
764 @functools.wraps(f)
765 def wrapper():
766 pass
767 return wrapper, f
768
769 def test_default_update(self):
770 wrapper, f = self._default_update()
771 self.check_wrapper(wrapper, f)
772 self.assertEqual(wrapper.__name__, 'f')
773 self.assertEqual(wrapper.__qualname__, f.__qualname__)
774 self.assertEqual(wrapper.attr, 'This is also a test')
775
776 @unittest.skipIf(sys.flags.optimize >= 2,
777 "Docstrings are omitted with -O2 and above")
778 def test_default_update_doc(self):
779 wrapper, _ = self._default_update()
780 self.assertEqual(wrapper.__doc__, 'This is a test')
781
782 def test_no_update(self):
783 def f():
784 """This is a test"""
785 pass
786 f.attr = 'This is also a test'
787 @functools.wraps(f, (), ())
788 def wrapper():
789 pass
790 self.check_wrapper(wrapper, f, (), ())
791 self.assertEqual(wrapper.__name__, 'wrapper')
792 self.assertNotEqual(wrapper.__qualname__, f.__qualname__)
793 self.assertEqual(wrapper.__doc__, None)
794 self.assertFalse(hasattr(wrapper, 'attr'))
795
796 def test_selective_update(self):
797 def f():
798 pass
799 f.attr = 'This is a different test'
800 f.dict_attr = dict(a=1, b=2, c=3)
801 def add_dict_attr(f):
802 f.dict_attr = {}
803 return f
804 assign = ('attr',)
805 update = ('dict_attr',)
806 @functools.wraps(f, assign, update)
807 @add_dict_attr
808 def wrapper():
809 pass
810 self.check_wrapper(wrapper, f, assign, update)
811 self.assertEqual(wrapper.__name__, 'wrapper')
812 self.assertNotEqual(wrapper.__qualname__, f.__qualname__)
813 self.assertEqual(wrapper.__doc__, None)
814 self.assertEqual(wrapper.attr, 'This is a different test')
815 self.assertEqual(wrapper.dict_attr, f.dict_attr)
816
817
818 class TestReduce:
819 def test_reduce(self):
820 class Squares:
821 def __init__(self, max):
822 self.max = max
823 self.sofar = []
824
825 def __len__(self):
826 return len(self.sofar)
827
828 def __getitem__(self, i):
829 if not 0 <= i < self.max: raise IndexError
830 n = len(self.sofar)
831 while n <= i:
832 self.sofar.append(n*n)
833 n += 1
834 return self.sofar[i]
835 def add(x, y):
836 return x + y
837 self.assertEqual(self.reduce(add, ['a', 'b', 'c'], ''), 'abc')
838 self.assertEqual(
839 self.reduce(add, [['a', 'c'], [], ['d', 'w']], []),
840 ['a','c','d','w']
841 )
842 self.assertEqual(self.reduce(lambda x, y: x*y, range(2,8), 1), 5040)
843 self.assertEqual(
844 self.reduce(lambda x, y: x*y, range(2,21), 1),
845 2432902008176640000
846 )
847 self.assertEqual(self.reduce(add, Squares(10)), 285)
848 self.assertEqual(self.reduce(add, Squares(10), 0), 285)
849 self.assertEqual(self.reduce(add, Squares(0), 0), 0)
850 self.assertRaises(TypeError, self.reduce)
851 self.assertRaises(TypeError, self.reduce, 42, 42)
852 self.assertRaises(TypeError, self.reduce, 42, 42, 42)
853 self.assertEqual(self.reduce(42, "1"), "1") # func is never called with one item
854 self.assertEqual(self.reduce(42, "", "1"), "1") # func is never called with one item
855 self.assertRaises(TypeError, self.reduce, 42, (42, 42))
856 self.assertRaises(TypeError, self.reduce, add, []) # arg 2 must not be empty sequence with no initial value
857 self.assertRaises(TypeError, self.reduce, add, "")
858 self.assertRaises(TypeError, self.reduce, add, ())
859 self.assertRaises(TypeError, self.reduce, add, object())
860
861 class TestFailingIter:
862 def __iter__(self):
863 raise RuntimeError
864 self.assertRaises(RuntimeError, self.reduce, add, TestFailingIter())
865
866 self.assertEqual(self.reduce(add, [], None), None)
867 self.assertEqual(self.reduce(add, [], 42), 42)
868
869 class BadSeq:
870 def __getitem__(self, index):
871 raise ValueError
872 self.assertRaises(ValueError, self.reduce, 42, BadSeq())
873
874 # Test reduce()'s use of iterators.
875 def test_iterator_usage(self):
876 class SequenceClass:
877 def __init__(self, n):
878 self.n = n
879 def __getitem__(self, i):
880 if 0 <= i < self.n:
881 return i
882 else:
883 raise IndexError
884
885 from operator import add
886 self.assertEqual(self.reduce(add, SequenceClass(5)), 10)
887 self.assertEqual(self.reduce(add, SequenceClass(5), 42), 52)
888 self.assertRaises(TypeError, self.reduce, add, SequenceClass(0))
889 self.assertEqual(self.reduce(add, SequenceClass(0), 42), 42)
890 self.assertEqual(self.reduce(add, SequenceClass(1)), 0)
891 self.assertEqual(self.reduce(add, SequenceClass(1), 42), 42)
892
893 d = {"one": 1, "two": 2, "three": 3}
894 self.assertEqual(self.reduce(add, d), "".join(d.keys()))
895
896
897 @unittest.skipUnless(c_functools, 'requires the C _functools module')
898 class TestReduceC(TestReduce, unittest.TestCase):
899 if c_functools:
900 reduce = c_functools.reduce
901
902
903 class TestReducePy(TestReduce, unittest.TestCase):
904 reduce = staticmethod(py_functools.reduce)
905
906
907 class TestCmpToKey:
908
909 def test_cmp_to_key(self):
910 def cmp1(x, y):
911 return (x > y) - (x < y)
912 key = self.cmp_to_key(cmp1)
913 self.assertEqual(key(3), key(3))
914 self.assertGreater(key(3), key(1))
915 self.assertGreaterEqual(key(3), key(3))
916
917 def cmp2(x, y):
918 return int(x) - int(y)
919 key = self.cmp_to_key(cmp2)
920 self.assertEqual(key(4.0), key('4'))
921 self.assertLess(key(2), key('35'))
922 self.assertLessEqual(key(2), key('35'))
923 self.assertNotEqual(key(2), key('35'))
924
925 def test_cmp_to_key_arguments(self):
926 def cmp1(x, y):
927 return (x > y) - (x < y)
928 key = self.cmp_to_key(mycmp=cmp1)
929 self.assertEqual(key(obj=3), key(obj=3))
930 self.assertGreater(key(obj=3), key(obj=1))
931 with self.assertRaises((TypeError, AttributeError)):
932 key(3) > 1 # rhs is not a K object
933 with self.assertRaises((TypeError, AttributeError)):
934 1 < key(3) # lhs is not a K object
935 with self.assertRaises(TypeError):
936 key = self.cmp_to_key() # too few args
937 with self.assertRaises(TypeError):
938 key = self.cmp_to_key(cmp1, None) # too many args
939 key = self.cmp_to_key(cmp1)
940 with self.assertRaises(TypeError):
941 key() # too few args
942 with self.assertRaises(TypeError):
943 key(None, None) # too many args
944
945 def test_bad_cmp(self):
946 def cmp1(x, y):
947 raise ZeroDivisionError
948 key = self.cmp_to_key(cmp1)
949 with self.assertRaises(ZeroDivisionError):
950 key(3) > key(1)
951
952 class BadCmp:
953 def __lt__(self, other):
954 raise ZeroDivisionError
955 def cmp1(x, y):
956 return BadCmp()
957 with self.assertRaises(ZeroDivisionError):
958 key(3) > key(1)
959
960 def test_obj_field(self):
961 def cmp1(x, y):
962 return (x > y) - (x < y)
963 key = self.cmp_to_key(mycmp=cmp1)
964 self.assertEqual(key(50).obj, 50)
965
966 def test_sort_int(self):
967 def mycmp(x, y):
968 return y - x
969 self.assertEqual(sorted(range(5), key=self.cmp_to_key(mycmp)),
970 [4, 3, 2, 1, 0])
971
972 def test_sort_int_str(self):
973 def mycmp(x, y):
974 x, y = int(x), int(y)
975 return (x > y) - (x < y)
976 values = [5, '3', 7, 2, '0', '1', 4, '10', 1]
977 values = sorted(values, key=self.cmp_to_key(mycmp))
978 self.assertEqual([int(value) for value in values],
979 [0, 1, 1, 2, 3, 4, 5, 7, 10])
980
981 def test_hash(self):
982 def mycmp(x, y):
983 return y - x
984 key = self.cmp_to_key(mycmp)
985 k = key(10)
986 self.assertRaises(TypeError, hash, k)
987 self.assertNotIsInstance(k, collections.abc.Hashable)
988
989 @unittest.skipIf(support.MISSING_C_DOCSTRINGS,
990 "Signature information for builtins requires docstrings")
991 def test_cmp_to_signature(self):
992 sig = Signature.from_callable(self.cmp_to_key)
993 self.assertEqual(str(sig), '(mycmp)')
994 def mycmp(x, y):
995 return y - x
996 sig = Signature.from_callable(self.cmp_to_key(mycmp))
997 self.assertEqual(str(sig), '(obj)')
998
999
1000
1001 @unittest.skipUnless(c_functools, 'requires the C _functools module')
1002 class TestCmpToKeyC(TestCmpToKey, unittest.TestCase):
1003 if c_functools:
1004 cmp_to_key = c_functools.cmp_to_key
1005
1006 @support.cpython_only
1007 def test_disallow_instantiation(self):
1008 # Ensure that the type disallows instantiation (bpo-43916)
1009 support.check_disallow_instantiation(
1010 self, type(c_functools.cmp_to_key(None))
1011 )
1012
1013
1014 class TestCmpToKeyPy(TestCmpToKey, unittest.TestCase):
1015 cmp_to_key = staticmethod(py_functools.cmp_to_key)
1016
1017
1018 class TestTotalOrdering(unittest.TestCase):
1019
1020 def test_total_ordering_lt(self):
1021 @functools.total_ordering
1022 class A:
1023 def __init__(self, value):
1024 self.value = value
1025 def __lt__(self, other):
1026 return self.value < other.value
1027 def __eq__(self, other):
1028 return self.value == other.value
1029 self.assertTrue(A(1) < A(2))
1030 self.assertTrue(A(2) > A(1))
1031 self.assertTrue(A(1) <= A(2))
1032 self.assertTrue(A(2) >= A(1))
1033 self.assertTrue(A(2) <= A(2))
1034 self.assertTrue(A(2) >= A(2))
1035 self.assertFalse(A(1) > A(2))
1036
1037 def test_total_ordering_le(self):
1038 @functools.total_ordering
1039 class A:
1040 def __init__(self, value):
1041 self.value = value
1042 def __le__(self, other):
1043 return self.value <= other.value
1044 def __eq__(self, other):
1045 return self.value == other.value
1046 self.assertTrue(A(1) < A(2))
1047 self.assertTrue(A(2) > A(1))
1048 self.assertTrue(A(1) <= A(2))
1049 self.assertTrue(A(2) >= A(1))
1050 self.assertTrue(A(2) <= A(2))
1051 self.assertTrue(A(2) >= A(2))
1052 self.assertFalse(A(1) >= A(2))
1053
1054 def test_total_ordering_gt(self):
1055 @functools.total_ordering
1056 class A:
1057 def __init__(self, value):
1058 self.value = value
1059 def __gt__(self, other):
1060 return self.value > other.value
1061 def __eq__(self, other):
1062 return self.value == other.value
1063 self.assertTrue(A(1) < A(2))
1064 self.assertTrue(A(2) > A(1))
1065 self.assertTrue(A(1) <= A(2))
1066 self.assertTrue(A(2) >= A(1))
1067 self.assertTrue(A(2) <= A(2))
1068 self.assertTrue(A(2) >= A(2))
1069 self.assertFalse(A(2) < A(1))
1070
1071 def test_total_ordering_ge(self):
1072 @functools.total_ordering
1073 class A:
1074 def __init__(self, value):
1075 self.value = value
1076 def __ge__(self, other):
1077 return self.value >= other.value
1078 def __eq__(self, other):
1079 return self.value == other.value
1080 self.assertTrue(A(1) < A(2))
1081 self.assertTrue(A(2) > A(1))
1082 self.assertTrue(A(1) <= A(2))
1083 self.assertTrue(A(2) >= A(1))
1084 self.assertTrue(A(2) <= A(2))
1085 self.assertTrue(A(2) >= A(2))
1086 self.assertFalse(A(2) <= A(1))
1087
1088 def test_total_ordering_no_overwrite(self):
1089 # new methods should not overwrite existing
1090 @functools.total_ordering
1091 class A(int):
1092 pass
1093 self.assertTrue(A(1) < A(2))
1094 self.assertTrue(A(2) > A(1))
1095 self.assertTrue(A(1) <= A(2))
1096 self.assertTrue(A(2) >= A(1))
1097 self.assertTrue(A(2) <= A(2))
1098 self.assertTrue(A(2) >= A(2))
1099
1100 def test_no_operations_defined(self):
1101 with self.assertRaises(ValueError):
1102 @functools.total_ordering
1103 class A:
1104 pass
1105
1106 def test_notimplemented(self):
1107 # Verify NotImplemented results are correctly handled
1108 @functools.total_ordering
1109 class ImplementsLessThan:
1110 def __init__(self, value):
1111 self.value = value
1112 def __eq__(self, other):
1113 if isinstance(other, ImplementsLessThan):
1114 return self.value == other.value
1115 return False
1116 def __lt__(self, other):
1117 if isinstance(other, ImplementsLessThan):
1118 return self.value < other.value
1119 return NotImplemented
1120
1121 @functools.total_ordering
1122 class ImplementsLessThanEqualTo:
1123 def __init__(self, value):
1124 self.value = value
1125 def __eq__(self, other):
1126 if isinstance(other, ImplementsLessThanEqualTo):
1127 return self.value == other.value
1128 return False
1129 def __le__(self, other):
1130 if isinstance(other, ImplementsLessThanEqualTo):
1131 return self.value <= other.value
1132 return NotImplemented
1133
1134 @functools.total_ordering
1135 class ImplementsGreaterThan:
1136 def __init__(self, value):
1137 self.value = value
1138 def __eq__(self, other):
1139 if isinstance(other, ImplementsGreaterThan):
1140 return self.value == other.value
1141 return False
1142 def __gt__(self, other):
1143 if isinstance(other, ImplementsGreaterThan):
1144 return self.value > other.value
1145 return NotImplemented
1146
1147 @functools.total_ordering
1148 class ImplementsGreaterThanEqualTo:
1149 def __init__(self, value):
1150 self.value = value
1151 def __eq__(self, other):
1152 if isinstance(other, ImplementsGreaterThanEqualTo):
1153 return self.value == other.value
1154 return False
1155 def __ge__(self, other):
1156 if isinstance(other, ImplementsGreaterThanEqualTo):
1157 return self.value >= other.value
1158 return NotImplemented
1159
1160 self.assertIs(ImplementsLessThan(1).__le__(1), NotImplemented)
1161 self.assertIs(ImplementsLessThan(1).__gt__(1), NotImplemented)
1162 self.assertIs(ImplementsLessThan(1).__ge__(1), NotImplemented)
1163 self.assertIs(ImplementsLessThanEqualTo(1).__lt__(1), NotImplemented)
1164 self.assertIs(ImplementsLessThanEqualTo(1).__gt__(1), NotImplemented)
1165 self.assertIs(ImplementsLessThanEqualTo(1).__ge__(1), NotImplemented)
1166 self.assertIs(ImplementsGreaterThan(1).__lt__(1), NotImplemented)
1167 self.assertIs(ImplementsGreaterThan(1).__gt__(1), NotImplemented)
1168 self.assertIs(ImplementsGreaterThan(1).__ge__(1), NotImplemented)
1169 self.assertIs(ImplementsGreaterThanEqualTo(1).__lt__(1), NotImplemented)
1170 self.assertIs(ImplementsGreaterThanEqualTo(1).__le__(1), NotImplemented)
1171 self.assertIs(ImplementsGreaterThanEqualTo(1).__gt__(1), NotImplemented)
1172
1173 def test_type_error_when_not_implemented(self):
1174 # bug 10042; ensure stack overflow does not occur
1175 # when decorated types return NotImplemented
1176 @functools.total_ordering
1177 class ImplementsLessThan:
1178 def __init__(self, value):
1179 self.value = value
1180 def __eq__(self, other):
1181 if isinstance(other, ImplementsLessThan):
1182 return self.value == other.value
1183 return False
1184 def __lt__(self, other):
1185 if isinstance(other, ImplementsLessThan):
1186 return self.value < other.value
1187 return NotImplemented
1188
1189 @functools.total_ordering
1190 class ImplementsGreaterThan:
1191 def __init__(self, value):
1192 self.value = value
1193 def __eq__(self, other):
1194 if isinstance(other, ImplementsGreaterThan):
1195 return self.value == other.value
1196 return False
1197 def __gt__(self, other):
1198 if isinstance(other, ImplementsGreaterThan):
1199 return self.value > other.value
1200 return NotImplemented
1201
1202 @functools.total_ordering
1203 class ImplementsLessThanEqualTo:
1204 def __init__(self, value):
1205 self.value = value
1206 def __eq__(self, other):
1207 if isinstance(other, ImplementsLessThanEqualTo):
1208 return self.value == other.value
1209 return False
1210 def __le__(self, other):
1211 if isinstance(other, ImplementsLessThanEqualTo):
1212 return self.value <= other.value
1213 return NotImplemented
1214
1215 @functools.total_ordering
1216 class ImplementsGreaterThanEqualTo:
1217 def __init__(self, value):
1218 self.value = value
1219 def __eq__(self, other):
1220 if isinstance(other, ImplementsGreaterThanEqualTo):
1221 return self.value == other.value
1222 return False
1223 def __ge__(self, other):
1224 if isinstance(other, ImplementsGreaterThanEqualTo):
1225 return self.value >= other.value
1226 return NotImplemented
1227
1228 @functools.total_ordering
1229 class ComparatorNotImplemented:
1230 def __init__(self, value):
1231 self.value = value
1232 def __eq__(self, other):
1233 if isinstance(other, ComparatorNotImplemented):
1234 return self.value == other.value
1235 return False
1236 def __lt__(self, other):
1237 return NotImplemented
1238
1239 with self.subTest("LT < 1"), self.assertRaises(TypeError):
1240 ImplementsLessThan(-1) < 1
1241
1242 with self.subTest("LT < LE"), self.assertRaises(TypeError):
1243 ImplementsLessThan(0) < ImplementsLessThanEqualTo(0)
1244
1245 with self.subTest("LT < GT"), self.assertRaises(TypeError):
1246 ImplementsLessThan(1) < ImplementsGreaterThan(1)
1247
1248 with self.subTest("LE <= LT"), self.assertRaises(TypeError):
1249 ImplementsLessThanEqualTo(2) <= ImplementsLessThan(2)
1250
1251 with self.subTest("LE <= GE"), self.assertRaises(TypeError):
1252 ImplementsLessThanEqualTo(3) <= ImplementsGreaterThanEqualTo(3)
1253
1254 with self.subTest("GT > GE"), self.assertRaises(TypeError):
1255 ImplementsGreaterThan(4) > ImplementsGreaterThanEqualTo(4)
1256
1257 with self.subTest("GT > LT"), self.assertRaises(TypeError):
1258 ImplementsGreaterThan(5) > ImplementsLessThan(5)
1259
1260 with self.subTest("GE >= GT"), self.assertRaises(TypeError):
1261 ImplementsGreaterThanEqualTo(6) >= ImplementsGreaterThan(6)
1262
1263 with self.subTest("GE >= LE"), self.assertRaises(TypeError):
1264 ImplementsGreaterThanEqualTo(7) >= ImplementsLessThanEqualTo(7)
1265
1266 with self.subTest("GE when equal"):
1267 a = ComparatorNotImplemented(8)
1268 b = ComparatorNotImplemented(8)
1269 self.assertEqual(a, b)
1270 with self.assertRaises(TypeError):
1271 a >= b
1272
1273 with self.subTest("LE when equal"):
1274 a = ComparatorNotImplemented(9)
1275 b = ComparatorNotImplemented(9)
1276 self.assertEqual(a, b)
1277 with self.assertRaises(TypeError):
1278 a <= b
1279
1280 def test_pickle(self):
1281 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1282 for name in '__lt__', '__gt__', '__le__', '__ge__':
1283 with self.subTest(method=name, proto=proto):
1284 method = getattr(Orderable_LT, name)
1285 method_copy = pickle.loads(pickle.dumps(method, proto))
1286 self.assertIs(method_copy, method)
1287
1288
1289 def test_total_ordering_for_metaclasses_issue_44605(self):
1290
1291 @functools.total_ordering
1292 class SortableMeta(type):
1293 def __new__(cls, name, bases, ns):
1294 return super().__new__(cls, name, bases, ns)
1295
1296 def __lt__(self, other):
1297 if not isinstance(other, SortableMeta):
1298 pass
1299 return self.__name__ < other.__name__
1300
1301 def __eq__(self, other):
1302 if not isinstance(other, SortableMeta):
1303 pass
1304 return self.__name__ == other.__name__
1305
1306 class B(metaclass=SortableMeta):
1307 pass
1308
1309 class A(metaclass=SortableMeta):
1310 pass
1311
1312 self.assertTrue(A < B)
1313 self.assertFalse(A > B)
1314
1315
1316 @functools.total_ordering
1317 class Orderable_LT:
1318 def __init__(self, value):
1319 self.value = value
1320 def __lt__(self, other):
1321 return self.value < other.value
1322 def __eq__(self, other):
1323 return self.value == other.value
1324
1325
1326 class TestCache:
1327 # This tests that the pass-through is working as designed.
1328 # The underlying functionality is tested in TestLRU.
1329
1330 def test_cache(self):
1331 @self.module.cache
1332 def fib(n):
1333 if n < 2:
1334 return n
1335 return fib(n-1) + fib(n-2)
1336 self.assertEqual([fib(n) for n in range(16)],
1337 [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610])
1338 self.assertEqual(fib.cache_info(),
1339 self.module._CacheInfo(hits=28, misses=16, maxsize=None, currsize=16))
1340 fib.cache_clear()
1341 self.assertEqual(fib.cache_info(),
1342 self.module._CacheInfo(hits=0, misses=0, maxsize=None, currsize=0))
1343
1344
1345 class TestCachePy(TestCache, unittest.TestCase):
1346 module = py_functools
1347
1348
1349 @unittest.skipUnless(c_functools, 'requires the C _functools module')
1350 class TestCacheC(TestCache, unittest.TestCase):
1351 if c_functools:
1352 module = c_functools
1353
1354
1355 class TestLRU:
1356
1357 def test_lru(self):
1358 def orig(x, y):
1359 return 3 * x + y
1360 f = self.module.lru_cache(maxsize=20)(orig)
1361 hits, misses, maxsize, currsize = f.cache_info()
1362 self.assertEqual(maxsize, 20)
1363 self.assertEqual(currsize, 0)
1364 self.assertEqual(hits, 0)
1365 self.assertEqual(misses, 0)
1366
1367 domain = range(5)
1368 for i in range(1000):
1369 x, y = choice(domain), choice(domain)
1370 actual = f(x, y)
1371 expected = orig(x, y)
1372 self.assertEqual(actual, expected)
1373 hits, misses, maxsize, currsize = f.cache_info()
1374 self.assertTrue(hits > misses)
1375 self.assertEqual(hits + misses, 1000)
1376 self.assertEqual(currsize, 20)
1377
1378 f.cache_clear() # test clearing
1379 hits, misses, maxsize, currsize = f.cache_info()
1380 self.assertEqual(hits, 0)
1381 self.assertEqual(misses, 0)
1382 self.assertEqual(currsize, 0)
1383 f(x, y)
1384 hits, misses, maxsize, currsize = f.cache_info()
1385 self.assertEqual(hits, 0)
1386 self.assertEqual(misses, 1)
1387 self.assertEqual(currsize, 1)
1388
1389 # Test bypassing the cache
1390 self.assertIs(f.__wrapped__, orig)
1391 f.__wrapped__(x, y)
1392 hits, misses, maxsize, currsize = f.cache_info()
1393 self.assertEqual(hits, 0)
1394 self.assertEqual(misses, 1)
1395 self.assertEqual(currsize, 1)
1396
1397 # test size zero (which means "never-cache")
1398 @self.module.lru_cache(0)
1399 def f():
1400 nonlocal f_cnt
1401 f_cnt += 1
1402 return 20
1403 self.assertEqual(f.cache_info().maxsize, 0)
1404 f_cnt = 0
1405 for i in range(5):
1406 self.assertEqual(f(), 20)
1407 self.assertEqual(f_cnt, 5)
1408 hits, misses, maxsize, currsize = f.cache_info()
1409 self.assertEqual(hits, 0)
1410 self.assertEqual(misses, 5)
1411 self.assertEqual(currsize, 0)
1412
1413 # test size one
1414 @self.module.lru_cache(1)
1415 def f():
1416 nonlocal f_cnt
1417 f_cnt += 1
1418 return 20
1419 self.assertEqual(f.cache_info().maxsize, 1)
1420 f_cnt = 0
1421 for i in range(5):
1422 self.assertEqual(f(), 20)
1423 self.assertEqual(f_cnt, 1)
1424 hits, misses, maxsize, currsize = f.cache_info()
1425 self.assertEqual(hits, 4)
1426 self.assertEqual(misses, 1)
1427 self.assertEqual(currsize, 1)
1428
1429 # test size two
1430 @self.module.lru_cache(2)
1431 def f(x):
1432 nonlocal f_cnt
1433 f_cnt += 1
1434 return x*10
1435 self.assertEqual(f.cache_info().maxsize, 2)
1436 f_cnt = 0
1437 for x in 7, 9, 7, 9, 7, 9, 8, 8, 8, 9, 9, 9, 8, 8, 8, 7:
1438 # * * * *
1439 self.assertEqual(f(x), x*10)
1440 self.assertEqual(f_cnt, 4)
1441 hits, misses, maxsize, currsize = f.cache_info()
1442 self.assertEqual(hits, 12)
1443 self.assertEqual(misses, 4)
1444 self.assertEqual(currsize, 2)
1445
1446 def test_lru_no_args(self):
1447 @self.module.lru_cache
1448 def square(x):
1449 return x ** 2
1450
1451 self.assertEqual(list(map(square, [10, 20, 10])),
1452 [100, 400, 100])
1453 self.assertEqual(square.cache_info().hits, 1)
1454 self.assertEqual(square.cache_info().misses, 2)
1455 self.assertEqual(square.cache_info().maxsize, 128)
1456 self.assertEqual(square.cache_info().currsize, 2)
1457
1458 def test_lru_bug_35780(self):
1459 # C version of the lru_cache was not checking to see if
1460 # the user function call has already modified the cache
1461 # (this arises in recursive calls and in multi-threading).
1462 # This cause the cache to have orphan links not referenced
1463 # by the cache dictionary.
1464
1465 once = True # Modified by f(x) below
1466
1467 @self.module.lru_cache(maxsize=10)
1468 def f(x):
1469 nonlocal once
1470 rv = f'.{x}.'
1471 if x == 20 and once:
1472 once = False
1473 rv = f(x)
1474 return rv
1475
1476 # Fill the cache
1477 for x in range(15):
1478 self.assertEqual(f(x), f'.{x}.')
1479 self.assertEqual(f.cache_info().currsize, 10)
1480
1481 # Make a recursive call and make sure the cache remains full
1482 self.assertEqual(f(20), '.20.')
1483 self.assertEqual(f.cache_info().currsize, 10)
1484
1485 def test_lru_bug_36650(self):
1486 # C version of lru_cache was treating a call with an empty **kwargs
1487 # dictionary as being distinct from a call with no keywords at all.
1488 # This did not result in an incorrect answer, but it did trigger
1489 # an unexpected cache miss.
1490
1491 @self.module.lru_cache()
1492 def f(x):
1493 pass
1494
1495 f(0)
1496 f(0, **{})
1497 self.assertEqual(f.cache_info().hits, 1)
1498
1499 def test_lru_hash_only_once(self):
1500 # To protect against weird reentrancy bugs and to improve
1501 # efficiency when faced with slow __hash__ methods, the
1502 # LRU cache guarantees that it will only call __hash__
1503 # only once per use as an argument to the cached function.
1504
1505 @self.module.lru_cache(maxsize=1)
1506 def f(x, y):
1507 return x * 3 + y
1508
1509 # Simulate the integer 5
1510 mock_int = unittest.mock.Mock()
1511 mock_int.__mul__ = unittest.mock.Mock(return_value=15)
1512 mock_int.__hash__ = unittest.mock.Mock(return_value=999)
1513
1514 # Add to cache: One use as an argument gives one call
1515 self.assertEqual(f(mock_int, 1), 16)
1516 self.assertEqual(mock_int.__hash__.call_count, 1)
1517 self.assertEqual(f.cache_info(), (0, 1, 1, 1))
1518
1519 # Cache hit: One use as an argument gives one additional call
1520 self.assertEqual(f(mock_int, 1), 16)
1521 self.assertEqual(mock_int.__hash__.call_count, 2)
1522 self.assertEqual(f.cache_info(), (1, 1, 1, 1))
1523
1524 # Cache eviction: No use as an argument gives no additional call
1525 self.assertEqual(f(6, 2), 20)
1526 self.assertEqual(mock_int.__hash__.call_count, 2)
1527 self.assertEqual(f.cache_info(), (1, 2, 1, 1))
1528
1529 # Cache miss: One use as an argument gives one additional call
1530 self.assertEqual(f(mock_int, 1), 16)
1531 self.assertEqual(mock_int.__hash__.call_count, 3)
1532 self.assertEqual(f.cache_info(), (1, 3, 1, 1))
1533
1534 def test_lru_reentrancy_with_len(self):
1535 # Test to make sure the LRU cache code isn't thrown-off by
1536 # caching the built-in len() function. Since len() can be
1537 # cached, we shouldn't use it inside the lru code itself.
1538 old_len = builtins.len
1539 try:
1540 builtins.len = self.module.lru_cache(4)(len)
1541 for i in [0, 0, 1, 2, 3, 3, 4, 5, 6, 1, 7, 2, 1]:
1542 self.assertEqual(len('abcdefghijklmn'[:i]), i)
1543 finally:
1544 builtins.len = old_len
1545
1546 def test_lru_star_arg_handling(self):
1547 # Test regression that arose in ea064ff3c10f
1548 @self.module.lru_cache()
1549 def f(*args):
1550 return args
1551
1552 self.assertEqual(f(1, 2), (1, 2))
1553 self.assertEqual(f((1, 2)), ((1, 2),))
1554
1555 def test_lru_type_error(self):
1556 # Regression test for issue #28653.
1557 # lru_cache was leaking when one of the arguments
1558 # wasn't cacheable.
1559
1560 @self.module.lru_cache(maxsize=None)
1561 def infinite_cache(o):
1562 pass
1563
1564 @self.module.lru_cache(maxsize=10)
1565 def limited_cache(o):
1566 pass
1567
1568 with self.assertRaises(TypeError):
1569 infinite_cache([])
1570
1571 with self.assertRaises(TypeError):
1572 limited_cache([])
1573
1574 def test_lru_with_maxsize_none(self):
1575 @self.module.lru_cache(maxsize=None)
1576 def fib(n):
1577 if n < 2:
1578 return n
1579 return fib(n-1) + fib(n-2)
1580 self.assertEqual([fib(n) for n in range(16)],
1581 [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610])
1582 self.assertEqual(fib.cache_info(),
1583 self.module._CacheInfo(hits=28, misses=16, maxsize=None, currsize=16))
1584 fib.cache_clear()
1585 self.assertEqual(fib.cache_info(),
1586 self.module._CacheInfo(hits=0, misses=0, maxsize=None, currsize=0))
1587
1588 def test_lru_with_maxsize_negative(self):
1589 @self.module.lru_cache(maxsize=-10)
1590 def eq(n):
1591 return n
1592 for i in (0, 1):
1593 self.assertEqual([eq(n) for n in range(150)], list(range(150)))
1594 self.assertEqual(eq.cache_info(),
1595 self.module._CacheInfo(hits=0, misses=300, maxsize=0, currsize=0))
1596
1597 def test_lru_with_exceptions(self):
1598 # Verify that user_function exceptions get passed through without
1599 # creating a hard-to-read chained exception.
1600 # http://bugs.python.org/issue13177
1601 for maxsize in (None, 128):
1602 @self.module.lru_cache(maxsize)
1603 def func(i):
1604 return 'abc'[i]
1605 self.assertEqual(func(0), 'a')
1606 with self.assertRaises(IndexError) as cm:
1607 func(15)
1608 self.assertIsNone(cm.exception.__context__)
1609 # Verify that the previous exception did not result in a cached entry
1610 with self.assertRaises(IndexError):
1611 func(15)
1612
1613 def test_lru_with_types(self):
1614 for maxsize in (None, 128):
1615 @self.module.lru_cache(maxsize=maxsize, typed=True)
1616 def square(x):
1617 return x * x
1618 self.assertEqual(square(3), 9)
1619 self.assertEqual(type(square(3)), type(9))
1620 self.assertEqual(square(3.0), 9.0)
1621 self.assertEqual(type(square(3.0)), type(9.0))
1622 self.assertEqual(square(x=3), 9)
1623 self.assertEqual(type(square(x=3)), type(9))
1624 self.assertEqual(square(x=3.0), 9.0)
1625 self.assertEqual(type(square(x=3.0)), type(9.0))
1626 self.assertEqual(square.cache_info().hits, 4)
1627 self.assertEqual(square.cache_info().misses, 4)
1628
1629 def test_lru_cache_typed_is_not_recursive(self):
1630 cached = self.module.lru_cache(typed=True)(repr)
1631
1632 self.assertEqual(cached(1), '1')
1633 self.assertEqual(cached(True), 'True')
1634 self.assertEqual(cached(1.0), '1.0')
1635 self.assertEqual(cached(0), '0')
1636 self.assertEqual(cached(False), 'False')
1637 self.assertEqual(cached(0.0), '0.0')
1638
1639 self.assertEqual(cached((1,)), '(1,)')
1640 self.assertEqual(cached((True,)), '(1,)')
1641 self.assertEqual(cached((1.0,)), '(1,)')
1642 self.assertEqual(cached((0,)), '(0,)')
1643 self.assertEqual(cached((False,)), '(0,)')
1644 self.assertEqual(cached((0.0,)), '(0,)')
1645
1646 class T(tuple):
1647 pass
1648
1649 self.assertEqual(cached(T((1,))), '(1,)')
1650 self.assertEqual(cached(T((True,))), '(1,)')
1651 self.assertEqual(cached(T((1.0,))), '(1,)')
1652 self.assertEqual(cached(T((0,))), '(0,)')
1653 self.assertEqual(cached(T((False,))), '(0,)')
1654 self.assertEqual(cached(T((0.0,))), '(0,)')
1655
1656 def test_lru_with_keyword_args(self):
1657 @self.module.lru_cache()
1658 def fib(n):
1659 if n < 2:
1660 return n
1661 return fib(n=n-1) + fib(n=n-2)
1662 self.assertEqual(
1663 [fib(n=number) for number in range(16)],
1664 [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]
1665 )
1666 self.assertEqual(fib.cache_info(),
1667 self.module._CacheInfo(hits=28, misses=16, maxsize=128, currsize=16))
1668 fib.cache_clear()
1669 self.assertEqual(fib.cache_info(),
1670 self.module._CacheInfo(hits=0, misses=0, maxsize=128, currsize=0))
1671
1672 def test_lru_with_keyword_args_maxsize_none(self):
1673 @self.module.lru_cache(maxsize=None)
1674 def fib(n):
1675 if n < 2:
1676 return n
1677 return fib(n=n-1) + fib(n=n-2)
1678 self.assertEqual([fib(n=number) for number in range(16)],
1679 [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610])
1680 self.assertEqual(fib.cache_info(),
1681 self.module._CacheInfo(hits=28, misses=16, maxsize=None, currsize=16))
1682 fib.cache_clear()
1683 self.assertEqual(fib.cache_info(),
1684 self.module._CacheInfo(hits=0, misses=0, maxsize=None, currsize=0))
1685
1686 def test_kwargs_order(self):
1687 # PEP 468: Preserving Keyword Argument Order
1688 @self.module.lru_cache(maxsize=10)
1689 def f(**kwargs):
1690 return list(kwargs.items())
1691 self.assertEqual(f(a=1, b=2), [('a', 1), ('b', 2)])
1692 self.assertEqual(f(b=2, a=1), [('b', 2), ('a', 1)])
1693 self.assertEqual(f.cache_info(),
1694 self.module._CacheInfo(hits=0, misses=2, maxsize=10, currsize=2))
1695
1696 def test_lru_cache_decoration(self):
1697 def f(zomg: 'zomg_annotation'):
1698 """f doc string"""
1699 return 42
1700 g = self.module.lru_cache()(f)
1701 for attr in self.module.WRAPPER_ASSIGNMENTS:
1702 self.assertEqual(getattr(g, attr), getattr(f, attr))
1703
1704 @threading_helper.requires_working_threading()
1705 def test_lru_cache_threaded(self):
1706 n, m = 5, 11
1707 def orig(x, y):
1708 return 3 * x + y
1709 f = self.module.lru_cache(maxsize=n*m)(orig)
1710 hits, misses, maxsize, currsize = f.cache_info()
1711 self.assertEqual(currsize, 0)
1712
1713 start = threading.Event()
1714 def full(k):
1715 start.wait(10)
1716 for _ in range(m):
1717 self.assertEqual(f(k, 0), orig(k, 0))
1718
1719 def clear():
1720 start.wait(10)
1721 for _ in range(2*m):
1722 f.cache_clear()
1723
1724 orig_si = sys.getswitchinterval()
1725 support.setswitchinterval(1e-6)
1726 try:
1727 # create n threads in order to fill cache
1728 threads = [threading.Thread(target=full, args=[k])
1729 for k in range(n)]
1730 with threading_helper.start_threads(threads):
1731 start.set()
1732
1733 hits, misses, maxsize, currsize = f.cache_info()
1734 if self.module is py_functools:
1735 # XXX: Why can be not equal?
1736 self.assertLessEqual(misses, n)
1737 self.assertLessEqual(hits, m*n - misses)
1738 else:
1739 self.assertEqual(misses, n)
1740 self.assertEqual(hits, m*n - misses)
1741 self.assertEqual(currsize, n)
1742
1743 # create n threads in order to fill cache and 1 to clear it
1744 threads = [threading.Thread(target=clear)]
1745 threads += [threading.Thread(target=full, args=[k])
1746 for k in range(n)]
1747 start.clear()
1748 with threading_helper.start_threads(threads):
1749 start.set()
1750 finally:
1751 sys.setswitchinterval(orig_si)
1752
1753 @threading_helper.requires_working_threading()
1754 def test_lru_cache_threaded2(self):
1755 # Simultaneous call with the same arguments
1756 n, m = 5, 7
1757 start = threading.Barrier(n+1)
1758 pause = threading.Barrier(n+1)
1759 stop = threading.Barrier(n+1)
1760 @self.module.lru_cache(maxsize=m*n)
1761 def f(x):
1762 pause.wait(10)
1763 return 3 * x
1764 self.assertEqual(f.cache_info(), (0, 0, m*n, 0))
1765 def test():
1766 for i in range(m):
1767 start.wait(10)
1768 self.assertEqual(f(i), 3 * i)
1769 stop.wait(10)
1770 threads = [threading.Thread(target=test) for k in range(n)]
1771 with threading_helper.start_threads(threads):
1772 for i in range(m):
1773 start.wait(10)
1774 stop.reset()
1775 pause.wait(10)
1776 start.reset()
1777 stop.wait(10)
1778 pause.reset()
1779 self.assertEqual(f.cache_info(), (0, (i+1)*n, m*n, i+1))
1780
1781 @threading_helper.requires_working_threading()
1782 def test_lru_cache_threaded3(self):
1783 @self.module.lru_cache(maxsize=2)
1784 def f(x):
1785 time.sleep(.01)
1786 return 3 * x
1787 def test(i, x):
1788 self.assertEqual(f(x), 3 * x, i)
1789 threads = [threading.Thread(target=test, args=(i, v))
1790 for i, v in enumerate([1, 2, 2, 3, 2])]
1791 with threading_helper.start_threads(threads):
1792 pass
1793
1794 def test_need_for_rlock(self):
1795 # This will deadlock on an LRU cache that uses a regular lock
1796
1797 @self.module.lru_cache(maxsize=10)
1798 def test_func(x):
1799 'Used to demonstrate a reentrant lru_cache call within a single thread'
1800 return x
1801
1802 class DoubleEq:
1803 'Demonstrate a reentrant lru_cache call within a single thread'
1804 def __init__(self, x):
1805 self.x = x
1806 def __hash__(self):
1807 return self.x
1808 def __eq__(self, other):
1809 if self.x == 2:
1810 test_func(DoubleEq(1))
1811 return self.x == other.x
1812
1813 test_func(DoubleEq(1)) # Load the cache
1814 test_func(DoubleEq(2)) # Load the cache
1815 self.assertEqual(test_func(DoubleEq(2)), # Trigger a re-entrant __eq__ call
1816 DoubleEq(2)) # Verify the correct return value
1817
1818 def test_lru_method(self):
1819 class X(int):
1820 f_cnt = 0
1821 @self.module.lru_cache(2)
1822 def f(self, x):
1823 self.f_cnt += 1
1824 return x*10+self
1825 a = X(5)
1826 b = X(5)
1827 c = X(7)
1828 self.assertEqual(X.f.cache_info(), (0, 0, 2, 0))
1829
1830 for x in 1, 2, 2, 3, 1, 1, 1, 2, 3, 3:
1831 self.assertEqual(a.f(x), x*10 + 5)
1832 self.assertEqual((a.f_cnt, b.f_cnt, c.f_cnt), (6, 0, 0))
1833 self.assertEqual(X.f.cache_info(), (4, 6, 2, 2))
1834
1835 for x in 1, 2, 1, 1, 1, 1, 3, 2, 2, 2:
1836 self.assertEqual(b.f(x), x*10 + 5)
1837 self.assertEqual((a.f_cnt, b.f_cnt, c.f_cnt), (6, 4, 0))
1838 self.assertEqual(X.f.cache_info(), (10, 10, 2, 2))
1839
1840 for x in 2, 1, 1, 1, 1, 2, 1, 3, 2, 1:
1841 self.assertEqual(c.f(x), x*10 + 7)
1842 self.assertEqual((a.f_cnt, b.f_cnt, c.f_cnt), (6, 4, 5))
1843 self.assertEqual(X.f.cache_info(), (15, 15, 2, 2))
1844
1845 self.assertEqual(a.f.cache_info(), X.f.cache_info())
1846 self.assertEqual(b.f.cache_info(), X.f.cache_info())
1847 self.assertEqual(c.f.cache_info(), X.f.cache_info())
1848
1849 def test_pickle(self):
1850 cls = self.__class__
1851 for f in cls.cached_func[0], cls.cached_meth, cls.cached_staticmeth:
1852 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1853 with self.subTest(proto=proto, func=f):
1854 f_copy = pickle.loads(pickle.dumps(f, proto))
1855 self.assertIs(f_copy, f)
1856
1857 def test_copy(self):
1858 cls = self.__class__
1859 def orig(x, y):
1860 return 3 * x + y
1861 part = self.module.partial(orig, 2)
1862 funcs = (cls.cached_func[0], cls.cached_meth, cls.cached_staticmeth,
1863 self.module.lru_cache(2)(part))
1864 for f in funcs:
1865 with self.subTest(func=f):
1866 f_copy = copy.copy(f)
1867 self.assertIs(f_copy, f)
1868
1869 def test_deepcopy(self):
1870 cls = self.__class__
1871 def orig(x, y):
1872 return 3 * x + y
1873 part = self.module.partial(orig, 2)
1874 funcs = (cls.cached_func[0], cls.cached_meth, cls.cached_staticmeth,
1875 self.module.lru_cache(2)(part))
1876 for f in funcs:
1877 with self.subTest(func=f):
1878 f_copy = copy.deepcopy(f)
1879 self.assertIs(f_copy, f)
1880
1881 def test_lru_cache_parameters(self):
1882 @self.module.lru_cache(maxsize=2)
1883 def f():
1884 return 1
1885 self.assertEqual(f.cache_parameters(), {'maxsize': 2, "typed": False})
1886
1887 @self.module.lru_cache(maxsize=1000, typed=True)
1888 def f():
1889 return 1
1890 self.assertEqual(f.cache_parameters(), {'maxsize': 1000, "typed": True})
1891
1892 @support.suppress_immortalization()
1893 def test_lru_cache_weakrefable(self):
1894 @self.module.lru_cache
1895 def test_function(x):
1896 return x
1897
1898 class A:
1899 @self.module.lru_cache
1900 def test_method(self, x):
1901 return (self, x)
1902
1903 @staticmethod
1904 @self.module.lru_cache
1905 def test_staticmethod(x):
1906 return (self, x)
1907
1908 refs = [weakref.ref(test_function),
1909 weakref.ref(A.test_method),
1910 weakref.ref(A.test_staticmethod)]
1911
1912 for ref in refs:
1913 self.assertIsNotNone(ref())
1914
1915 del A
1916 del test_function
1917 gc.collect()
1918
1919 for ref in refs:
1920 self.assertIsNone(ref())
1921
1922 def test_common_signatures(self):
1923 def orig(a, /, b, c=True): ...
1924 lru = self.module.lru_cache(1)(orig)
1925
1926 self.assertEqual(str(Signature.from_callable(lru)), '(a, /, b, c=True)')
1927 self.assertEqual(str(Signature.from_callable(lru.cache_info)), '()')
1928 self.assertEqual(str(Signature.from_callable(lru.cache_clear)), '()')
1929
1930 @support.skip_on_s390x
1931 @unittest.skipIf(support.is_wasi, "WASI has limited C stack")
1932 def test_lru_recursion(self):
1933
1934 @self.module.lru_cache
1935 def fib(n):
1936 if n <= 1:
1937 return n
1938 return fib(n-1) + fib(n-2)
1939
1940 if not support.Py_DEBUG:
1941 depth = support.get_c_recursion_limit()*2//7
1942 with support.infinite_recursion():
1943 fib(depth)
1944 if self.module == c_functools:
1945 fib.cache_clear()
1946 with support.infinite_recursion():
1947 with self.assertRaises(RecursionError):
1948 fib(10000)
1949
1950
1951 @py_functools.lru_cache()
1952 def py_cached_func(x, y):
1953 return 3 * x + y
1954
1955 if c_functools:
1956 @c_functools.lru_cache()
1957 def c_cached_func(x, y):
1958 return 3 * x + y
1959
1960
1961 class TestLRUPy(TestLRU, unittest.TestCase):
1962 module = py_functools
1963 cached_func = py_cached_func,
1964
1965 @module.lru_cache()
1966 def cached_meth(self, x, y):
1967 return 3 * x + y
1968
1969 @staticmethod
1970 @module.lru_cache()
1971 def cached_staticmeth(x, y):
1972 return 3 * x + y
1973
1974
1975 @unittest.skipUnless(c_functools, 'requires the C _functools module')
1976 class TestLRUC(TestLRU, unittest.TestCase):
1977 if c_functools:
1978 module = c_functools
1979 cached_func = c_cached_func,
1980
1981 @module.lru_cache()
1982 def cached_meth(self, x, y):
1983 return 3 * x + y
1984
1985 @staticmethod
1986 @module.lru_cache()
1987 def cached_staticmeth(x, y):
1988 return 3 * x + y
1989
1990
1991 class TestSingleDispatch(unittest.TestCase):
1992 def test_simple_overloads(self):
1993 @functools.singledispatch
1994 def g(obj):
1995 return "base"
1996 def g_int(i):
1997 return "integer"
1998 g.register(int, g_int)
1999 self.assertEqual(g("str"), "base")
2000 self.assertEqual(g(1), "integer")
2001 self.assertEqual(g([1,2,3]), "base")
2002
2003 def test_mro(self):
2004 @functools.singledispatch
2005 def g(obj):
2006 return "base"
2007 class A:
2008 pass
2009 class C(A):
2010 pass
2011 class B(A):
2012 pass
2013 class D(C, B):
2014 pass
2015 def g_A(a):
2016 return "A"
2017 def g_B(b):
2018 return "B"
2019 g.register(A, g_A)
2020 g.register(B, g_B)
2021 self.assertEqual(g(A()), "A")
2022 self.assertEqual(g(B()), "B")
2023 self.assertEqual(g(C()), "A")
2024 self.assertEqual(g(D()), "B")
2025
2026 def test_register_decorator(self):
2027 @functools.singledispatch
2028 def g(obj):
2029 return "base"
2030 @g.register(int)
2031 def g_int(i):
2032 return "int %s" % (i,)
2033 self.assertEqual(g(""), "base")
2034 self.assertEqual(g(12), "int 12")
2035 self.assertIs(g.dispatch(int), g_int)
2036 self.assertIs(g.dispatch(object), g.dispatch(str))
2037 # Note: in the assert above this is not g.
2038 # @singledispatch returns the wrapper.
2039
2040 def test_wrapping_attributes(self):
2041 @functools.singledispatch
2042 def g(obj):
2043 "Simple test"
2044 return "Test"
2045 self.assertEqual(g.__name__, "g")
2046 if sys.flags.optimize < 2:
2047 self.assertEqual(g.__doc__, "Simple test")
2048
2049 @unittest.skipUnless(decimal, 'requires _decimal')
2050 @support.cpython_only
2051 def test_c_classes(self):
2052 @functools.singledispatch
2053 def g(obj):
2054 return "base"
2055 @g.register(decimal.DecimalException)
2056 def _(obj):
2057 return obj.args
2058 subn = decimal.Subnormal("Exponent < Emin")
2059 rnd = decimal.Rounded("Number got rounded")
2060 self.assertEqual(g(subn), ("Exponent < Emin",))
2061 self.assertEqual(g(rnd), ("Number got rounded",))
2062 @g.register(decimal.Subnormal)
2063 def _(obj):
2064 return "Too small to care."
2065 self.assertEqual(g(subn), "Too small to care.")
2066 self.assertEqual(g(rnd), ("Number got rounded",))
2067
2068 def test_compose_mro(self):
2069 # None of the examples in this test depend on haystack ordering.
2070 c = collections.abc
2071 mro = functools._compose_mro
2072 bases = [c.Sequence, c.MutableMapping, c.Mapping, c.Set]
2073 for haystack in permutations(bases):
2074 m = mro(dict, haystack)
2075 self.assertEqual(m, [dict, c.MutableMapping, c.Mapping,
2076 c.Collection, c.Sized, c.Iterable,
2077 c.Container, object])
2078 bases = [c.Container, c.Mapping, c.MutableMapping, collections.OrderedDict]
2079 for haystack in permutations(bases):
2080 m = mro(collections.ChainMap, haystack)
2081 self.assertEqual(m, [collections.ChainMap, c.MutableMapping, c.Mapping,
2082 c.Collection, c.Sized, c.Iterable,
2083 c.Container, object])
2084
2085 # If there's a generic function with implementations registered for
2086 # both Sized and Container, passing a defaultdict to it results in an
2087 # ambiguous dispatch which will cause a RuntimeError (see
2088 # test_mro_conflicts).
2089 bases = [c.Container, c.Sized, str]
2090 for haystack in permutations(bases):
2091 m = mro(collections.defaultdict, [c.Sized, c.Container, str])
2092 self.assertEqual(m, [collections.defaultdict, dict, c.Sized,
2093 c.Container, object])
2094
2095 # MutableSequence below is registered directly on D. In other words, it
2096 # precedes MutableMapping which means single dispatch will always
2097 # choose MutableSequence here.
2098 class D(collections.defaultdict):
2099 pass
2100 c.MutableSequence.register(D)
2101 bases = [c.MutableSequence, c.MutableMapping]
2102 for haystack in permutations(bases):
2103 m = mro(D, haystack)
2104 self.assertEqual(m, [D, c.MutableSequence, c.Sequence, c.Reversible,
2105 collections.defaultdict, dict, c.MutableMapping, c.Mapping,
2106 c.Collection, c.Sized, c.Iterable, c.Container,
2107 object])
2108
2109 # Container and Callable are registered on different base classes and
2110 # a generic function supporting both should always pick the Callable
2111 # implementation if a C instance is passed.
2112 class C(collections.defaultdict):
2113 def __call__(self):
2114 pass
2115 bases = [c.Sized, c.Callable, c.Container, c.Mapping]
2116 for haystack in permutations(bases):
2117 m = mro(C, haystack)
2118 self.assertEqual(m, [C, c.Callable, collections.defaultdict, dict, c.Mapping,
2119 c.Collection, c.Sized, c.Iterable,
2120 c.Container, object])
2121
2122 def test_register_abc(self):
2123 c = collections.abc
2124 d = {"a": "b"}
2125 l = [1, 2, 3]
2126 s = {object(), None}
2127 f = frozenset(s)
2128 t = (1, 2, 3)
2129 @functools.singledispatch
2130 def g(obj):
2131 return "base"
2132 self.assertEqual(g(d), "base")
2133 self.assertEqual(g(l), "base")
2134 self.assertEqual(g(s), "base")
2135 self.assertEqual(g(f), "base")
2136 self.assertEqual(g(t), "base")
2137 g.register(c.Sized, lambda obj: "sized")
2138 self.assertEqual(g(d), "sized")
2139 self.assertEqual(g(l), "sized")
2140 self.assertEqual(g(s), "sized")
2141 self.assertEqual(g(f), "sized")
2142 self.assertEqual(g(t), "sized")
2143 g.register(c.MutableMapping, lambda obj: "mutablemapping")
2144 self.assertEqual(g(d), "mutablemapping")
2145 self.assertEqual(g(l), "sized")
2146 self.assertEqual(g(s), "sized")
2147 self.assertEqual(g(f), "sized")
2148 self.assertEqual(g(t), "sized")
2149 g.register(collections.ChainMap, lambda obj: "chainmap")
2150 self.assertEqual(g(d), "mutablemapping") # irrelevant ABCs registered
2151 self.assertEqual(g(l), "sized")
2152 self.assertEqual(g(s), "sized")
2153 self.assertEqual(g(f), "sized")
2154 self.assertEqual(g(t), "sized")
2155 g.register(c.MutableSequence, lambda obj: "mutablesequence")
2156 self.assertEqual(g(d), "mutablemapping")
2157 self.assertEqual(g(l), "mutablesequence")
2158 self.assertEqual(g(s), "sized")
2159 self.assertEqual(g(f), "sized")
2160 self.assertEqual(g(t), "sized")
2161 g.register(c.MutableSet, lambda obj: "mutableset")
2162 self.assertEqual(g(d), "mutablemapping")
2163 self.assertEqual(g(l), "mutablesequence")
2164 self.assertEqual(g(s), "mutableset")
2165 self.assertEqual(g(f), "sized")
2166 self.assertEqual(g(t), "sized")
2167 g.register(c.Mapping, lambda obj: "mapping")
2168 self.assertEqual(g(d), "mutablemapping") # not specific enough
2169 self.assertEqual(g(l), "mutablesequence")
2170 self.assertEqual(g(s), "mutableset")
2171 self.assertEqual(g(f), "sized")
2172 self.assertEqual(g(t), "sized")
2173 g.register(c.Sequence, lambda obj: "sequence")
2174 self.assertEqual(g(d), "mutablemapping")
2175 self.assertEqual(g(l), "mutablesequence")
2176 self.assertEqual(g(s), "mutableset")
2177 self.assertEqual(g(f), "sized")
2178 self.assertEqual(g(t), "sequence")
2179 g.register(c.Set, lambda obj: "set")
2180 self.assertEqual(g(d), "mutablemapping")
2181 self.assertEqual(g(l), "mutablesequence")
2182 self.assertEqual(g(s), "mutableset")
2183 self.assertEqual(g(f), "set")
2184 self.assertEqual(g(t), "sequence")
2185 g.register(dict, lambda obj: "dict")
2186 self.assertEqual(g(d), "dict")
2187 self.assertEqual(g(l), "mutablesequence")
2188 self.assertEqual(g(s), "mutableset")
2189 self.assertEqual(g(f), "set")
2190 self.assertEqual(g(t), "sequence")
2191 g.register(list, lambda obj: "list")
2192 self.assertEqual(g(d), "dict")
2193 self.assertEqual(g(l), "list")
2194 self.assertEqual(g(s), "mutableset")
2195 self.assertEqual(g(f), "set")
2196 self.assertEqual(g(t), "sequence")
2197 g.register(set, lambda obj: "concrete-set")
2198 self.assertEqual(g(d), "dict")
2199 self.assertEqual(g(l), "list")
2200 self.assertEqual(g(s), "concrete-set")
2201 self.assertEqual(g(f), "set")
2202 self.assertEqual(g(t), "sequence")
2203 g.register(frozenset, lambda obj: "frozen-set")
2204 self.assertEqual(g(d), "dict")
2205 self.assertEqual(g(l), "list")
2206 self.assertEqual(g(s), "concrete-set")
2207 self.assertEqual(g(f), "frozen-set")
2208 self.assertEqual(g(t), "sequence")
2209 g.register(tuple, lambda obj: "tuple")
2210 self.assertEqual(g(d), "dict")
2211 self.assertEqual(g(l), "list")
2212 self.assertEqual(g(s), "concrete-set")
2213 self.assertEqual(g(f), "frozen-set")
2214 self.assertEqual(g(t), "tuple")
2215
2216 def test_c3_abc(self):
2217 c = collections.abc
2218 mro = functools._c3_mro
2219 class A(object):
2220 pass
2221 class B(A):
2222 def __len__(self):
2223 return 0 # implies Sized
2224 @c.Container.register
2225 class C(object):
2226 pass
2227 class D(object):
2228 pass # unrelated
2229 class X(D, C, B):
2230 def __call__(self):
2231 pass # implies Callable
2232 expected = [X, c.Callable, D, C, c.Container, B, c.Sized, A, object]
2233 for abcs in permutations([c.Sized, c.Callable, c.Container]):
2234 self.assertEqual(mro(X, abcs=abcs), expected)
2235 # unrelated ABCs don't appear in the resulting MRO
2236 many_abcs = [c.Mapping, c.Sized, c.Callable, c.Container, c.Iterable]
2237 self.assertEqual(mro(X, abcs=many_abcs), expected)
2238
2239 def test_false_meta(self):
2240 # see issue23572
2241 class MetaA(type):
2242 def __len__(self):
2243 return 0
2244 class A(metaclass=MetaA):
2245 pass
2246 class AA(A):
2247 pass
2248 @functools.singledispatch
2249 def fun(a):
2250 return 'base A'
2251 @fun.register(A)
2252 def _(a):
2253 return 'fun A'
2254 aa = AA()
2255 self.assertEqual(fun(aa), 'fun A')
2256
2257 def test_mro_conflicts(self):
2258 c = collections.abc
2259 @functools.singledispatch
2260 def g(arg):
2261 return "base"
2262 class O(c.Sized):
2263 def __len__(self):
2264 return 0
2265 o = O()
2266 self.assertEqual(g(o), "base")
2267 g.register(c.Iterable, lambda arg: "iterable")
2268 g.register(c.Container, lambda arg: "container")
2269 g.register(c.Sized, lambda arg: "sized")
2270 g.register(c.Set, lambda arg: "set")
2271 self.assertEqual(g(o), "sized")
2272 c.Iterable.register(O)
2273 self.assertEqual(g(o), "sized") # because it's explicitly in __mro__
2274 c.Container.register(O)
2275 self.assertEqual(g(o), "sized") # see above: Sized is in __mro__
2276 c.Set.register(O)
2277 self.assertEqual(g(o), "set") # because c.Set is a subclass of
2278 # c.Sized and c.Container
2279 class P:
2280 pass
2281 p = P()
2282 self.assertEqual(g(p), "base")
2283 c.Iterable.register(P)
2284 self.assertEqual(g(p), "iterable")
2285 c.Container.register(P)
2286 with self.assertRaises(RuntimeError) as re_one:
2287 g(p)
2288 self.assertIn(
2289 str(re_one.exception),
2290 (("Ambiguous dispatch: <class 'collections.abc.Container'> "
2291 "or <class 'collections.abc.Iterable'>"),
2292 ("Ambiguous dispatch: <class 'collections.abc.Iterable'> "
2293 "or <class 'collections.abc.Container'>")),
2294 )
2295 class Q(c.Sized):
2296 def __len__(self):
2297 return 0
2298 q = Q()
2299 self.assertEqual(g(q), "sized")
2300 c.Iterable.register(Q)
2301 self.assertEqual(g(q), "sized") # because it's explicitly in __mro__
2302 c.Set.register(Q)
2303 self.assertEqual(g(q), "set") # because c.Set is a subclass of
2304 # c.Sized and c.Iterable
2305 @functools.singledispatch
2306 def h(arg):
2307 return "base"
2308 @h.register(c.Sized)
2309 def _(arg):
2310 return "sized"
2311 @h.register(c.Container)
2312 def _(arg):
2313 return "container"
2314 # Even though Sized and Container are explicit bases of MutableMapping,
2315 # this ABC is implicitly registered on defaultdict which makes all of
2316 # MutableMapping's bases implicit as well from defaultdict's
2317 # perspective.
2318 with self.assertRaises(RuntimeError) as re_two:
2319 h(collections.defaultdict(lambda: 0))
2320 self.assertIn(
2321 str(re_two.exception),
2322 (("Ambiguous dispatch: <class 'collections.abc.Container'> "
2323 "or <class 'collections.abc.Sized'>"),
2324 ("Ambiguous dispatch: <class 'collections.abc.Sized'> "
2325 "or <class 'collections.abc.Container'>")),
2326 )
2327 class R(collections.defaultdict):
2328 pass
2329 c.MutableSequence.register(R)
2330 @functools.singledispatch
2331 def i(arg):
2332 return "base"
2333 @i.register(c.MutableMapping)
2334 def _(arg):
2335 return "mapping"
2336 @i.register(c.MutableSequence)
2337 def _(arg):
2338 return "sequence"
2339 r = R()
2340 self.assertEqual(i(r), "sequence")
2341 class S:
2342 pass
2343 class T(S, c.Sized):
2344 def __len__(self):
2345 return 0
2346 t = T()
2347 self.assertEqual(h(t), "sized")
2348 c.Container.register(T)
2349 self.assertEqual(h(t), "sized") # because it's explicitly in the MRO
2350 class U:
2351 def __len__(self):
2352 return 0
2353 u = U()
2354 self.assertEqual(h(u), "sized") # implicit Sized subclass inferred
2355 # from the existence of __len__()
2356 c.Container.register(U)
2357 # There is no preference for registered versus inferred ABCs.
2358 with self.assertRaises(RuntimeError) as re_three:
2359 h(u)
2360 self.assertIn(
2361 str(re_three.exception),
2362 (("Ambiguous dispatch: <class 'collections.abc.Container'> "
2363 "or <class 'collections.abc.Sized'>"),
2364 ("Ambiguous dispatch: <class 'collections.abc.Sized'> "
2365 "or <class 'collections.abc.Container'>")),
2366 )
2367 class V(c.Sized, S):
2368 def __len__(self):
2369 return 0
2370 @functools.singledispatch
2371 def j(arg):
2372 return "base"
2373 @j.register(S)
2374 def _(arg):
2375 return "s"
2376 @j.register(c.Container)
2377 def _(arg):
2378 return "container"
2379 v = V()
2380 self.assertEqual(j(v), "s")
2381 c.Container.register(V)
2382 self.assertEqual(j(v), "container") # because it ends up right after
2383 # Sized in the MRO
2384
2385 def test_cache_invalidation(self):
2386 from collections import UserDict
2387 import weakref
2388
2389 class TracingDict(UserDict):
2390 def __init__(self, *args, **kwargs):
2391 super(TracingDict, self).__init__(*args, **kwargs)
2392 self.set_ops = []
2393 self.get_ops = []
2394 def __getitem__(self, key):
2395 result = self.data[key]
2396 self.get_ops.append(key)
2397 return result
2398 def __setitem__(self, key, value):
2399 self.set_ops.append(key)
2400 self.data[key] = value
2401 def clear(self):
2402 self.data.clear()
2403
2404 td = TracingDict()
2405 with support.swap_attr(weakref, "WeakKeyDictionary", lambda: td):
2406 c = collections.abc
2407 @functools.singledispatch
2408 def g(arg):
2409 return "base"
2410 d = {}
2411 l = []
2412 self.assertEqual(len(td), 0)
2413 self.assertEqual(g(d), "base")
2414 self.assertEqual(len(td), 1)
2415 self.assertEqual(td.get_ops, [])
2416 self.assertEqual(td.set_ops, [dict])
2417 self.assertEqual(td.data[dict], g.registry[object])
2418 self.assertEqual(g(l), "base")
2419 self.assertEqual(len(td), 2)
2420 self.assertEqual(td.get_ops, [])
2421 self.assertEqual(td.set_ops, [dict, list])
2422 self.assertEqual(td.data[dict], g.registry[object])
2423 self.assertEqual(td.data[list], g.registry[object])
2424 self.assertEqual(td.data[dict], td.data[list])
2425 self.assertEqual(g(l), "base")
2426 self.assertEqual(g(d), "base")
2427 self.assertEqual(td.get_ops, [list, dict])
2428 self.assertEqual(td.set_ops, [dict, list])
2429 g.register(list, lambda arg: "list")
2430 self.assertEqual(td.get_ops, [list, dict])
2431 self.assertEqual(len(td), 0)
2432 self.assertEqual(g(d), "base")
2433 self.assertEqual(len(td), 1)
2434 self.assertEqual(td.get_ops, [list, dict])
2435 self.assertEqual(td.set_ops, [dict, list, dict])
2436 self.assertEqual(td.data[dict],
2437 functools._find_impl(dict, g.registry))
2438 self.assertEqual(g(l), "list")
2439 self.assertEqual(len(td), 2)
2440 self.assertEqual(td.get_ops, [list, dict])
2441 self.assertEqual(td.set_ops, [dict, list, dict, list])
2442 self.assertEqual(td.data[list],
2443 functools._find_impl(list, g.registry))
2444 class X:
2445 pass
2446 c.MutableMapping.register(X) # Will not invalidate the cache,
2447 # not using ABCs yet.
2448 self.assertEqual(g(d), "base")
2449 self.assertEqual(g(l), "list")
2450 self.assertEqual(td.get_ops, [list, dict, dict, list])
2451 self.assertEqual(td.set_ops, [dict, list, dict, list])
2452 g.register(c.Sized, lambda arg: "sized")
2453 self.assertEqual(len(td), 0)
2454 self.assertEqual(g(d), "sized")
2455 self.assertEqual(len(td), 1)
2456 self.assertEqual(td.get_ops, [list, dict, dict, list])
2457 self.assertEqual(td.set_ops, [dict, list, dict, list, dict])
2458 self.assertEqual(g(l), "list")
2459 self.assertEqual(len(td), 2)
2460 self.assertEqual(td.get_ops, [list, dict, dict, list])
2461 self.assertEqual(td.set_ops, [dict, list, dict, list, dict, list])
2462 self.assertEqual(g(l), "list")
2463 self.assertEqual(g(d), "sized")
2464 self.assertEqual(td.get_ops, [list, dict, dict, list, list, dict])
2465 self.assertEqual(td.set_ops, [dict, list, dict, list, dict, list])
2466 g.dispatch(list)
2467 g.dispatch(dict)
2468 self.assertEqual(td.get_ops, [list, dict, dict, list, list, dict,
2469 list, dict])
2470 self.assertEqual(td.set_ops, [dict, list, dict, list, dict, list])
2471 c.MutableSet.register(X) # Will invalidate the cache.
2472 self.assertEqual(len(td), 2) # Stale cache.
2473 self.assertEqual(g(l), "list")
2474 self.assertEqual(len(td), 1)
2475 g.register(c.MutableMapping, lambda arg: "mutablemapping")
2476 self.assertEqual(len(td), 0)
2477 self.assertEqual(g(d), "mutablemapping")
2478 self.assertEqual(len(td), 1)
2479 self.assertEqual(g(l), "list")
2480 self.assertEqual(len(td), 2)
2481 g.register(dict, lambda arg: "dict")
2482 self.assertEqual(g(d), "dict")
2483 self.assertEqual(g(l), "list")
2484 g._clear_cache()
2485 self.assertEqual(len(td), 0)
2486
2487 def test_annotations(self):
2488 @functools.singledispatch
2489 def i(arg):
2490 return "base"
2491 @i.register
2492 def _(arg: collections.abc.Mapping):
2493 return "mapping"
2494 @i.register
2495 def _(arg: "collections.abc.Sequence"):
2496 return "sequence"
2497 self.assertEqual(i(None), "base")
2498 self.assertEqual(i({"a": 1}), "mapping")
2499 self.assertEqual(i([1, 2, 3]), "sequence")
2500 self.assertEqual(i((1, 2, 3)), "sequence")
2501 self.assertEqual(i("str"), "sequence")
2502
2503 # Registering classes as callables doesn't work with annotations,
2504 # you need to pass the type explicitly.
2505 @i.register(str)
2506 class _:
2507 def __init__(self, arg):
2508 self.arg = arg
2509
2510 def __eq__(self, other):
2511 return self.arg == other
2512 self.assertEqual(i("str"), "str")
2513
2514 def test_method_register(self):
2515 class A:
2516 @functools.singledispatchmethod
2517 def t(self, arg):
2518 self.arg = "base"
2519 @t.register(int)
2520 def _(self, arg):
2521 self.arg = "int"
2522 @t.register(str)
2523 def _(self, arg):
2524 self.arg = "str"
2525 a = A()
2526
2527 a.t(0)
2528 self.assertEqual(a.arg, "int")
2529 aa = A()
2530 self.assertFalse(hasattr(aa, 'arg'))
2531 a.t('')
2532 self.assertEqual(a.arg, "str")
2533 aa = A()
2534 self.assertFalse(hasattr(aa, 'arg'))
2535 a.t(0.0)
2536 self.assertEqual(a.arg, "base")
2537 aa = A()
2538 self.assertFalse(hasattr(aa, 'arg'))
2539
2540 def test_staticmethod_register(self):
2541 class A:
2542 @functools.singledispatchmethod
2543 @staticmethod
2544 def t(arg):
2545 return arg
2546 @t.register(int)
2547 @staticmethod
2548 def _(arg):
2549 return isinstance(arg, int)
2550 @t.register(str)
2551 @staticmethod
2552 def _(arg):
2553 return isinstance(arg, str)
2554 a = A()
2555
2556 self.assertTrue(A.t(0))
2557 self.assertTrue(A.t(''))
2558 self.assertEqual(A.t(0.0), 0.0)
2559
2560 def test_slotted_class(self):
2561 class Slot:
2562 __slots__ = ('a', 'b')
2563 @functools.singledispatchmethod
2564 def go(self, item, arg):
2565 pass
2566
2567 @go.register
2568 def _(self, item: int, arg):
2569 return item + arg
2570
2571 s = Slot()
2572 self.assertEqual(s.go(1, 1), 2)
2573
2574 def test_classmethod_slotted_class(self):
2575 class Slot:
2576 __slots__ = ('a', 'b')
2577 @functools.singledispatchmethod
2578 @classmethod
2579 def go(cls, item, arg):
2580 pass
2581
2582 @go.register
2583 @classmethod
2584 def _(cls, item: int, arg):
2585 return item + arg
2586
2587 s = Slot()
2588 self.assertEqual(s.go(1, 1), 2)
2589 self.assertEqual(Slot.go(1, 1), 2)
2590
2591 def test_staticmethod_slotted_class(self):
2592 class A:
2593 __slots__ = ['a']
2594 @functools.singledispatchmethod
2595 @staticmethod
2596 def t(arg):
2597 return arg
2598 @t.register(int)
2599 @staticmethod
2600 def _(arg):
2601 return isinstance(arg, int)
2602 @t.register(str)
2603 @staticmethod
2604 def _(arg):
2605 return isinstance(arg, str)
2606 a = A()
2607
2608 self.assertTrue(A.t(0))
2609 self.assertTrue(A.t(''))
2610 self.assertEqual(A.t(0.0), 0.0)
2611 self.assertTrue(a.t(0))
2612 self.assertTrue(a.t(''))
2613 self.assertEqual(a.t(0.0), 0.0)
2614
2615 def test_assignment_behavior(self):
2616 # see gh-106448
2617 class A:
2618 @functools.singledispatchmethod
2619 def t(arg):
2620 return arg
2621
2622 a = A()
2623 a.t.foo = 'bar'
2624 a2 = A()
2625 with self.assertRaises(AttributeError):
2626 a2.t.foo
2627
2628 def test_classmethod_register(self):
2629 class A:
2630 def __init__(self, arg):
2631 self.arg = arg
2632
2633 @functools.singledispatchmethod
2634 @classmethod
2635 def t(cls, arg):
2636 return cls("base")
2637 @t.register(int)
2638 @classmethod
2639 def _(cls, arg):
2640 return cls("int")
2641 @t.register(str)
2642 @classmethod
2643 def _(cls, arg):
2644 return cls("str")
2645
2646 self.assertEqual(A.t(0).arg, "int")
2647 self.assertEqual(A.t('').arg, "str")
2648 self.assertEqual(A.t(0.0).arg, "base")
2649
2650 def test_callable_register(self):
2651 class A:
2652 def __init__(self, arg):
2653 self.arg = arg
2654
2655 @functools.singledispatchmethod
2656 @classmethod
2657 def t(cls, arg):
2658 return cls("base")
2659
2660 @A.t.register(int)
2661 @classmethod
2662 def _(cls, arg):
2663 return cls("int")
2664 @A.t.register(str)
2665 @classmethod
2666 def _(cls, arg):
2667 return cls("str")
2668
2669 self.assertEqual(A.t(0).arg, "int")
2670 self.assertEqual(A.t('').arg, "str")
2671 self.assertEqual(A.t(0.0).arg, "base")
2672
2673 def test_abstractmethod_register(self):
2674 class Abstract(metaclass=abc.ABCMeta):
2675
2676 @functools.singledispatchmethod
2677 @abc.abstractmethod
2678 def add(self, x, y):
2679 pass
2680
2681 self.assertTrue(Abstract.add.__isabstractmethod__)
2682 self.assertTrue(Abstract.__dict__['add'].__isabstractmethod__)
2683
2684 with self.assertRaises(TypeError):
2685 Abstract()
2686
2687 def test_type_ann_register(self):
2688 class A:
2689 @functools.singledispatchmethod
2690 def t(self, arg):
2691 return "base"
2692 @t.register
2693 def _(self, arg: int):
2694 return "int"
2695 @t.register
2696 def _(self, arg: str):
2697 return "str"
2698 a = A()
2699
2700 self.assertEqual(a.t(0), "int")
2701 self.assertEqual(a.t(''), "str")
2702 self.assertEqual(a.t(0.0), "base")
2703
2704 def test_staticmethod_type_ann_register(self):
2705 class A:
2706 @functools.singledispatchmethod
2707 @staticmethod
2708 def t(arg):
2709 return arg
2710 @t.register
2711 @staticmethod
2712 def _(arg: int):
2713 return isinstance(arg, int)
2714 @t.register
2715 @staticmethod
2716 def _(arg: str):
2717 return isinstance(arg, str)
2718 a = A()
2719
2720 self.assertTrue(A.t(0))
2721 self.assertTrue(A.t(''))
2722 self.assertEqual(A.t(0.0), 0.0)
2723
2724 def test_classmethod_type_ann_register(self):
2725 class A:
2726 def __init__(self, arg):
2727 self.arg = arg
2728
2729 @functools.singledispatchmethod
2730 @classmethod
2731 def t(cls, arg):
2732 return cls("base")
2733 @t.register
2734 @classmethod
2735 def _(cls, arg: int):
2736 return cls("int")
2737 @t.register
2738 @classmethod
2739 def _(cls, arg: str):
2740 return cls("str")
2741
2742 self.assertEqual(A.t(0).arg, "int")
2743 self.assertEqual(A.t('').arg, "str")
2744 self.assertEqual(A.t(0.0).arg, "base")
2745
2746 def test_method_wrapping_attributes(self):
2747 class A:
2748 @functools.singledispatchmethod
2749 def func(self, arg: int) -> str:
2750 """My function docstring"""
2751 return str(arg)
2752 @functools.singledispatchmethod
2753 @classmethod
2754 def cls_func(cls, arg: int) -> str:
2755 """My function docstring"""
2756 return str(arg)
2757 @functools.singledispatchmethod
2758 @staticmethod
2759 def static_func(arg: int) -> str:
2760 """My function docstring"""
2761 return str(arg)
2762
2763 prefix = A.__qualname__ + '.'
2764 for meth in (
2765 A.func,
2766 A().func,
2767 A.cls_func,
2768 A().cls_func,
2769 A.static_func,
2770 A().static_func
2771 ):
2772 with self.subTest(meth=meth):
2773 self.assertEqual(meth.__qualname__, prefix + meth.__name__)
2774 self.assertEqual(meth.__doc__,
2775 ('My function docstring'
2776 if support.HAVE_PY_DOCSTRINGS
2777 else None))
2778 self.assertEqual(meth.__annotations__['arg'], int)
2779
2780 self.assertEqual(A.func.__name__, 'func')
2781 self.assertEqual(A().func.__name__, 'func')
2782 self.assertEqual(A.cls_func.__name__, 'cls_func')
2783 self.assertEqual(A().cls_func.__name__, 'cls_func')
2784 self.assertEqual(A.static_func.__name__, 'static_func')
2785 self.assertEqual(A().static_func.__name__, 'static_func')
2786
2787 def test_double_wrapped_methods(self):
2788 def classmethod_friendly_decorator(func):
2789 wrapped = func.__func__
2790 @classmethod
2791 @functools.wraps(wrapped)
2792 def wrapper(*args, **kwargs):
2793 return wrapped(*args, **kwargs)
2794 return wrapper
2795
2796 class WithoutSingleDispatch:
2797 @classmethod
2798 @contextlib.contextmanager
2799 def cls_context_manager(cls, arg: int) -> str:
2800 try:
2801 yield str(arg)
2802 finally:
2803 return 'Done'
2804
2805 @classmethod_friendly_decorator
2806 @classmethod
2807 def decorated_classmethod(cls, arg: int) -> str:
2808 return str(arg)
2809
2810 class WithSingleDispatch:
2811 @functools.singledispatchmethod
2812 @classmethod
2813 @contextlib.contextmanager
2814 def cls_context_manager(cls, arg: int) -> str:
2815 """My function docstring"""
2816 try:
2817 yield str(arg)
2818 finally:
2819 return 'Done'
2820
2821 @functools.singledispatchmethod
2822 @classmethod_friendly_decorator
2823 @classmethod
2824 def decorated_classmethod(cls, arg: int) -> str:
2825 """My function docstring"""
2826 return str(arg)
2827
2828 # These are sanity checks
2829 # to test the test itself is working as expected
2830 with WithoutSingleDispatch.cls_context_manager(5) as foo:
2831 without_single_dispatch_foo = foo
2832
2833 with WithSingleDispatch.cls_context_manager(5) as foo:
2834 single_dispatch_foo = foo
2835
2836 self.assertEqual(without_single_dispatch_foo, single_dispatch_foo)
2837 self.assertEqual(single_dispatch_foo, '5')
2838
2839 self.assertEqual(
2840 WithoutSingleDispatch.decorated_classmethod(5),
2841 WithSingleDispatch.decorated_classmethod(5)
2842 )
2843
2844 self.assertEqual(WithSingleDispatch.decorated_classmethod(5), '5')
2845
2846 # Behavioural checks now follow
2847 for method_name in ('cls_context_manager', 'decorated_classmethod'):
2848 with self.subTest(method=method_name):
2849 self.assertEqual(
2850 getattr(WithSingleDispatch, method_name).__name__,
2851 getattr(WithoutSingleDispatch, method_name).__name__
2852 )
2853
2854 self.assertEqual(
2855 getattr(WithSingleDispatch(), method_name).__name__,
2856 getattr(WithoutSingleDispatch(), method_name).__name__
2857 )
2858
2859 for meth in (
2860 WithSingleDispatch.cls_context_manager,
2861 WithSingleDispatch().cls_context_manager,
2862 WithSingleDispatch.decorated_classmethod,
2863 WithSingleDispatch().decorated_classmethod
2864 ):
2865 with self.subTest(meth=meth):
2866 self.assertEqual(meth.__doc__,
2867 ('My function docstring'
2868 if support.HAVE_PY_DOCSTRINGS
2869 else None))
2870 self.assertEqual(meth.__annotations__['arg'], int)
2871
2872 self.assertEqual(
2873 WithSingleDispatch.cls_context_manager.__name__,
2874 'cls_context_manager'
2875 )
2876 self.assertEqual(
2877 WithSingleDispatch().cls_context_manager.__name__,
2878 'cls_context_manager'
2879 )
2880 self.assertEqual(
2881 WithSingleDispatch.decorated_classmethod.__name__,
2882 'decorated_classmethod'
2883 )
2884 self.assertEqual(
2885 WithSingleDispatch().decorated_classmethod.__name__,
2886 'decorated_classmethod'
2887 )
2888
2889 def test_invalid_registrations(self):
2890 msg_prefix = "Invalid first argument to `register()`: "
2891 msg_suffix = (
2892 ". Use either `@register(some_class)` or plain `@register` on an "
2893 "annotated function."
2894 )
2895 @functools.singledispatch
2896 def i(arg):
2897 return "base"
2898 with self.assertRaises(TypeError) as exc:
2899 @i.register(42)
2900 def _(arg):
2901 return "I annotated with a non-type"
2902 self.assertTrue(str(exc.exception).startswith(msg_prefix + "42"))
2903 self.assertTrue(str(exc.exception).endswith(msg_suffix))
2904 with self.assertRaises(TypeError) as exc:
2905 @i.register
2906 def _(arg):
2907 return "I forgot to annotate"
2908 self.assertTrue(str(exc.exception).startswith(msg_prefix +
2909 "<function TestSingleDispatch.test_invalid_registrations.<locals>._"
2910 ))
2911 self.assertTrue(str(exc.exception).endswith(msg_suffix))
2912
2913 with self.assertRaises(TypeError) as exc:
2914 @i.register
2915 def _(arg: typing.Iterable[str]):
2916 # At runtime, dispatching on generics is impossible.
2917 # When registering implementations with singledispatch, avoid
2918 # types from `typing`. Instead, annotate with regular types
2919 # or ABCs.
2920 return "I annotated with a generic collection"
2921 self.assertTrue(str(exc.exception).startswith(
2922 "Invalid annotation for 'arg'."
2923 ))
2924 self.assertTrue(str(exc.exception).endswith(
2925 'typing.Iterable[str] is not a class.'
2926 ))
2927
2928 with self.assertRaises(TypeError) as exc:
2929 @i.register
2930 def _(arg: typing.Union[int, typing.Iterable[str]]):
2931 return "Invalid Union"
2932 self.assertTrue(str(exc.exception).startswith(
2933 "Invalid annotation for 'arg'."
2934 ))
2935 self.assertTrue(str(exc.exception).endswith(
2936 'typing.Union[int, typing.Iterable[str]] not all arguments are classes.'
2937 ))
2938
2939 def test_invalid_positional_argument(self):
2940 @functools.singledispatch
2941 def f(*args, **kwargs):
2942 pass
2943 msg = 'f requires at least 1 positional argument'
2944 with self.assertRaisesRegex(TypeError, msg):
2945 f()
2946 msg = 'f requires at least 1 positional argument'
2947 with self.assertRaisesRegex(TypeError, msg):
2948 f(a=1)
2949
2950 def test_invalid_positional_argument_singledispatchmethod(self):
2951 class A:
2952 @functools.singledispatchmethod
2953 def t(self, *args, **kwargs):
2954 pass
2955 msg = 't requires at least 1 positional argument'
2956 with self.assertRaisesRegex(TypeError, msg):
2957 A().t()
2958 msg = 't requires at least 1 positional argument'
2959 with self.assertRaisesRegex(TypeError, msg):
2960 A().t(a=1)
2961
2962 def test_union(self):
2963 @functools.singledispatch
2964 def f(arg):
2965 return "default"
2966
2967 @f.register
2968 def _(arg: typing.Union[str, bytes]):
2969 return "typing.Union"
2970
2971 @f.register
2972 def _(arg: int | float):
2973 return "types.UnionType"
2974
2975 self.assertEqual(f([]), "default")
2976 self.assertEqual(f(""), "typing.Union")
2977 self.assertEqual(f(b""), "typing.Union")
2978 self.assertEqual(f(1), "types.UnionType")
2979 self.assertEqual(f(1.0), "types.UnionType")
2980
2981 def test_union_conflict(self):
2982 @functools.singledispatch
2983 def f(arg):
2984 return "default"
2985
2986 @f.register
2987 def _(arg: typing.Union[str, bytes]):
2988 return "typing.Union"
2989
2990 @f.register
2991 def _(arg: int | str):
2992 return "types.UnionType"
2993
2994 self.assertEqual(f([]), "default")
2995 self.assertEqual(f(""), "types.UnionType") # last one wins
2996 self.assertEqual(f(b""), "typing.Union")
2997 self.assertEqual(f(1), "types.UnionType")
2998
2999 def test_union_None(self):
3000 @functools.singledispatch
3001 def typing_union(arg):
3002 return "default"
3003
3004 @typing_union.register
3005 def _(arg: typing.Union[str, None]):
3006 return "typing.Union"
3007
3008 self.assertEqual(typing_union(1), "default")
3009 self.assertEqual(typing_union(""), "typing.Union")
3010 self.assertEqual(typing_union(None), "typing.Union")
3011
3012 @functools.singledispatch
3013 def types_union(arg):
3014 return "default"
3015
3016 @types_union.register
3017 def _(arg: int | None):
3018 return "types.UnionType"
3019
3020 self.assertEqual(types_union(""), "default")
3021 self.assertEqual(types_union(1), "types.UnionType")
3022 self.assertEqual(types_union(None), "types.UnionType")
3023
3024 def test_register_genericalias(self):
3025 @functools.singledispatch
3026 def f(arg):
3027 return "default"
3028
3029 with self.assertRaisesRegex(TypeError, "Invalid first argument to "):
3030 f.register(list[int], lambda arg: "types.GenericAlias")
3031 with self.assertRaisesRegex(TypeError, "Invalid first argument to "):
3032 f.register(typing.List[int], lambda arg: "typing.GenericAlias")
3033 with self.assertRaisesRegex(TypeError, "Invalid first argument to "):
3034 f.register(list[int] | str, lambda arg: "types.UnionTypes(types.GenericAlias)")
3035 with self.assertRaisesRegex(TypeError, "Invalid first argument to "):
3036 f.register(typing.List[float] | bytes, lambda arg: "typing.Union[typing.GenericAlias]")
3037
3038 self.assertEqual(f([1]), "default")
3039 self.assertEqual(f([1.0]), "default")
3040 self.assertEqual(f(""), "default")
3041 self.assertEqual(f(b""), "default")
3042
3043 def test_register_genericalias_decorator(self):
3044 @functools.singledispatch
3045 def f(arg):
3046 return "default"
3047
3048 with self.assertRaisesRegex(TypeError, "Invalid first argument to "):
3049 f.register(list[int])
3050 with self.assertRaisesRegex(TypeError, "Invalid first argument to "):
3051 f.register(typing.List[int])
3052 with self.assertRaisesRegex(TypeError, "Invalid first argument to "):
3053 f.register(list[int] | str)
3054 with self.assertRaisesRegex(TypeError, "Invalid first argument to "):
3055 f.register(typing.List[int] | str)
3056
3057 def test_register_genericalias_annotation(self):
3058 @functools.singledispatch
3059 def f(arg):
3060 return "default"
3061
3062 with self.assertRaisesRegex(TypeError, "Invalid annotation for 'arg'"):
3063 @f.register
3064 def _(arg: list[int]):
3065 return "types.GenericAlias"
3066 with self.assertRaisesRegex(TypeError, "Invalid annotation for 'arg'"):
3067 @f.register
3068 def _(arg: typing.List[float]):
3069 return "typing.GenericAlias"
3070 with self.assertRaisesRegex(TypeError, "Invalid annotation for 'arg'"):
3071 @f.register
3072 def _(arg: list[int] | str):
3073 return "types.UnionType(types.GenericAlias)"
3074 with self.assertRaisesRegex(TypeError, "Invalid annotation for 'arg'"):
3075 @f.register
3076 def _(arg: typing.List[float] | bytes):
3077 return "typing.Union[typing.GenericAlias]"
3078
3079 self.assertEqual(f([1]), "default")
3080 self.assertEqual(f([1.0]), "default")
3081 self.assertEqual(f(""), "default")
3082 self.assertEqual(f(b""), "default")
3083
3084 def test_method_equal_instances(self):
3085 # gh-127750: Reference to self was cached
3086 class A:
3087 def __eq__(self, other):
3088 return True
3089 def __hash__(self):
3090 return 1
3091 @functools.singledispatchmethod
3092 def t(self, arg):
3093 return self
3094
3095 a = A()
3096 b = A()
3097 self.assertIs(a.t(1), a)
3098 self.assertIs(b.t(2), b)
3099
3100 def test_method_bad_hash(self):
3101 class A:
3102 def __eq__(self, other):
3103 raise AssertionError
3104 def __hash__(self):
3105 raise AssertionError
3106 @functools.singledispatchmethod
3107 def t(self, arg):
3108 pass
3109
3110 # Should not raise
3111 A().t(1)
3112 hash(A().t)
3113 A().t == A().t
3114
3115 def test_method_no_reference_loops(self):
3116 # gh-127750: Created a strong reference to self
3117 class A:
3118 @functools.singledispatchmethod
3119 def t(self, arg):
3120 return weakref.ref(self)
3121
3122 a = A()
3123 r = a.t(1)
3124 self.assertIsNotNone(r())
3125 del a # delete a after a.t
3126 if not support.check_impl_detail(cpython=True):
3127 support.gc_collect()
3128 self.assertIsNone(r())
3129
3130 a = A()
3131 t = a.t
3132 del a # delete a before a.t
3133 support.gc_collect()
3134 r = t(1)
3135 self.assertIsNotNone(r())
3136 del t
3137 if not support.check_impl_detail(cpython=True):
3138 support.gc_collect()
3139 self.assertIsNone(r())
3140
3141 def test_signatures(self):
3142 @functools.singledispatch
3143 def func(item, arg: int) -> str:
3144 return str(item)
3145 @func.register
3146 def _(item: int, arg: bytes) -> str:
3147 return str(item)
3148
3149 self.assertEqual(str(Signature.from_callable(func)),
3150 '(item, arg: int) -> str')
3151
3152 def test_method_signatures(self):
3153 class A:
3154 @functools.singledispatchmethod
3155 def func(self, item, arg: int) -> str:
3156 return str(item)
3157 @func.register
3158 def _(self, item: int, arg: bytes) -> str:
3159 return str(item)
3160
3161 @functools.singledispatchmethod
3162 @classmethod
3163 def cls_func(cls, item, arg: int) -> str:
3164 return str(arg)
3165 @func.register
3166 @classmethod
3167 def _(cls, item: int, arg: bytes) -> str:
3168 return str(item)
3169
3170 @functools.singledispatchmethod
3171 @staticmethod
3172 def static_func(item, arg: int) -> str:
3173 return str(arg)
3174 @func.register
3175 @staticmethod
3176 def _(item: int, arg: bytes) -> str:
3177 return str(item)
3178
3179 self.assertEqual(str(Signature.from_callable(A.func)),
3180 '(self, item, arg: int) -> str')
3181 self.assertEqual(str(Signature.from_callable(A().func)),
3182 '(self, item, arg: int) -> str')
3183 self.assertEqual(str(Signature.from_callable(A.cls_func)),
3184 '(cls, item, arg: int) -> str')
3185 self.assertEqual(str(Signature.from_callable(A.static_func)),
3186 '(item, arg: int) -> str')
3187
3188
3189 class CachedCostItem:
3190 _cost = 1
3191
3192 def __init__(self):
3193 self.lock = py_functools.RLock()
3194
3195 @py_functools.cached_property
3196 def cost(self):
3197 """The cost of the item."""
3198 with self.lock:
3199 self._cost += 1
3200 return self._cost
3201
3202
3203 class OptionallyCachedCostItem:
3204 _cost = 1
3205
3206 def get_cost(self):
3207 """The cost of the item."""
3208 self._cost += 1
3209 return self._cost
3210
3211 cached_cost = py_functools.cached_property(get_cost)
3212
3213
3214 class CachedCostItemWithSlots:
3215 __slots__ = ('_cost')
3216
3217 def __init__(self):
3218 self._cost = 1
3219
3220 @py_functools.cached_property
3221 def cost(self):
3222 raise RuntimeError('never called, slots not supported')
3223
3224
3225 class TestCachedProperty(unittest.TestCase):
3226 def test_cached(self):
3227 item = CachedCostItem()
3228 self.assertEqual(item.cost, 2)
3229 self.assertEqual(item.cost, 2) # not 3
3230
3231 def test_cached_attribute_name_differs_from_func_name(self):
3232 item = OptionallyCachedCostItem()
3233 self.assertEqual(item.get_cost(), 2)
3234 self.assertEqual(item.cached_cost, 3)
3235 self.assertEqual(item.get_cost(), 4)
3236 self.assertEqual(item.cached_cost, 3)
3237
3238 def test_object_with_slots(self):
3239 item = CachedCostItemWithSlots()
3240 with self.assertRaisesRegex(
3241 TypeError,
3242 "No '__dict__' attribute on 'CachedCostItemWithSlots' instance to cache 'cost' property.",
3243 ):
3244 item.cost
3245
3246 def test_immutable_dict(self):
3247 class MyMeta(type):
3248 @py_functools.cached_property
3249 def prop(self):
3250 return True
3251
3252 class MyClass(metaclass=MyMeta):
3253 pass
3254
3255 with self.assertRaisesRegex(
3256 TypeError,
3257 "The '__dict__' attribute on 'MyMeta' instance does not support item assignment for caching 'prop' property.",
3258 ):
3259 MyClass.prop
3260
3261 def test_reuse_different_names(self):
3262 """Disallow this case because decorated function a would not be cached."""
3263 with self.assertRaises(TypeError) as ctx:
3264 class ReusedCachedProperty:
3265 @py_functools.cached_property
3266 def a(self):
3267 pass
3268
3269 b = a
3270
3271 self.assertEqual(
3272 str(ctx.exception),
3273 str(TypeError("Cannot assign the same cached_property to two different names ('a' and 'b')."))
3274 )
3275
3276 def test_reuse_same_name(self):
3277 """Reusing a cached_property on different classes under the same name is OK."""
3278 counter = 0
3279
3280 @py_functools.cached_property
3281 def _cp(_self):
3282 nonlocal counter
3283 counter += 1
3284 return counter
3285
3286 class A:
3287 cp = _cp
3288
3289 class B:
3290 cp = _cp
3291
3292 a = A()
3293 b = B()
3294
3295 self.assertEqual(a.cp, 1)
3296 self.assertEqual(b.cp, 2)
3297 self.assertEqual(a.cp, 1)
3298
3299 def test_set_name_not_called(self):
3300 cp = py_functools.cached_property(lambda s: None)
3301 class Foo:
3302 pass
3303
3304 Foo.cp = cp
3305
3306 with self.assertRaisesRegex(
3307 TypeError,
3308 "Cannot use cached_property instance without calling __set_name__ on it.",
3309 ):
3310 Foo().cp
3311
3312 def test_access_from_class(self):
3313 self.assertIsInstance(CachedCostItem.cost, py_functools.cached_property)
3314
3315 def test_doc(self):
3316 self.assertEqual(CachedCostItem.cost.__doc__,
3317 ("The cost of the item."
3318 if support.HAVE_PY_DOCSTRINGS
3319 else None))
3320
3321 def test_module(self):
3322 self.assertEqual(CachedCostItem.cost.__module__, CachedCostItem.__module__)
3323
3324 def test_subclass_with___set__(self):
3325 """Caching still works for a subclass defining __set__."""
3326 class readonly_cached_property(py_functools.cached_property):
3327 def __set__(self, obj, value):
3328 raise AttributeError("read only property")
3329
3330 class Test:
3331 def __init__(self, prop):
3332 self._prop = prop
3333
3334 @readonly_cached_property
3335 def prop(self):
3336 return self._prop
3337
3338 t = Test(1)
3339 self.assertEqual(t.prop, 1)
3340 t._prop = 999
3341 self.assertEqual(t.prop, 1)
3342
3343
3344 if __name__ == '__main__':
3345 unittest.main()