Debian Codegraph @

lib-python/3/test/test_functools.py

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