Skip to content

Commit 2e14ac4

Browse files
committed
.supports now also uses cache
1 parent e77e4ea commit 2e14ac4

File tree

2 files changed

+49
-4
lines changed

2 files changed

+49
-4
lines changed

classes/_typeclass.py

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -480,11 +480,20 @@ def supports(
480480
481481
See also: https://www.python.org/dev/peps/pep-0647
482482
"""
483+
self._control_abc_cache()
484+
483485
instance_type = type(instance)
484-
return (
485-
instance_type in self._dispatch_cache or
486-
self._dispatch(instance, instance_type) is not None
487-
)
486+
if instance_type in self._dispatch_cache:
487+
return True
488+
489+
# This only happens when we don't have a cache in place:
490+
impl = self._dispatch(instance, instance_type)
491+
if impl is None:
492+
self._dispatch_cache[instance_type] = self._default_implementation
493+
return False
494+
495+
self._dispatch_cache[instance_type] = impl
496+
return True
488497

489498
def instance(
490499
self,

tests/test_suppots.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
from typing import Sized
2+
3+
import pytest
4+
5+
from classes import typeclass
6+
7+
8+
@typeclass
9+
def my_len(instance) -> int:
10+
"""Returns a length of an object."""
11+
12+
13+
@my_len.instance(Sized, is_protocol=True)
14+
def _my_len_sized(instance: Sized) -> int:
15+
return 0
16+
17+
18+
@my_len.instance(list)
19+
def _my_len_list(instance: list) -> int:
20+
return 1
21+
22+
23+
class _MyList(list): # noqa: WPS600
24+
"""We use it to test mro."""
25+
26+
27+
@pytest.mark.parametrize(('data_type', 'expected'), [
28+
([], True), # direct list call
29+
('', True), # sized protocol)
30+
(1, False), # default impl
31+
(_MyList(), True), # mro fallback
32+
])
33+
def test_supports(data_type, expected):
34+
"""Ensures that ``.supports`` works correctly."""
35+
assert my_len.supports(data_type) is expected
36+
assert type(data_type) in my_len._dispatch_cache # noqa: WPS437, WPS516

0 commit comments

Comments
 (0)