pure-interface 8.4.0__tar.gz → 8.6.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. {pure_interface-8.4.0 → pure_interface-8.6.0}/PKG-INFO +3 -1
  2. {pure_interface-8.4.0 → pure_interface-8.6.0}/pure_interface/__init__.py +1 -1
  3. {pure_interface-8.4.0 → pure_interface-8.6.0}/pure_interface/adaption.py +6 -0
  4. {pure_interface-8.4.0 → pure_interface-8.6.0}/pure_interface/interface.py +89 -67
  5. {pure_interface-8.4.0 → pure_interface-8.6.0}/pure_interface.egg-info/PKG-INFO +3 -1
  6. {pure_interface-8.4.0 → pure_interface-8.6.0}/pure_interface.egg-info/SOURCES.txt +1 -0
  7. {pure_interface-8.4.0 → pure_interface-8.6.0}/pure_interface.egg-info/requires.txt +1 -0
  8. {pure_interface-8.4.0 → pure_interface-8.6.0}/pyproject.toml +77 -73
  9. pure_interface-8.6.0/tests/test_adapter_cache.py +199 -0
  10. {pure_interface-8.4.0 → pure_interface-8.6.0}/tests/test_no_content_checks.py +20 -0
  11. {pure_interface-8.4.0 → pure_interface-8.6.0}/LICENSE +0 -0
  12. {pure_interface-8.4.0 → pure_interface-8.6.0}/README.rst +0 -0
  13. {pure_interface-8.4.0 → pure_interface-8.6.0}/pure_interface/_sub_interface.py +0 -0
  14. {pure_interface-8.4.0 → pure_interface-8.6.0}/pure_interface/delegation.py +0 -0
  15. {pure_interface-8.4.0 → pure_interface-8.6.0}/pure_interface/errors.py +0 -0
  16. {pure_interface-8.4.0 → pure_interface-8.6.0}/pure_interface/mypy_plugin.py +0 -0
  17. {pure_interface-8.4.0 → pure_interface-8.6.0}/pure_interface/py.typed +0 -0
  18. {pure_interface-8.4.0 → pure_interface-8.6.0}/pure_interface.egg-info/dependency_links.txt +0 -0
  19. {pure_interface-8.4.0 → pure_interface-8.6.0}/pure_interface.egg-info/top_level.txt +0 -0
  20. {pure_interface-8.4.0 → pure_interface-8.6.0}/setup.cfg +0 -0
  21. {pure_interface-8.4.0 → pure_interface-8.6.0}/tests/test_adapt_args_anno.py +0 -0
  22. {pure_interface-8.4.0 → pure_interface-8.6.0}/tests/test_adapt_args_no_anno.py +0 -0
  23. {pure_interface-8.4.0 → pure_interface-8.6.0}/tests/test_adapt_call.py +0 -0
  24. {pure_interface-8.4.0 → pure_interface-8.6.0}/tests/test_adaption.py +0 -0
  25. {pure_interface-8.4.0 → pure_interface-8.6.0}/tests/test_dataclass_support.py +0 -0
  26. {pure_interface-8.4.0 → pure_interface-8.6.0}/tests/test_delegate.py +0 -0
  27. {pure_interface-8.4.0 → pure_interface-8.6.0}/tests/test_func_sigs3.py +0 -0
  28. {pure_interface-8.4.0 → pure_interface-8.6.0}/tests/test_func_sigs_po.py +0 -0
  29. {pure_interface-8.4.0 → pure_interface-8.6.0}/tests/test_function_sigs.py +0 -0
  30. {pure_interface-8.4.0 → pure_interface-8.6.0}/tests/test_generic_support.py +0 -0
  31. {pure_interface-8.4.0 → pure_interface-8.6.0}/tests/test_implementation_checks.py +0 -0
  32. {pure_interface-8.4.0 → pure_interface-8.6.0}/tests/test_inheritance.py +0 -0
  33. {pure_interface-8.4.0 → pure_interface-8.6.0}/tests/test_isinstance.py +0 -0
  34. {pure_interface-8.4.0 → pure_interface-8.6.0}/tests/test_meta_classes.py +0 -0
  35. {pure_interface-8.4.0 → pure_interface-8.6.0}/tests/test_module_funcs.py +0 -0
  36. {pure_interface-8.4.0 → pure_interface-8.6.0}/tests/test_singledispatch.py +0 -0
  37. {pure_interface-8.4.0 → pure_interface-8.6.0}/tests/test_sub_interfaces.py +0 -0
  38. {pure_interface-8.4.0 → pure_interface-8.6.0}/tests/test_tracker.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pure-interface
3
- Version: 8.4.0
3
+ Version: 8.6.0
4
4
  Summary: A Python interface library that disallows function body content on interfaces and supports adaption.
5
5
  Author-email: Tim Mitchell <tim.mitchell@seequent.com>
6
6
  License-Expression: MIT
@@ -15,9 +15,11 @@ Classifier: Programming Language :: Python :: 3.11
15
15
  Classifier: Programming Language :: Python :: 3.12
16
16
  Classifier: Programming Language :: Python :: 3.13
17
17
  Classifier: Programming Language :: Python :: 3.14
18
+ Classifier: Programming Language :: Python :: 3.15
18
19
  Requires-Python: >=3.10
19
20
  Description-Content-Type: text/x-rst
20
21
  License-File: LICENSE
22
+ Requires-Dist: build>=1.6.1
21
23
  Provides-Extra: dev
22
24
  Requires-Dist: mypy>=1.4; extra == "dev"
23
25
  Requires-Dist: tox; extra == "dev"
@@ -19,4 +19,4 @@ from .interface import (
19
19
  type_is_interface,
20
20
  )
21
21
 
22
- __version__ = "8.4.0" # Don't change this manually - run `bump-my-version bump [major|minor|patch]` instead
22
+ __version__ = "8.6.0" # Don't change this manually - run `bump-my-version bump [major|minor|patch]` instead
@@ -16,6 +16,7 @@ from .interface import (
16
16
  AnInterface,
17
17
  Interface,
18
18
  InterfaceType,
19
+ clear_adapter_caches,
19
20
  get_pi_attribute,
20
21
  get_type_interfaces,
21
22
  type_is_interface,
@@ -81,6 +82,11 @@ def register_adapter(
81
82
  raise AdaptionError("{} already has an adapter to {}".format(from_type, to_interface))
82
83
 
83
84
  adapters[from_type] = adapter
85
+ # Clears all cached adapter lookups for to_interface and its ancestors.
86
+ # This is safe because registration is expected to happen at startup.
87
+ # Calling register_adapter at runtime will cause all cached adapters for
88
+ # the interface to be re-resolved on next use.
89
+ clear_adapter_caches(to_interface)
84
90
 
85
91
 
86
92
  class AdapterTracker(object):
@@ -10,7 +10,6 @@ from __future__ import absolute_import, division, print_function
10
10
 
11
11
  import abc
12
12
  import collections
13
- import dis
14
13
  import functools
15
14
  import inspect
16
15
  import sys
@@ -32,8 +31,11 @@ from typing import (
32
31
  Tuple,
33
32
  Type,
34
33
  TypeVar,
34
+ cast,
35
35
  )
36
36
 
37
+ import opcode
38
+
37
39
  from .errors import AdaptionError, InterfaceError
38
40
 
39
41
  is_development = not hasattr(sys, "frozen")
@@ -63,6 +65,17 @@ AnInterface = TypeVar("AnInterface", bound="Interface")
63
65
  AnInterfaceType = TypeVar("AnInterfaceType", bound="InterfaceType")
64
66
 
65
67
 
68
+ def clear_adapter_caches(interface_cls: type) -> None:
69
+ """Clear adapter caches for the given interface, all its ancestor interfaces,
70
+ and any interfaces that have registered this interface via .register()."""
71
+ affected = [interface_cls] + list(get_pi_attribute(interface_cls, "registered_by", ()))
72
+ for affected_cls in affected:
73
+ for cls in affected_cls.__mro__:
74
+ cache = get_pi_attribute(cls, "adapter_cache")
75
+ if cache is not None:
76
+ cache.clear()
77
+
78
+
66
79
  def _unique_list(items: Iterable[Any]) -> List[Any]:
67
80
  seen = set()
68
81
  unique_items = []
@@ -91,10 +104,12 @@ class _PIAttributes:
91
104
  # keep an ordered list for dataclass
92
105
  self.interface_attribute_names: List[str] = _unique_list(interface_attribute_names)
93
106
  self.interface_method_signatures = interface_method_signatures
94
- self.adapters = weakref.WeakKeyDictionary() # type: ignore
95
- self.registered_types = weakref.WeakSet() # type: ignore
107
+ self.adapters: weakref.WeakKeyDictionary[type, Callable] = weakref.WeakKeyDictionary()
108
+ self.registered_types: weakref.WeakSet[type] = weakref.WeakSet()
109
+ self.registered_by: weakref.WeakSet[type] = weakref.WeakSet() # interfaces that have registered this one
96
110
  self.structural_subclasses: Set[type] = set()
97
111
  self.impl_wrapper_type: Optional[type] = None
112
+ self.adapter_cache: weakref.WeakKeyDictionary[type, Optional[Callable]] = weakref.WeakKeyDictionary()
98
113
 
99
114
  @property
100
115
  def interface_names(self) -> FrozenSet[str]:
@@ -217,6 +232,49 @@ def _unwrap_function(func: Any) -> Any:
217
232
  return func
218
233
 
219
234
 
235
+ def _bytecode_instructions(code_obj: types.CodeType) -> List[Tuple[str, int]]:
236
+ instructions = []
237
+ extended_arg = 0
238
+ byte_code = code_obj.co_code
239
+ for offset in range(0, len(byte_code), 2):
240
+ op = byte_code[offset]
241
+ arg = byte_code[offset + 1]
242
+ opname = opcode.opname[op]
243
+ if opname == "CACHE":
244
+ continue
245
+ if opname == "EXTENDED_ARG":
246
+ extended_arg = (extended_arg << 8) | arg
247
+ continue
248
+ instructions.append((opname, (extended_arg << 8) | arg))
249
+ extended_arg = 0
250
+ return instructions
251
+
252
+
253
+ def _is_none_constant(code_obj: types.CodeType, instruction: Tuple[str, int]) -> bool:
254
+ opname, arg = instruction
255
+ if opname in ("LOAD_CONST", "RETURN_CONST"):
256
+ return arg < len(code_obj.co_consts) and code_obj.co_consts[arg] is None
257
+ if opname == "LOAD_COMMON_CONSTANT":
258
+ common_constants = getattr(opcode, "_common_constants", ())
259
+ return arg < len(common_constants) and common_constants[arg] is None
260
+ return False
261
+
262
+
263
+ def _normalized_bytecode(code_obj: types.CodeType) -> List[Tuple[str, int]]:
264
+ instructions = _bytecode_instructions(code_obj)
265
+ while instructions and instructions[0][0] in ("GEN_START", "RESUME", "NOP"):
266
+ instructions.pop(0)
267
+ if instructions and instructions[0][0] == "RETURN_GENERATOR":
268
+ instructions.pop(0)
269
+ if instructions and instructions[0][0] == "POP_TOP":
270
+ instructions.pop(0)
271
+ while instructions and instructions[0][0] in ("RESUME", "NOP"):
272
+ instructions.pop(0)
273
+ if len(instructions) > 2 and instructions[-2][0] == "CALL_INTRINSIC_1" and instructions[-1][0] == "RERAISE":
274
+ instructions = instructions[:-2]
275
+ return instructions
276
+
277
+
220
278
  def _is_empty_function(func: Any, unwrap: bool = False) -> bool:
221
279
  """Return True if func is considered empty.
222
280
  All functions with no return statement have an implicit return None - this is explicit in the code object.
@@ -233,72 +291,27 @@ def _is_empty_function(func: Any, unwrap: bool = False) -> bool:
233
291
  # This callable is something else - assume it is OK.
234
292
  return True
235
293
 
236
- # quick check
237
- byte_code = code_obj.co_code
238
- if byte_code.startswith(b"\x81\x01"):
239
- byte_code = byte_code[2:] # remove GEN_START async def opcode
240
- if byte_code.startswith(b"\x97\x00"):
241
- byte_code = byte_code[2:] # remove RESUME opcode added in 3.11
242
- if byte_code.startswith(b"\t\x00"):
243
- byte_code = byte_code[2:] # remove NOP opcode
244
- if byte_code.startswith(b"K\x00"):
245
- byte_code = byte_code[2:] # remove RETURN_GENERATOR async def opcode in py311
246
- if byte_code.startswith(b"\x01"):
247
- byte_code = byte_code[2:] # remove POP_TOP
248
- if byte_code.startswith(b"\x97\x00"):
249
- byte_code = byte_code[2:] # remove RESUME opcode added in 3.11
250
- if byte_code.startswith(b"\t\x00"):
251
- byte_code = byte_code[2:] # remove NOP opcode
252
- if byte_code in (b"d\x00\x00S", b"d\x00S\x00") and code_obj.co_consts[0] is None:
253
- return True
254
- if byte_code in (b"d\x01\x00S", b"d\x01S\x00") and code_obj.co_consts[1] is None:
294
+ instructions = _normalized_bytecode(code_obj)
295
+ if len(instructions) == 2 and _is_none_constant(code_obj, instructions[0]) and instructions[1][0] == "RETURN_VALUE":
255
296
  return True
256
- if byte_code == b"y\x00" and code_obj.co_consts[0] is None: # RETURN_CONST in 3.12+
257
- return True
258
- # convert bytes to instructions
259
- instructions = list(dis.get_instructions(code_obj))
260
- if len(instructions) < 2:
261
- return True # this never happens
262
- if instructions[0].opname == "GEN_START":
263
- instructions.pop(0)
264
- if instructions[0].opname == "RESUME":
265
- instructions.pop(0)
266
- if instructions[0].opname == "NOP":
267
- instructions.pop(0)
268
- if instructions[0].opname == "RETURN_GENERATOR":
269
- instructions.pop(0)
270
- if instructions[0].opname == "POP_TOP":
271
- instructions.pop(0)
272
- # All generator functions end with these 2 opcodes in 3.12+
273
- if (
274
- len(instructions) > 2
275
- and instructions[-2].opname == "CALL_INTRINSIC_1"
276
- and instructions[-1].opname == "RERAISE"
277
- ):
278
- instructions = instructions[:-2] # remove last 2 instructions
279
- if instructions[0].opname == "RESUME":
280
- instructions.pop(0)
281
- if instructions[0].opname == "NOP":
282
- instructions.pop(0)
283
- if instructions[-1].opname == "RETURN_VALUE": # returns TOS (top of stack)
284
- instruction = instructions[-2]
285
- if not (instruction.opname == "LOAD_CONST" and code_obj.co_consts[instruction.arg] is None): # TOS is None
286
- return False # return is not None
287
- instructions = instructions[:-2]
288
- if (
289
- len(instructions) > 0 and instructions[-1].opname == "RETURN_CONST" and instructions[-1].argval is None
290
- ): # returns constant
291
- instructions.pop(-1)
292
- if len(instructions) == 0:
297
+ if len(instructions) == 1 and _is_none_constant(code_obj, instructions[0]):
293
298
  return True
299
+ return _is_not_implemented_function(code_obj, instructions)
300
+
301
+
302
+ def _is_not_implemented_function(code_obj: types.CodeType, instructions: List[Tuple[str, int]]) -> bool:
294
303
  # look for raise NotImplementedError
295
- if instructions[-1].opname == "RAISE_VARARGS":
304
+ if instructions[-1][0] == "RAISE_VARARGS":
296
305
  # the thing we are raising should be the result of __call__ (instantiating exception object)
297
- if instructions[-2].opname in ("CALL_FUNCTION", "CALL"):
298
- for instr in instructions[-3::-1]:
299
- if instr.opname == "LOAD_GLOBAL":
300
- return bool(instr.argval == "NotImplementedError")
301
-
306
+ if len(instructions) >= 2 and instructions[-2][0] in ("CALL_FUNCTION", "CALL"):
307
+ for opname, arg in reversed(instructions[:-2]):
308
+ if opname == "LOAD_GLOBAL":
309
+ if sys.version_info >= (3, 11):
310
+ arg >>= 1
311
+ return arg < len(code_obj.co_names) and code_obj.co_names[arg] == "NotImplementedError"
312
+ if opname == "LOAD_COMMON_CONSTANT":
313
+ common_constants = getattr(opcode, "_common_constants", ())
314
+ return arg < len(common_constants) and common_constants[arg] is NotImplementedError
302
315
  return False
303
316
 
304
317
 
@@ -576,7 +589,7 @@ def _get_adapter(cls: AnInterfaceType, obj_type: Type) -> Optional[Callable]:
576
589
  candidate_interfaces.reverse() # prefer this class over sub-class adapters
577
590
  for subcls in candidate_interfaces:
578
591
  if type_is_interface(subcls):
579
- adapters.update(subcls._pi.adapters)
592
+ adapters.update(cast(AnInterfaceType, subcls)._pi.adapters)
580
593
  if not adapters:
581
594
  return None
582
595
 
@@ -755,7 +768,13 @@ class InterfaceType(abc.ABCMeta):
755
768
  if InterfaceType._provided_by(cls, obj, allow_implicit=allow_implicit):
756
769
  adapter = no_adaption
757
770
  else:
758
- adapter = _get_adapter(cls, type(obj))
771
+ obj_type = type(obj)
772
+ cache = cls._pi.adapter_cache
773
+ try:
774
+ adapter = cache[obj_type]
775
+ except KeyError:
776
+ cache[obj_type] = _get_adapter(cls, obj_type)
777
+ adapter = cache[obj_type]
759
778
  if adapter is None:
760
779
  raise AdaptionError("Cannot adapt {} to {}".format(obj, cls.__name__))
761
780
 
@@ -795,6 +814,9 @@ class InterfaceType(abc.ABCMeta):
795
814
  def register(cls, subclass: Type[_T]) -> Type[_T]:
796
815
  if type_is_interface(cls):
797
816
  cls._pi.registered_types.add(subclass) # type: ignore[attr-defined]
817
+ if type_is_interface(subclass):
818
+ subclass._pi.registered_by.add(cls) # type: ignore[attr-defined]
819
+ clear_adapter_caches(cls)
798
820
  return super().register(subclass)
799
821
 
800
822
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pure-interface
3
- Version: 8.4.0
3
+ Version: 8.6.0
4
4
  Summary: A Python interface library that disallows function body content on interfaces and supports adaption.
5
5
  Author-email: Tim Mitchell <tim.mitchell@seequent.com>
6
6
  License-Expression: MIT
@@ -15,9 +15,11 @@ Classifier: Programming Language :: Python :: 3.11
15
15
  Classifier: Programming Language :: Python :: 3.12
16
16
  Classifier: Programming Language :: Python :: 3.13
17
17
  Classifier: Programming Language :: Python :: 3.14
18
+ Classifier: Programming Language :: Python :: 3.15
18
19
  Requires-Python: >=3.10
19
20
  Description-Content-Type: text/x-rst
20
21
  License-File: LICENSE
22
+ Requires-Dist: build>=1.6.1
21
23
  Provides-Extra: dev
22
24
  Requires-Dist: mypy>=1.4; extra == "dev"
23
25
  Requires-Dist: tox; extra == "dev"
@@ -17,6 +17,7 @@ pure_interface.egg-info/top_level.txt
17
17
  tests/test_adapt_args_anno.py
18
18
  tests/test_adapt_args_no_anno.py
19
19
  tests/test_adapt_call.py
20
+ tests/test_adapter_cache.py
20
21
  tests/test_adaption.py
21
22
  tests/test_dataclass_support.py
22
23
  tests/test_delegate.py
@@ -1,3 +1,4 @@
1
+ build>=1.6.1
1
2
 
2
3
  [dev]
3
4
  mypy>=1.4
@@ -1,73 +1,77 @@
1
- [project]
2
- name = "pure-interface"
3
- version = "8.4.0"
4
- description = "A Python interface library that disallows function body content on interfaces and supports adaption."
5
- keywords = ["interface", "protocol", "adaption", "structural", "dataclass"]
6
- authors = [
7
- {name = "Tim Mitchell", email = "tim.mitchell@seequent.com"}
8
- ]
9
- readme = "README.rst"
10
- requires-python = ">=3.10"
11
- classifiers = [
12
- "Development Status :: 5 - Production/Stable",
13
- "Intended Audience :: Developers",
14
- "Topic :: Software Development :: Libraries",
15
- "Programming Language :: Python :: 3.10",
16
- "Programming Language :: Python :: 3.11",
17
- "Programming Language :: Python :: 3.12",
18
- "Programming Language :: Python :: 3.13",
19
- "Programming Language :: Python :: 3.14",
20
- ]
21
- license = "MIT"
22
- license-files = ["LICENSE"]
23
-
24
- [project.urls]
25
- Homepage = "https://pypi.org/project/pure-interface/"
26
- Repository = "https://github.com/seequent/pure_interface"
27
-
28
- [project.optional-dependencies]
29
- dev = ['mypy >= 1.4', 'tox']
30
- typing = ['mypy']
31
-
32
- [build-system]
33
- requires = ["setuptools", "wheel"]
34
- build-backend = "setuptools.build_meta"
35
-
36
- [tool.mypy]
37
- plugins = "pure_interface/mypy_plugin.py"
38
-
39
- [tool.black]
40
- line-length = 120
41
-
42
- [tool.isort]
43
- profile = "black"
44
-
45
- [tool.bumpversion]
46
- current_version = "8.4.0"
47
- parse = "(?P<major>\\d+)\\.(?P<minor>\\d+)\\.(?P<patch>\\d+)"
48
- serialize = ["{major}.{minor}.{patch}"]
49
- search = "{current_version}"
50
- replace = "{new_version}"
51
- regex = false
52
- ignore_missing_version = false
53
- ignore_missing_files = false
54
- tag = true
55
- sign_tags = false
56
- tag_name = "v{new_version}"
57
- tag_message = "Bump version: {current_version} → {new_version}"
58
- allow_dirty = false
59
- commit = true
60
- message = "Bump version: {current_version} → {new_version}"
61
- setup_hooks = []
62
- pre_commit_hooks = []
63
- post_commit_hooks = []
64
-
65
- [[tool.bumpversion.files]]
66
- filename = "pyproject.toml"
67
- search = 'version = "{current_version}"'
68
- replace = 'version = "{new_version}"'
69
-
70
- [[tool.bumpversion.files]]
71
- filename = "pure_interface/__init__.py"
72
- search = '__version__ = "{current_version}"'
73
- replace = '__version__ = "{new_version}"'
1
+ [project]
2
+ name = "pure-interface"
3
+ version = "8.6.0"
4
+ description = "A Python interface library that disallows function body content on interfaces and supports adaption."
5
+ keywords = ["interface", "protocol", "adaption", "structural", "dataclass"]
6
+ authors = [
7
+ {name = "Tim Mitchell", email = "tim.mitchell@seequent.com"}
8
+ ]
9
+ readme = "README.rst"
10
+ requires-python = ">=3.10"
11
+ classifiers = [
12
+ "Development Status :: 5 - Production/Stable",
13
+ "Intended Audience :: Developers",
14
+ "Topic :: Software Development :: Libraries",
15
+ "Programming Language :: Python :: 3.10",
16
+ "Programming Language :: Python :: 3.11",
17
+ "Programming Language :: Python :: 3.12",
18
+ "Programming Language :: Python :: 3.13",
19
+ "Programming Language :: Python :: 3.14",
20
+ "Programming Language :: Python :: 3.15",
21
+ ]
22
+ license = "MIT"
23
+ license-files = ["LICENSE"]
24
+ dependencies = [
25
+ "build>=1.6.1",
26
+ ]
27
+
28
+ [project.urls]
29
+ Homepage = "https://pypi.org/project/pure-interface/"
30
+ Repository = "https://github.com/seequent/pure_interface"
31
+
32
+ [project.optional-dependencies]
33
+ dev = ['mypy >= 1.4', 'tox']
34
+ typing = ['mypy']
35
+
36
+ [build-system]
37
+ requires = ["setuptools", "wheel"]
38
+ build-backend = "setuptools.build_meta"
39
+
40
+ [tool.mypy]
41
+ plugins = "pure_interface/mypy_plugin.py"
42
+
43
+ [tool.black]
44
+ line-length = 120
45
+
46
+ [tool.isort]
47
+ profile = "black"
48
+
49
+ [tool.bumpversion]
50
+ current_version = "8.6.0"
51
+ parse = "(?P<major>\\d+)\\.(?P<minor>\\d+)\\.(?P<patch>\\d+)"
52
+ serialize = ["{major}.{minor}.{patch}"]
53
+ search = "{current_version}"
54
+ replace = "{new_version}"
55
+ regex = false
56
+ ignore_missing_version = false
57
+ ignore_missing_files = false
58
+ tag = true
59
+ sign_tags = false
60
+ tag_name = "v{new_version}"
61
+ tag_message = "Bump version: {current_version} → {new_version}"
62
+ allow_dirty = false
63
+ commit = true
64
+ message = "Bump version: {current_version} → {new_version}"
65
+ setup_hooks = []
66
+ pre_commit_hooks = []
67
+ post_commit_hooks = []
68
+
69
+ [[tool.bumpversion.files]]
70
+ filename = "pyproject.toml"
71
+ search = 'version = "{current_version}"'
72
+ replace = 'version = "{new_version}"'
73
+
74
+ [[tool.bumpversion.files]]
75
+ filename = "pure_interface/__init__.py"
76
+ search = '__version__ = "{current_version}"'
77
+ replace = '__version__ = "{new_version}"'
@@ -0,0 +1,199 @@
1
+ # --------------------------------------------------------------------------------------------
2
+ # Copyright (c) 2024 Bentley Systems, Incorporated. All rights reserved.
3
+ # --------------------------------------------------------------------------------------------
4
+
5
+ import unittest
6
+ from unittest import mock
7
+
8
+ import pure_interface
9
+ from pure_interface import Interface, interface
10
+ from pure_interface.adaption import register_adapter
11
+
12
+
13
+ class IAnimal(Interface):
14
+ def speak(self):
15
+ pass
16
+
17
+
18
+ class IDog(IAnimal, Interface):
19
+ def fetch(self):
20
+ pass
21
+
22
+
23
+ class ICreature(Interface):
24
+ """Separate interface used to test cache invalidation via .register()."""
25
+
26
+ def speak(self):
27
+ pass
28
+
29
+
30
+ class Cat:
31
+ pass
32
+
33
+
34
+ class CatToIAnimal(IAnimal):
35
+ def __init__(self, obj):
36
+ pass
37
+
38
+ def speak(self):
39
+ return "meow"
40
+
41
+
42
+ class Hawk:
43
+ pass
44
+
45
+
46
+ class HawkToIDog(IDog):
47
+ def __init__(self, obj):
48
+ pass
49
+
50
+ def speak(self):
51
+ return "screech"
52
+
53
+ def fetch(self):
54
+ return "prey"
55
+
56
+
57
+ class Fish:
58
+ pass # used to test None caching and late adapter registration
59
+
60
+
61
+ class FishToIAnimal(IAnimal):
62
+ def __init__(self, obj):
63
+ pass
64
+
65
+ def speak(self):
66
+ return "blub"
67
+
68
+
69
+ class FishToIDog(IDog):
70
+ def __init__(self, obj):
71
+ pass
72
+
73
+ def speak(self):
74
+ return "blub"
75
+
76
+ def fetch(self):
77
+ return "swim"
78
+
79
+
80
+ class Iguana:
81
+ pass # used for register() test
82
+
83
+
84
+ ICreature.register(IAnimal)
85
+
86
+
87
+ def _register_adapters():
88
+ register_adapter(CatToIAnimal, Cat, IAnimal)
89
+ register_adapter(HawkToIDog, Hawk, IDog)
90
+
91
+
92
+ class TestAdapterCache(unittest.TestCase):
93
+ @classmethod
94
+ def setUpClass(cls):
95
+ pure_interface.set_is_development(True)
96
+
97
+ def setUp(self):
98
+ _register_adapters()
99
+
100
+ def tearDown(self):
101
+ IAnimal._pi.adapter_cache.clear()
102
+ IDog._pi.adapter_cache.clear()
103
+ ICreature._pi.adapter_cache.clear()
104
+ IAnimal._pi.adapters.clear()
105
+ IDog._pi.adapters.clear()
106
+
107
+ def test_adapter_cached_after_adapt(self):
108
+ IAnimal.adapt(Cat(), interface_only=False)
109
+ self.assertIn(Cat, IAnimal._pi.adapter_cache)
110
+ self.assertIs(IAnimal._pi.adapter_cache[Cat], CatToIAnimal)
111
+
112
+ def test_get_adapter_called_only_once_for_repeated_adapts(self):
113
+ cat = Cat()
114
+ with mock.patch("pure_interface.interface._get_adapter", wraps=interface._get_adapter) as mock_get:
115
+ IAnimal.adapt(cat, interface_only=False)
116
+ IAnimal.adapt(cat, interface_only=False)
117
+ mock_get.assert_called_once()
118
+
119
+ def test_none_cached_when_no_adapter_exists(self):
120
+ IAnimal.adapt_or_none(Fish(), interface_only=False)
121
+ self.assertIn(Fish, IAnimal._pi.adapter_cache)
122
+ self.assertIsNone(IAnimal._pi.adapter_cache[Fish])
123
+
124
+ def test_get_adapter_called_only_once_for_repeated_none_results(self):
125
+ fish = Fish()
126
+ with mock.patch("pure_interface.interface._get_adapter", wraps=interface._get_adapter) as mock_get:
127
+ IAnimal.adapt_or_none(fish, interface_only=False)
128
+ IAnimal.adapt_or_none(fish, interface_only=False)
129
+ mock_get.assert_called_once()
130
+
131
+ def test_clear_adapter_caches_clears_interface_cache(self):
132
+ IAnimal._pi.adapter_cache[Cat] = CatToIAnimal
133
+ interface.clear_adapter_caches(IAnimal)
134
+ self.assertEqual(len(IAnimal._pi.adapter_cache), 0)
135
+
136
+ def test_clear_adapter_caches_on_child_clears_parent_cache(self):
137
+ # IAnimal's cache should be cleared when IDog's adapters change,
138
+ # because _get_adapter(IAnimal, ...) collects adapters from IAnimal.__subclasses__()
139
+ IAnimal._pi.adapter_cache[Hawk] = None
140
+ interface.clear_adapter_caches(IDog)
141
+ self.assertNotIn(Hawk, IAnimal._pi.adapter_cache)
142
+
143
+ def test_parent_interface_finds_adapter_registered_on_child(self):
144
+ adapted = IAnimal.adapt(Hawk(), interface_only=False)
145
+ self.assertIsInstance(adapted, HawkToIDog)
146
+
147
+ def test_parent_caches_adapter_found_via_child(self):
148
+ IAnimal.adapt(Hawk(), interface_only=False)
149
+ self.assertIn(Hawk, IAnimal._pi.adapter_cache)
150
+ self.assertIs(IAnimal._pi.adapter_cache[Hawk], HawkToIDog)
151
+
152
+ def test_register_type_clears_cache(self):
153
+ IAnimal._pi.adapter_cache[Iguana] = None
154
+ IAnimal.register(Iguana)
155
+ self.assertNotIn(Iguana, IAnimal._pi.adapter_cache)
156
+
157
+ def test_register_adapter_clears_entire_cache(self):
158
+ # Pre-populate cache with an unrelated entry
159
+ IAnimal._pi.adapter_cache[Fish] = None
160
+ # Registering any adapter should wipe the whole cache
161
+ register_adapter(lambda obj: CatToIAnimal(obj), Iguana, IAnimal)
162
+ self.assertEqual(len(IAnimal._pi.adapter_cache), 0)
163
+
164
+ def test_stale_none_on_parent_cleared_when_adapter_registered_on_child(self):
165
+ # Prime a stale None on both parent and child: no adapter for Fish yet
166
+ self.assertIsNone(IAnimal.adapt_or_none(Fish(), interface_only=False))
167
+ self.assertIsNone(IDog.adapt_or_none(Fish(), interface_only=False))
168
+ self.assertIsNone(IAnimal._pi.adapter_cache[Fish])
169
+ self.assertIsNone(IDog._pi.adapter_cache[Fish])
170
+
171
+ # Registering on the child must evict the stale entry from both caches
172
+ register_adapter(FishToIDog, Fish, IDog)
173
+ self.assertNotIn(Fish, IAnimal._pi.adapter_cache)
174
+ self.assertNotIn(Fish, IDog._pi.adapter_cache)
175
+
176
+ # Parent can now adapt Fish via the child's adapter
177
+ adapted = IAnimal.adapt(Fish(), interface_only=False)
178
+ self.assertIsInstance(adapted, FishToIDog)
179
+
180
+ def test_stale_none_cleared_when_adapter_added_to_registered_interface(self):
181
+ # IAnimal is registered as a virtual subclass of ICreature at module level.
182
+ # _get_adapter(ICreature, T) therefore reads IAnimal._pi.adapters.
183
+ # If a stale None is cached on ICreature and a new adapter is later added
184
+ # to IAnimal, the stale entry must be evicted so ICreature can find the adapter.
185
+
186
+ # Prime ICreature's cache with None — no adapter for Fish exists yet
187
+ self.assertIsNone(ICreature.adapt_or_none(Fish(), interface_only=False))
188
+ self.assertIn(Fish, ICreature._pi.adapter_cache)
189
+ self.assertIsNone(ICreature._pi.adapter_cache[Fish])
190
+
191
+ # Register an adapter for Fish on IAnimal
192
+ register_adapter(FishToIAnimal, Fish, IAnimal)
193
+
194
+ # ICreature's stale None should have been evicted
195
+ self.assertNotIn(Fish, ICreature._pi.adapter_cache)
196
+
197
+ # ICreature should now successfully adapt Fish via IAnimal's adapter
198
+ adapted = ICreature.adapt(Fish(), interface_only=False)
199
+ self.assertIsInstance(adapted, FishToIAnimal)
@@ -5,12 +5,32 @@
5
5
  import abc
6
6
  import collections.abc
7
7
  import unittest
8
+ from unittest.mock import patch
8
9
 
9
10
  import pure_interface
10
11
  import pure_interface.errors
12
+ import pure_interface.interface as interface_module
11
13
 
12
14
 
13
15
  class TestNoContentChecks(unittest.TestCase):
16
+ def test_simple_empty_functions_do_not_use_extended_check(self):
17
+ def empty_with_pass():
18
+ pass
19
+
20
+ def empty_with_docstring():
21
+ """A comment."""
22
+
23
+ def empty_with_docstring_and_pass():
24
+ """A comment."""
25
+ pass
26
+
27
+ with patch.object(interface_module, "_is_not_implemented_function") as extended_check:
28
+ for func in (empty_with_pass, empty_with_docstring, empty_with_docstring_and_pass):
29
+ with self.subTest(func=func.__name__):
30
+ self.assertTrue(interface_module._is_empty_function(func))
31
+
32
+ extended_check.assert_not_called()
33
+
14
34
  def test_empty_function_passes(self):
15
35
  class IAnimal(pure_interface.Interface):
16
36
  def speak(self, volume):
File without changes
File without changes