python-wrap 0.2.1__py3-none-any.whl → 0.4.0__py3-none-any.whl

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 (88) hide show
  1. python_wrap/__init__.py +348 -1
  2. python_wrap/__main__.py +57 -0
  3. python_wrap/_backend.py +133 -0
  4. python_wrap/_buckets.py +162 -0
  5. python_wrap/_core.py +12 -3
  6. python_wrap/_data/agent_guide.md +103 -0
  7. python_wrap/_data/recipes.json +703 -0
  8. python_wrap/_fork.py +113 -0
  9. python_wrap/_integration.py +29 -0
  10. python_wrap/_runtime.py +157 -0
  11. python_wrap/adapters/__init__.py +101 -0
  12. python_wrap/adapters/_frameworks.py +251 -0
  13. python_wrap/adapters/_sdk.py +1978 -0
  14. python_wrap/adapters/anthropic.py +139 -0
  15. python_wrap/adapters/langchain.py +288 -0
  16. python_wrap/adapters/openai.py +169 -0
  17. python_wrap/adapters/openai_agents.py +468 -0
  18. python_wrap/adapters/pydantic_ai.py +459 -0
  19. python_wrap/adaptive.py +605 -0
  20. python_wrap/agents.py +2503 -0
  21. python_wrap/alerts.py +293 -0
  22. python_wrap/async_cache.py +745 -0
  23. python_wrap/batching.py +17 -4
  24. python_wrap/buffering.py +952 -0
  25. python_wrap/bulkhead.py +58 -6
  26. python_wrap/caching.py +425 -56
  27. python_wrap/celery.py +528 -0
  28. python_wrap/chaos.py +519 -0
  29. python_wrap/circuit.py +454 -23
  30. python_wrap/compat.py +267 -0
  31. python_wrap/concurrency.py +82 -1746
  32. python_wrap/config.py +25 -4
  33. python_wrap/coordination.py +638 -0
  34. python_wrap/credentials.py +126 -0
  35. python_wrap/dashboard.py +358 -0
  36. python_wrap/debounce.py +538 -0
  37. python_wrap/django.py +100 -0
  38. python_wrap/doctor.py +599 -0
  39. python_wrap/events.py +145 -4
  40. python_wrap/exporters.py +663 -0
  41. python_wrap/fastapi.py +81 -0
  42. python_wrap/flask.py +61 -0
  43. python_wrap/genai.py +1101 -0
  44. python_wrap/health.py +187 -0
  45. python_wrap/http.py +940 -0
  46. python_wrap/idempotency.py +446 -0
  47. python_wrap/introspect.py +738 -0
  48. python_wrap/lifecycle.py +620 -0
  49. python_wrap/llm.py +2574 -0
  50. python_wrap/llm_cassette.py +948 -0
  51. python_wrap/llm_http_chaos.py +326 -0
  52. python_wrap/llm_shared.py +772 -0
  53. python_wrap/llm_testing.py +990 -0
  54. python_wrap/llm_validate.py +383 -0
  55. python_wrap/local_state.py +395 -0
  56. python_wrap/logs.py +82 -26
  57. python_wrap/mcp.py +490 -0
  58. python_wrap/mcp_guard.py +357 -0
  59. python_wrap/metrics.py +6 -3
  60. python_wrap/migrate.py +1452 -0
  61. python_wrap/observability.py +484 -0
  62. python_wrap/periodic.py +24 -2
  63. python_wrap/policies.py +396 -0
  64. python_wrap/policy.py +14 -0
  65. python_wrap/predicates.py +276 -0
  66. python_wrap/presets.py +378 -0
  67. python_wrap/processing.py +227 -0
  68. python_wrap/propagation.py +62 -0
  69. python_wrap/pytest_plugin.py +85 -0
  70. python_wrap/quotas.py +319 -0
  71. python_wrap/ratelimit.py +560 -0
  72. python_wrap/redaction.py +228 -0
  73. python_wrap/retry.py +448 -70
  74. python_wrap/shared.py +653 -0
  75. python_wrap/singleflight.py +255 -0
  76. python_wrap/slow.py +72 -0
  77. python_wrap/stores.py +168 -0
  78. python_wrap/switches.py +164 -0
  79. python_wrap/testing.py +34 -8
  80. python_wrap/timeouts.py +874 -0
  81. python_wrap/timing.py +239 -17
  82. python_wrap/validation.py +187 -12
  83. python_wrap/web.py +723 -0
  84. {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/METADATA +117 -7
  85. python_wrap-0.4.0.dist-info/RECORD +95 -0
  86. python_wrap-0.2.1.dist-info/RECORD +0 -29
  87. {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/WHEEL +0 -0
  88. {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/licenses/LICENSE +0 -0
python_wrap/timing.py CHANGED
@@ -2,16 +2,19 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import asyncio
6
+ import contextvars
7
+ import functools
5
8
  import io
6
9
  import logging
7
10
  import statistics
8
11
  import sys
9
12
  import threading
10
- from collections.abc import Callable, Mapping
13
+ from collections.abc import Callable, Generator, Mapping
11
14
  from dataclasses import dataclass
12
- from typing import TYPE_CHECKING, Any, overload
15
+ from typing import TYPE_CHECKING, Any, cast, overload
13
16
 
14
- from python_wrap import _core
17
+ from python_wrap import _core, _fork
15
18
  from python_wrap._core import F, LoggerLike, P, R
16
19
  from python_wrap.logs import _instrument, _log
17
20
 
@@ -357,6 +360,74 @@ def _trace_release() -> None:
357
360
  _trace_started_by_us = False
358
361
 
359
362
 
363
+ # One measured call at a time: tracemalloc has a single, process-wide peak counter, so
364
+ # two overlapping measurements would reset and read each other's peak. The gate is
365
+ # re-entrant for the call holding it: nested measured calls, and tasks or
366
+ # ``asyncio.to_thread`` workers started inside it (they inherit the context variable),
367
+ # enter immediately instead of deadlocking on their parent.
368
+ _gate = threading.Condition(threading.Lock())
369
+ _gate_owner: object | None = None
370
+ _gate_depth = 0
371
+ _measuring: contextvars.ContextVar[object | None] = contextvars.ContextVar(
372
+ "python_wrap_measuring", default=None
373
+ )
374
+
375
+
376
+ def _reset_gate() -> None:
377
+ global _gate, _gate_owner, _gate_depth
378
+ _gate = threading.Condition(threading.Lock())
379
+ _gate_owner, _gate_depth = None, 0
380
+
381
+
382
+ _gate_fork_reset = _fork.register_reset(_reset_gate)
383
+
384
+
385
+ def _gate_try() -> object | None:
386
+ """Enter the measurement gate if free (or already ours); return its token or None."""
387
+ global _gate_owner, _gate_depth
388
+ held = _measuring.get()
389
+ with _gate:
390
+ if _gate_owner is None:
391
+ _gate_owner, _gate_depth = object(), 1
392
+ return _gate_owner
393
+ if held is not None and held is _gate_owner:
394
+ _gate_depth += 1
395
+ return held
396
+ return None
397
+
398
+
399
+ def _gate_enter() -> object:
400
+ """Block the thread until the gate is ours."""
401
+ while True:
402
+ token = _gate_try()
403
+ if token is not None:
404
+ return token
405
+ with _gate:
406
+ if _gate_owner is not None:
407
+ _gate.wait(0.05)
408
+
409
+
410
+ async def _gate_enter_async() -> object:
411
+ """Wait for the gate without blocking the event loop."""
412
+ delay = 0.001
413
+ while True:
414
+ token = _gate_try()
415
+ if token is not None:
416
+ return token
417
+ # Real sleep, not _core.async_sleep: fake clocks must not turn this into a spin.
418
+ await asyncio.sleep(delay)
419
+ delay = min(delay * 2, 0.02)
420
+
421
+
422
+ def _gate_exit() -> None:
423
+ global _gate_owner, _gate_depth
424
+ with _gate:
425
+ _gate_depth -= 1
426
+ if _gate_depth <= 0:
427
+ _gate_owner, _gate_depth = None, 0
428
+ _gate.notify_all()
429
+
430
+
360
431
  @overload
361
432
  def measure_memory(func: F, /) -> F: ...
362
433
  @overload
@@ -367,6 +438,7 @@ def measure_memory(
367
438
  logger: LoggerLike = None,
368
439
  level: int = logging.INFO,
369
440
  callback: Callable[[MemoryRecord], None] | None = None,
441
+ exclusive: bool = True,
370
442
  ) -> Callable[[F], F]: ...
371
443
  def measure_memory(
372
444
  func: Callable[..., Any] | None = None,
@@ -375,6 +447,7 @@ def measure_memory(
375
447
  logger: LoggerLike = None,
376
448
  level: int = logging.INFO,
377
449
  callback: Callable[[MemoryRecord], None] | None = None,
450
+ exclusive: bool = True,
378
451
  ) -> Any:
379
452
  """Measure the Python memory a call allocates, using `tracemalloc`.
380
453
 
@@ -383,17 +456,29 @@ def measure_memory(
383
456
  running and stopped afterwards only if this decorator started it. Logs
384
457
  ``<name> peak memory 1.00 MiB (net +12.00 KiB)``.
385
458
 
459
+ Measured calls are serialised (``exclusive=True``, the default): ``tracemalloc``
460
+ has one process-wide peak counter, so overlapping measurements would reset and read
461
+ each other's peak. A measured call made while another is running in a different
462
+ thread or task waits for it to finish (threads block, coroutines wait with
463
+ ``await``). Nested measured calls, and tasks or ``asyncio.to_thread`` workers started
464
+ inside a measured call, do not wait: they are part of the outer measurement.
465
+
386
466
  Note:
387
- ``tracemalloc`` is process-global: allocations made by other threads or asyncio
388
- tasks while the call runs are counted too, and the peak counter is reset at the
389
- start of every measured call. Only memory allocated by Python (not by C
467
+ ``tracemalloc`` is process-global: allocations made by *unmeasured* threads or
468
+ asyncio tasks while the call runs are still counted, and a nested measured call
469
+ resets the outer call's peak. Only memory allocated by Python (not by C
390
470
  extensions that bypass its allocator) is seen, and tracing slows the program.
471
+ A measured function that starts a plain `threading.Thread` running *another*
472
+ measured function and then joins it would wait forever with ``exclusive=True``;
473
+ use ``exclusive=False`` there (measurements may then overlap).
391
474
 
392
475
  Args:
393
476
  func: The function, when used as a bare ``@measure_memory``.
394
477
  logger: A ``logging.Logger``, a logger name, or ``None`` for the package logger.
395
478
  level: Log level.
396
479
  callback: Called with a `MemoryRecord` for every call.
480
+ exclusive: Serialise measured calls process-wide so their numbers are not
481
+ mixed up. ``False`` restores the unserialised behaviour.
397
482
 
398
483
  Returns:
399
484
  The decorated function, with its signature preserved.
@@ -410,12 +495,12 @@ def measure_memory(
410
495
  lg = _core.get_logger(logger)
411
496
  name = _core.qualname(f)
412
497
 
413
- def start(args: tuple[Any, ...], kwargs: dict[str, Any]) -> int:
498
+ def begin() -> int:
414
499
  _trace_acquire()
415
500
  tracemalloc.reset_peak()
416
501
  return tracemalloc.get_traced_memory()[0]
417
502
 
418
- def finish(baseline: int, ok: bool, value: Any) -> None:
503
+ def report(baseline: int) -> None:
419
504
  current, peak = tracemalloc.get_traced_memory()
420
505
  _trace_release()
421
506
  record = MemoryRecord(name, max(peak - baseline, 0), current - baseline)
@@ -428,7 +513,55 @@ def measure_memory(
428
513
  )
429
514
  _safe_callback(lg, callback, record, name)
430
515
 
431
- return _instrument(f, start, finish)
516
+ if not exclusive:
517
+
518
+ def start(args: tuple[Any, ...], kwargs: dict[str, Any]) -> int:
519
+ return begin()
520
+
521
+ def finish(baseline: int, ok: bool, value: Any) -> None:
522
+ report(baseline)
523
+
524
+ return _instrument(f, start, finish)
525
+
526
+ def safe_report(baseline: int) -> None:
527
+ try:
528
+ report(baseline)
529
+ except Exception:
530
+ lg.exception("%s: logging hook failed", name)
531
+
532
+ if _core.is_async(f):
533
+
534
+ @functools.wraps(f)
535
+ async def awrapper(*args: Any, **kwargs: Any) -> Any:
536
+ token = await _gate_enter_async()
537
+ marker = _measuring.set(token)
538
+ try:
539
+ baseline = begin()
540
+ try:
541
+ return await f(*args, **kwargs) # type: ignore[misc]
542
+ finally:
543
+ safe_report(baseline)
544
+ finally:
545
+ _measuring.reset(marker)
546
+ _gate_exit()
547
+
548
+ return cast("Callable[P, R]", awrapper)
549
+
550
+ @functools.wraps(f)
551
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
552
+ token = _gate_enter()
553
+ marker = _measuring.set(token)
554
+ try:
555
+ baseline = begin()
556
+ try:
557
+ return f(*args, **kwargs)
558
+ finally:
559
+ safe_report(baseline)
560
+ finally:
561
+ _measuring.reset(marker)
562
+ _gate_exit()
563
+
564
+ return cast("Callable[P, R]", wrapper)
432
565
 
433
566
  return decorate if func is None else decorate(func)
434
567
 
@@ -441,6 +574,55 @@ def _another_profiler_active() -> bool:
441
574
  return sys.version_info < (3, 12) and sys.getprofile() is not None
442
575
 
443
576
 
577
+ class _PassThrough:
578
+ """Hand one value a coroutine yielded up to the event loop, and the reply back."""
579
+
580
+ __slots__ = ("value",)
581
+
582
+ def __init__(self, value: Any) -> None:
583
+ self.value = value
584
+
585
+ def __await__(self) -> Generator[Any, Any, Any]:
586
+ return (yield self.value)
587
+
588
+
589
+ async def _drive_profiled(
590
+ coro: Any, enable: Callable[[], bool], disable: Callable[[], None]
591
+ ) -> Any:
592
+ """Run ``coro`` step by step, profiling only its own steps.
593
+
594
+ The profiler is switched on just before each step of the coroutine and off as soon
595
+ as it suspends, so whatever the event loop runs for other tasks while this one is
596
+ waiting is not attributed to it.
597
+ """
598
+ if not hasattr(coro, "send"): # an awaitable that is not a coroutine: run it whole
599
+ return await coro
600
+ send: Any = None
601
+ error: BaseException | None = None
602
+ finished = False
603
+ try:
604
+ while True:
605
+ active = enable()
606
+ try:
607
+ yielded = coro.send(send) if error is None else coro.throw(error)
608
+ except StopIteration as stop:
609
+ finished = True
610
+ return stop.value
611
+ except BaseException:
612
+ finished = True
613
+ raise
614
+ finally:
615
+ if active:
616
+ disable()
617
+ try:
618
+ send, error = await _PassThrough(yielded), None
619
+ except BaseException as exc: # cancellation and errors go into the coroutine
620
+ send, error = None, exc
621
+ finally:
622
+ if not finished:
623
+ coro.close()
624
+
625
+
444
626
  @overload
445
627
  def profile(func: F, /) -> F: ...
446
628
  @overload
@@ -469,10 +651,19 @@ def profile(
469
651
  If another profiler is already active (Python 3.12+ raises ``ValueError`` when
470
652
  profilers nest), a warning is logged once and the function simply runs unprofiled.
471
653
 
472
- Note:
473
- For ``async def`` functions the profiler is enabled for the whole awaited
474
- coroutine, so work the event loop does for *other* tasks while this one is
475
- suspended is included in the results.
654
+ For ``async def`` functions the profiler is switched on only while *this* coroutine
655
+ is running: it is turned off every time the coroutine suspends at an ``await`` and
656
+ back on when it resumes. Work the event loop does for other tasks in the meantime is
657
+ therefore not included, and neither is time spent waiting.
658
+
659
+ Warning:
660
+ `cProfile` is process-wide on Python 3.12+ and thread-wide before that. Only one
661
+ profiled call can be measured at a time in a thread (3.12+: in the process);
662
+ overlapping profiled calls, including concurrent tasks of the same ``async
663
+ def`` function, run unprofiled and the warning above is logged. Work an async
664
+ function hands to other threads (``asyncio.to_thread``, executors) or to tasks
665
+ it creates is not profiled either. Use ``profile`` for focused investigations,
666
+ not on hot concurrent paths.
476
667
 
477
668
  Args:
478
669
  func: The function, when used as a bare ``@profile``.
@@ -502,9 +693,8 @@ def profile(
502
693
  name = _core.qualname(f)
503
694
  warned = False
504
695
 
505
- def start(args: tuple[Any, ...], kwargs: dict[str, Any]) -> cProfile.Profile | None:
696
+ def switch_on(profiler: cProfile.Profile) -> bool:
506
697
  nonlocal warned
507
- profiler = cProfile.Profile()
508
698
  try:
509
699
  if _another_profiler_active():
510
700
  raise ValueError("another profiler is active")
@@ -513,13 +703,20 @@ def profile(
513
703
  if not warned:
514
704
  warned = True
515
705
  lg.warning("Another profiler is active; running %s unprofiled", name)
516
- return None
517
- return profiler
706
+ return False
707
+ return True
708
+
709
+ def start(args: tuple[Any, ...], kwargs: dict[str, Any]) -> cProfile.Profile | None:
710
+ profiler = cProfile.Profile()
711
+ return profiler if switch_on(profiler) else None
518
712
 
519
713
  def finish(profiler: cProfile.Profile | None, ok: bool, value: Any) -> None:
520
714
  if profiler is None:
521
715
  return
522
716
  profiler.disable()
717
+ report(profiler)
718
+
719
+ def report(profiler: cProfile.Profile) -> None:
523
720
  stream = io.StringIO()
524
721
  stats = pstats.Stats(profiler, stream=stream).sort_stats(sort_key)
525
722
  if lg.isEnabledFor(level):
@@ -530,6 +727,31 @@ def profile(
530
727
  lg.log(level, "Profile of %s:\n%s", name, stream.getvalue().rstrip())
531
728
  _safe_callback(lg, callback, stats, name)
532
729
 
730
+ if _core.is_async(f):
731
+
732
+ @functools.wraps(f)
733
+ async def awrapper(*args: Any, **kwargs: Any) -> Any:
734
+ profiler = cProfile.Profile()
735
+ stepped = False
736
+
737
+ def enable() -> bool:
738
+ nonlocal stepped
739
+ if switch_on(profiler):
740
+ stepped = True
741
+ return True
742
+ return False
743
+
744
+ try:
745
+ return await _drive_profiled(f(*args, **kwargs), enable, profiler.disable)
746
+ finally:
747
+ if stepped:
748
+ try:
749
+ report(profiler)
750
+ except Exception:
751
+ lg.exception("%s: logging hook failed", name)
752
+
753
+ return cast("Callable[P, R]", awrapper)
754
+
533
755
  return _instrument(f, start, finish)
534
756
 
535
757
  return decorate if func is None else decorate(func)
python_wrap/validation.py CHANGED
@@ -18,11 +18,14 @@ Checked: plain classes (``int`` also accepts ``bool``; ``float`` accepts ``int``
18
18
  ``Mapping[K, V]`` (elements checked) and ``Iterable[T]`` / ``Iterator[T]`` / ``Generator``
19
19
  (``isinstance`` only, iterators are never consumed), ``Callable`` (``callable()`` only),
20
20
  ``type[T]``, ``TypeVar`` (bound or constraints, otherwise anything), ``Annotated[T, ...]``
21
- (checks ``T``), ``NewType`` (checks the supertype) and ``runtime_checkable`` protocols.
21
+ (checks ``T``), ``NewType`` (checks the supertype), ``runtime_checkable`` protocols (also
22
+ when parameterised, ``isinstance`` only) and ``TypedDict`` (a dict with every required key,
23
+ each present key checked against its annotation; extra keys are allowed).
22
24
 
23
- Accepted without checking: ``TypedDict``, protocols that are not ``runtime_checkable``,
25
+ Accepted without checking by default: protocols that are not ``runtime_checkable``,
24
26
  forward references that cannot be resolved and any other construct this module does not
25
- understand. A check that cannot be performed never raises.
27
+ understand. A check that cannot be performed never raises. Pass
28
+ ``enforce_types(strict=True)`` to raise `UnsupportedAnnotationError` for those instead.
26
29
  """
27
30
 
28
31
  from __future__ import annotations
@@ -40,12 +43,29 @@ from typing import Any, TypeVar, Union, cast, overload
40
43
  from python_wrap import _core, errors
41
44
  from python_wrap._core import F, P, R
42
45
 
43
- __all__ = ["check_type", "enforce_types", "validate_args"]
46
+ __all__ = ["UnsupportedAnnotationError", "check_type", "enforce_types", "validate_args"]
44
47
 
45
48
  Validator = Callable[[Any], object] | tuple[Callable[[Any], object], str]
46
49
 
47
50
  _NoneType = type(None)
48
51
  _UnionType = getattr(types, "UnionType", None)
52
+ _NEVER: tuple[Any, ...] = tuple(
53
+ item for item in (typing.NoReturn, getattr(typing, "Never", None)) if item is not None
54
+ )
55
+
56
+
57
+ class UnsupportedAnnotationError(errors.PythonWrapError, TypeError):
58
+ """``enforce_types(strict=True)`` met an annotation it cannot check at runtime.
59
+
60
+ Attributes:
61
+ parameter: The parameter name, or ``"return"``.
62
+ annotation: The offending annotation.
63
+ """
64
+
65
+ def __init__(self, message: str, *, parameter: str, annotation: Any) -> None:
66
+ super().__init__(message)
67
+ self.parameter = parameter
68
+ self.annotation = annotation
49
69
 
50
70
 
51
71
  def _repr(value: object) -> str:
@@ -391,6 +411,38 @@ def _check_tuple(value: Any, hint_args: tuple[Any, ...]) -> str | None:
391
411
  return None
392
412
 
393
413
 
414
+ @functools.lru_cache(maxsize=256)
415
+ def _typeddict_fields(td: Any) -> tuple[dict[str, Any], frozenset[str]] | None:
416
+ """Resolved field annotations and required keys of a TypedDict, or None."""
417
+ try:
418
+ hints = typing.get_type_hints(td)
419
+ except Exception:
420
+ return None
421
+ return hints, frozenset(getattr(td, "__required_keys__", hints))
422
+
423
+
424
+ def _check_typeddict(value: Any, hint: Any) -> str | None:
425
+ if not isinstance(value, cabc.Mapping):
426
+ return _got(value)
427
+ fields = _typeddict_fields(hint)
428
+ if fields is None:
429
+ return None # unresolvable annotations: accepted (strict mode rejects earlier)
430
+ hints, required = fields
431
+ for key in sorted(required):
432
+ if key not in value:
433
+ return f"{_got(value)} missing key {key!r}"
434
+ for key, field_hint in hints.items():
435
+ if key not in value:
436
+ continue
437
+ item = value[key]
438
+ problem = _mismatch(item, field_hint)
439
+ if problem is not None:
440
+ if " " not in problem:
441
+ return f"{_got(value)} with {problem} value at key {key!r}"
442
+ return f"{_got(value)} with {_got(item)} value at key {key!r} ({problem})"
443
+ return None
444
+
445
+
394
446
  def _mismatch(value: Any, hint: Any) -> str | None:
395
447
  """Return a description of what ``value`` is if it violates ``hint``, else ``None``."""
396
448
  if hint is Any or hint is object or isinstance(hint, (str, typing.ForwardRef)):
@@ -428,7 +480,7 @@ def _mismatch(value: Any, hint: Any) -> str | None:
428
480
  return _got(value) if not isinstance(value, (str, int, bytes, bool)) else _repr(value)
429
481
  if origin is None:
430
482
  if typing.is_typeddict(hint):
431
- return None
483
+ return _check_typeddict(value, hint)
432
484
  if hint is typing.Callable or hint is cabc.Callable:
433
485
  return None if callable(value) else _got(value)
434
486
  if isinstance(hint, type):
@@ -468,7 +520,9 @@ def _mismatch(value: Any, hint: Any) -> str | None:
468
520
  if not isinstance(origin, type):
469
521
  return None
470
522
  if getattr(origin, "_is_protocol", False):
471
- return None
523
+ if not getattr(origin, "_is_runtime_protocol", False):
524
+ return None
525
+ return None if _isinstance(value, origin) else _got(value)
472
526
  if not _isinstance(value, origin):
473
527
  return _got(value)
474
528
 
@@ -481,6 +535,78 @@ def _mismatch(value: Any, hint: Any) -> str | None:
481
535
  return None # Iterable/Iterator/other generics: isinstance only
482
536
 
483
537
 
538
+ def _unsupported(hint: Any, seen: frozenset[int] = frozenset()) -> str | None:
539
+ """Why ``hint`` (or a part of it) cannot be fully checked, or None if it can.
540
+
541
+ Mirrors `_mismatch`: everything it accepts without looking is reported here.
542
+ ``Callable[...]`` (checked with ``callable()``), ``Iterable[T]``-style generics and
543
+ user generic classes (``isinstance`` on the origin only) are documented partial
544
+ checks and are not reported.
545
+ """
546
+ if hint is Any or hint is object or hint is None or hint is _NoneType or hint in _NEVER:
547
+ return None
548
+ if isinstance(hint, (str, typing.ForwardRef)):
549
+ return f"the forward reference {_fmt(hint)!r} could not be resolved"
550
+ if isinstance(hint, TypeVar):
551
+ parts: tuple[Any, ...] = (
552
+ (hint.__bound__,) if hint.__bound__ is not None else hint.__constraints__
553
+ )
554
+ return next((r for r in (_unsupported(p, seen) for p in parts) if r), None)
555
+ supertype = getattr(hint, "__supertype__", None)
556
+ if supertype is not None:
557
+ return _unsupported(supertype, seen)
558
+ origin = typing.get_origin(hint)
559
+ args = typing.get_args(hint)
560
+ if origin is typing.Annotated:
561
+ return _unsupported(args[0], seen)
562
+ if origin is Union or (_UnionType is not None and origin is _UnionType):
563
+ return next((r for r in (_unsupported(a, seen) for a in args) if r), None)
564
+ if origin is typing.Literal:
565
+ return None
566
+ if origin is None:
567
+ if typing.is_typeddict(hint):
568
+ if id(hint) in seen:
569
+ return None # recursive TypedDict: already being checked
570
+ fields = _typeddict_fields(hint)
571
+ if fields is None:
572
+ return f"the annotations of TypedDict {_fmt(hint)} could not be resolved"
573
+ inner = seen | {id(hint)}
574
+ for key, field_hint in fields[0].items():
575
+ reason = _unsupported(field_hint, inner)
576
+ if reason:
577
+ return f"key {key!r} of {_fmt(hint)}: {reason}"
578
+ return None
579
+ if hint is typing.Callable or hint is cabc.Callable:
580
+ return None
581
+ if isinstance(hint, type):
582
+ if getattr(hint, "_is_protocol", False) and not getattr(
583
+ hint, "_is_runtime_protocol", False
584
+ ):
585
+ return f"protocol {_fmt(hint)} is not @runtime_checkable"
586
+ return None
587
+ return f"{_fmt(hint)} cannot be checked at runtime"
588
+ if origin is cabc.Callable or origin is type:
589
+ return None
590
+ if not isinstance(origin, type):
591
+ return f"{_fmt(hint)} cannot be checked at runtime"
592
+ if getattr(origin, "_is_protocol", False):
593
+ if not getattr(origin, "_is_runtime_protocol", False):
594
+ return f"protocol {_fmt(origin)} is not @runtime_checkable"
595
+ return None
596
+ if (
597
+ origin in (list, set, frozenset, dict, tuple)
598
+ or origin in _ELEMENT_CHECKED_ABCS
599
+ or origin in _MAPPING_ABCS
600
+ ):
601
+ for arg in args:
602
+ if arg is Ellipsis or arg == ():
603
+ continue
604
+ reason = _unsupported(arg, seen)
605
+ if reason:
606
+ return reason
607
+ return None
608
+
609
+
484
610
  _QUICK_METAS: tuple[type, ...] = (type, abc.ABCMeta)
485
611
 
486
612
 
@@ -537,9 +663,10 @@ class _Plan:
537
663
  class _Checker:
538
664
  """Lazily resolves annotations on first call and checks calls against them."""
539
665
 
540
- def __init__(self, func: Callable[..., Any], check_return: bool) -> None:
666
+ def __init__(self, func: Callable[..., Any], check_return: bool, strict: bool = False) -> None:
541
667
  self.func = func
542
668
  self.check_return = check_return
669
+ self.strict = strict
543
670
  self.sig = inspect.signature(func)
544
671
  layout = _plain_layout(self.sig)
545
672
  self.layout = None if layout is None else (layout[0], layout[1])
@@ -552,14 +679,45 @@ class _Checker:
552
679
  return plan
553
680
  try:
554
681
  hints = typing.get_type_hints(self.func)
555
- except Exception:
682
+ except Exception as exc:
683
+ if self.strict:
684
+ raise UnsupportedAnnotationError(
685
+ f"enforce_types(strict=True): the annotations of "
686
+ f"{_core.qualname(self.func)} could not be resolved ({exc})",
687
+ parameter="",
688
+ annotation=None,
689
+ ) from exc
556
690
  # Unresolvable forward reference (so far): fall back to raw annotations, where
557
691
  # strings are accepted, and try again on the next call.
558
692
  return _Plan(dict(getattr(self.func, "__annotations__", {})), self.layout)
693
+ if self.strict:
694
+ self._reject_unsupported(hints)
559
695
  self.hints = hints
560
696
  self.plan = plan = _Plan(hints, self.layout)
561
697
  return plan
562
698
 
699
+ def _reject_unsupported(self, hints: dict[str, Any]) -> None:
700
+ for name, hint in hints.items():
701
+ if name == "return" and not self.check_return:
702
+ continue
703
+ reason = _unsupported(hint)
704
+ if reason is not None:
705
+ what = "the return annotation" if name == "return" else f"parameter {name!r}"
706
+ raise UnsupportedAnnotationError(
707
+ f"enforce_types(strict=True): {what} of {_core.qualname(self.func)} "
708
+ f"is {_fmt(hint)}, which cannot be checked: {reason}",
709
+ parameter=name,
710
+ annotation=hint,
711
+ )
712
+
713
+ def prepare(self) -> None:
714
+ """Resolve and vet annotations now if possible (strict mode, at decoration)."""
715
+ try:
716
+ typing.get_type_hints(self.func)
717
+ except Exception:
718
+ return # maybe a forward reference to something defined later: retry on call
719
+ self._get_plan()
720
+
563
721
  @staticmethod
564
722
  def _fail(label: str, hint: Any, value: Any, problem: str, what: str) -> typing.NoReturn:
565
723
  raise errors.ArgumentTypeError(
@@ -623,8 +781,16 @@ class _Checker:
623
781
  @overload
624
782
  def enforce_types(func: F, /) -> F: ...
625
783
  @overload
626
- def enforce_types(func: None = None, /, *, check_return: bool = True) -> Callable[[F], F]: ...
627
- def enforce_types(func: Callable[..., Any] | None = None, /, *, check_return: bool = True) -> Any:
784
+ def enforce_types(
785
+ func: None = None, /, *, check_return: bool = True, strict: bool = False
786
+ ) -> Callable[[F], F]: ...
787
+ def enforce_types(
788
+ func: Callable[..., Any] | None = None,
789
+ /,
790
+ *,
791
+ check_return: bool = True,
792
+ strict: bool = False,
793
+ ) -> Any:
628
794
  """Check arguments and the return value against the function's own annotations.
629
795
 
630
796
  Annotations are resolved lazily on the first call with `typing.get_type_hints`, so
@@ -633,11 +799,16 @@ def enforce_types(func: Callable[..., Any] | None = None, /, *, check_return: bo
633
799
  subset of annotations is listed under "Annotations supported by `enforce_types`" in
634
800
  the `python_wrap.validation` module docstring (the top of its API reference page) and
635
801
  in the [validation guide](../features/correctness/validation.md); anything
636
- unsupported is accepted rather than rejected.
802
+ unsupported is accepted rather than rejected, unless ``strict=True``.
637
803
 
638
804
  Args:
639
805
  func: The function (when used as a bare ``@enforce_types``).
640
806
  check_return: Also check the return value against the return annotation.
807
+ strict: Raise `UnsupportedAnnotationError` instead of silently accepting an
808
+ annotation that cannot be checked (a protocol that is not
809
+ ``runtime_checkable``, an unresolvable forward reference, ``ClassVar``,
810
+ ``Self`` and similar). Checked when the decorator is applied if the
811
+ annotations resolve then, otherwise on the first call.
641
812
 
642
813
  Returns:
643
814
  The wrapped function, or a decorator when called with options.
@@ -646,6 +817,8 @@ def enforce_types(func: Callable[..., Any] | None = None, /, *, check_return: bo
646
817
  python_wrap.errors.ArgumentTypeError: On a mismatch (a ``TypeError``), with a message
647
818
  such as ``parameter 'items' expected list[int], got list containing str at
648
819
  index 2``. ``error.parameter`` is ``"return"`` for the return value.
820
+ UnsupportedAnnotationError: With ``strict=True``, for an annotation that cannot
821
+ be checked (also a ``TypeError``).
649
822
 
650
823
  Example:
651
824
  >>> @enforce_types
@@ -656,7 +829,9 @@ def enforce_types(func: Callable[..., Any] | None = None, /, *, check_return: bo
656
829
  """
657
830
 
658
831
  def decorate(f: Callable[P, R]) -> Callable[P, R]:
659
- checker = _Checker(f, check_return)
832
+ checker = _Checker(f, check_return, strict)
833
+ if strict:
834
+ checker.prepare()
660
835
  return _wrap(f, checker.before, checker.after if check_return else None)
661
836
 
662
837
  return decorate if func is None else decorate(func)