typeguard 4.5.2__tar.gz → 4.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 (66) hide show
  1. {typeguard-4.5.2 → typeguard-4.6.0}/.github/workflows/publish.yml +2 -2
  2. {typeguard-4.5.2 → typeguard-4.6.0}/.github/workflows/test.yml +2 -2
  3. {typeguard-4.5.2 → typeguard-4.6.0}/.pre-commit-config.yaml +2 -2
  4. {typeguard-4.5.2 → typeguard-4.6.0}/PKG-INFO +3 -4
  5. {typeguard-4.5.2 → typeguard-4.6.0}/docs/userguide.rst +17 -3
  6. {typeguard-4.5.2 → typeguard-4.6.0}/docs/versionhistory.rst +32 -1
  7. {typeguard-4.5.2 → typeguard-4.6.0}/pyproject.toml +4 -4
  8. {typeguard-4.5.2 → typeguard-4.6.0}/src/typeguard/_checkers.py +38 -28
  9. {typeguard-4.5.2 → typeguard-4.6.0}/src/typeguard/_decorators.py +1 -1
  10. {typeguard-4.5.2 → typeguard-4.6.0}/src/typeguard/_functions.py +1 -5
  11. {typeguard-4.5.2 → typeguard-4.6.0}/src/typeguard/_importhook.py +60 -19
  12. {typeguard-4.5.2 → typeguard-4.6.0}/src/typeguard/_pytest_plugin.py +15 -1
  13. {typeguard-4.5.2 → typeguard-4.6.0}/src/typeguard/_suppression.py +1 -7
  14. {typeguard-4.5.2 → typeguard-4.6.0}/src/typeguard/_transformer.py +23 -23
  15. {typeguard-4.5.2 → typeguard-4.6.0}/src/typeguard/_utils.py +3 -16
  16. {typeguard-4.5.2 → typeguard-4.6.0}/src/typeguard.egg-info/PKG-INFO +3 -4
  17. {typeguard-4.5.2 → typeguard-4.6.0}/src/typeguard.egg-info/SOURCES.txt +2 -0
  18. typeguard-4.6.0/src/typeguard.egg-info/requires.txt +1 -0
  19. typeguard-4.6.0/src/typeguard.egg-info/scm_file_list.json +59 -0
  20. typeguard-4.6.0/src/typeguard.egg-info/scm_version.json +8 -0
  21. {typeguard-4.5.2 → typeguard-4.6.0}/tests/__init__.py +1 -2
  22. {typeguard-4.5.2 → typeguard-4.6.0}/tests/conftest.py +1 -3
  23. {typeguard-4.5.2 → typeguard-4.6.0}/tests/dummymodule.py +7 -6
  24. {typeguard-4.5.2 → typeguard-4.6.0}/tests/test_checkers.py +65 -26
  25. {typeguard-4.5.2 → typeguard-4.6.0}/tests/test_importhook.py +32 -1
  26. {typeguard-4.5.2 → typeguard-4.6.0}/tests/test_instrumentation.py +10 -0
  27. {typeguard-4.5.2 → typeguard-4.6.0}/tests/test_pytest_plugin.py +37 -0
  28. {typeguard-4.5.2 → typeguard-4.6.0}/tests/test_transformer.py +31 -32
  29. {typeguard-4.5.2 → typeguard-4.6.0}/tests/test_typechecked.py +58 -1
  30. typeguard-4.5.2/src/typeguard.egg-info/requires.txt +0 -4
  31. {typeguard-4.5.2 → typeguard-4.6.0}/.github/FUNDING.yml +0 -0
  32. {typeguard-4.5.2 → typeguard-4.6.0}/.github/ISSUE_TEMPLATE/bug_report.yaml +0 -0
  33. {typeguard-4.5.2 → typeguard-4.6.0}/.github/ISSUE_TEMPLATE/config.yml +0 -0
  34. {typeguard-4.5.2 → typeguard-4.6.0}/.github/ISSUE_TEMPLATE/features_request.yaml +0 -0
  35. {typeguard-4.5.2 → typeguard-4.6.0}/.github/SECURITY.md +0 -0
  36. {typeguard-4.5.2 → typeguard-4.6.0}/.github/dependabot.yml +0 -0
  37. {typeguard-4.5.2 → typeguard-4.6.0}/.github/pull_request_template.md +0 -0
  38. {typeguard-4.5.2 → typeguard-4.6.0}/.gitignore +0 -0
  39. {typeguard-4.5.2 → typeguard-4.6.0}/.readthedocs.yml +0 -0
  40. {typeguard-4.5.2 → typeguard-4.6.0}/LICENSE +0 -0
  41. {typeguard-4.5.2 → typeguard-4.6.0}/README.rst +0 -0
  42. {typeguard-4.5.2 → typeguard-4.6.0}/docs/api.rst +0 -0
  43. {typeguard-4.5.2 → typeguard-4.6.0}/docs/conf.py +0 -0
  44. {typeguard-4.5.2 → typeguard-4.6.0}/docs/contributing.rst +0 -0
  45. {typeguard-4.5.2 → typeguard-4.6.0}/docs/extending.rst +0 -0
  46. {typeguard-4.5.2 → typeguard-4.6.0}/docs/features.rst +0 -0
  47. {typeguard-4.5.2 → typeguard-4.6.0}/docs/index.rst +0 -0
  48. {typeguard-4.5.2 → typeguard-4.6.0}/setup.cfg +0 -0
  49. {typeguard-4.5.2 → typeguard-4.6.0}/src/typeguard/__init__.py +0 -0
  50. {typeguard-4.5.2 → typeguard-4.6.0}/src/typeguard/_config.py +0 -0
  51. {typeguard-4.5.2 → typeguard-4.6.0}/src/typeguard/_exceptions.py +0 -0
  52. {typeguard-4.5.2 → typeguard-4.6.0}/src/typeguard/_memo.py +0 -0
  53. {typeguard-4.5.2 → typeguard-4.6.0}/src/typeguard/py.typed +0 -0
  54. {typeguard-4.5.2 → typeguard-4.6.0}/src/typeguard.egg-info/dependency_links.txt +0 -0
  55. {typeguard-4.5.2 → typeguard-4.6.0}/src/typeguard.egg-info/entry_points.txt +0 -0
  56. {typeguard-4.5.2 → typeguard-4.6.0}/src/typeguard.egg-info/top_level.txt +0 -0
  57. {typeguard-4.5.2 → typeguard-4.6.0}/tests/deferredannos.py +0 -0
  58. {typeguard-4.5.2 → typeguard-4.6.0}/tests/dummymodule_py312.py +0 -0
  59. {typeguard-4.5.2 → typeguard-4.6.0}/tests/mypy/negative.py +0 -0
  60. {typeguard-4.5.2 → typeguard-4.6.0}/tests/mypy/positive.py +0 -0
  61. {typeguard-4.5.2 → typeguard-4.6.0}/tests/mypy/test_type_annotations.py +0 -0
  62. {typeguard-4.5.2 → typeguard-4.6.0}/tests/test_functions.py +0 -0
  63. {typeguard-4.5.2 → typeguard-4.6.0}/tests/test_plugins.py +0 -0
  64. {typeguard-4.5.2 → typeguard-4.6.0}/tests/test_suppression.py +0 -0
  65. {typeguard-4.5.2 → typeguard-4.6.0}/tests/test_utils.py +0 -0
  66. {typeguard-4.5.2 → typeguard-4.6.0}/tests/test_warn_on_error.py +0 -0
@@ -14,7 +14,7 @@ jobs:
14
14
  runs-on: ubuntu-latest
15
15
  environment: release
16
16
  steps:
17
- - uses: actions/checkout@v6
17
+ - uses: actions/checkout@v7
18
18
  - name: Set up Python
19
19
  uses: actions/setup-python@v6
20
20
  with:
@@ -52,7 +52,7 @@ jobs:
52
52
  permissions:
53
53
  contents: write
54
54
  steps:
55
- - uses: actions/checkout@v6
55
+ - uses: actions/checkout@v7
56
56
  - id: changelog
57
57
  uses: agronholm/release-notes@v1
58
58
  with:
@@ -10,10 +10,10 @@ jobs:
10
10
  strategy:
11
11
  fail-fast: false
12
12
  matrix:
13
- python-version: ["3.9", "3.10", "3.11", "3.12", "3.13", "3.14", pypy-3.11]
13
+ python-version: ["3.10", "3.11", "3.12", "3.13", "3.14", "3.15", pypy-3.11]
14
14
  runs-on: ubuntu-latest
15
15
  steps:
16
- - uses: actions/checkout@v6
16
+ - uses: actions/checkout@v7
17
17
  - name: Set up Python ${{ matrix.python-version }}
18
18
  uses: actions/setup-python@v6
19
19
  with:
@@ -14,14 +14,14 @@ repos:
14
14
  - id: trailing-whitespace
15
15
 
16
16
  - repo: https://github.com/astral-sh/ruff-pre-commit
17
- rev: v0.15.0
17
+ rev: v0.15.20
18
18
  hooks:
19
19
  - id: ruff
20
20
  args: [--fix, --show-fixes]
21
21
  - id: ruff-format
22
22
 
23
23
  - repo: https://github.com/pre-commit/mirrors-mypy
24
- rev: v1.19.1
24
+ rev: v2.1.0
25
25
  hooks:
26
26
  - id: mypy
27
27
  pass_filenames: false
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: typeguard
3
- Version: 4.5.2
3
+ Version: 4.6.0
4
4
  Summary: Run-time type checker for Python
5
5
  Author-email: Alex Grönholm <alex.gronholm@nextday.fi>
6
6
  License-Expression: MIT
@@ -12,16 +12,15 @@ Classifier: Development Status :: 5 - Production/Stable
12
12
  Classifier: Intended Audience :: Developers
13
13
  Classifier: Programming Language :: Python
14
14
  Classifier: Programming Language :: Python :: 3
15
- Classifier: Programming Language :: Python :: 3.9
16
15
  Classifier: Programming Language :: Python :: 3.10
17
16
  Classifier: Programming Language :: Python :: 3.11
18
17
  Classifier: Programming Language :: Python :: 3.12
19
18
  Classifier: Programming Language :: Python :: 3.13
20
19
  Classifier: Programming Language :: Python :: 3.14
21
- Requires-Python: >=3.9
20
+ Classifier: Programming Language :: Python :: 3.15
21
+ Requires-Python: >=3.10
22
22
  Description-Content-Type: text/x-rst
23
23
  License-File: LICENSE
24
- Requires-Dist: importlib_metadata>=3.6; python_version < "3.10"
25
24
  Requires-Dist: typing_extensions>=4.14.0
26
25
  Dynamic: license-file
27
26
 
@@ -6,8 +6,8 @@ User guide
6
6
  Checking types directly
7
7
  -----------------------
8
8
 
9
- The most straightfoward way to do type checking with Typeguard is with
10
- :func:`.check_type`. It can be used as as a beefed-up version of :func:`isinstance` that
9
+ The most straightforward way to do type checking with Typeguard is with
10
+ :func:`.check_type`. It can be used as a beefed-up version of :func:`isinstance` that
11
11
  also supports checking against annotations in the :mod:`typing` module::
12
12
 
13
13
  from typeguard import check_type
@@ -131,6 +131,13 @@ list of package names)::
131
131
  install_import_hook('myapp')
132
132
  from myapp import some_module # import only AFTER installing the hook, or it won't take effect
133
133
 
134
+ You can also exclude specific packages or modules from instrumentation using the
135
+ ``ignore_packages`` parameter::
136
+
137
+ from typeguard import install_import_hook
138
+
139
+ install_import_hook('myapp', ignore_packages=['myapp.tests'])
140
+
134
141
  If you wish, you can uninstall the import hook::
135
142
 
136
143
  manager = install_import_hook('myapp')
@@ -184,7 +191,12 @@ Typeguard comes with a plugin for pytest (v7.0 or newer) that installs the impor
184
191
 
185
192
  pytest --typeguard-packages=foo.bar,xyz
186
193
 
187
- It is also possible to set option for the pytest plugin using pytest's own
194
+ You can also exclude specific packages or modules from type checking using the
195
+ ``--typeguard-packages-ignore`` option::
196
+
197
+ pytest --typeguard-packages=foo.bar,xyz --typeguard-packages-ignore=foo.bar.tests
198
+
199
+ It is also possible to set options for the pytest plugin using pytest's own
188
200
  configuration. For example, here's how you might specify several options in
189
201
  ``pyproject.toml``:
190
202
 
@@ -194,6 +206,8 @@ configuration. For example, here's how you might specify several options in
194
206
  typeguard-packages = """
195
207
  foo.bar
196
208
  xyz"""
209
+ typeguard-packages-ignore = """
210
+ foo.bar.tests"""
197
211
  typeguard-debug-instrumentation = true
198
212
  typeguard-typecheck-fail-callback = "mypackage:failcallback"
199
213
  typeguard-forward-ref-policy = "ERROR"
@@ -4,6 +4,37 @@ Version history
4
4
  This library adheres to
5
5
  `Semantic Versioning 2.0 <https://semver.org/#semantic-versioning-200>`_.
6
6
 
7
+ **4.6.0** (2026-07-26)
8
+
9
+ - Added support for type checking against the PEP 661 ``sentinel`` type (built-in on
10
+ Python 3.15 and available on ``typing_extensions`` for earlier Pythons)
11
+ - Added the ``typeguard-packages-ignore`` option (``--typeguard-packages-ignore`` on the
12
+ command line) to the pytest plugin to exclude specific packages from type checking
13
+ (`#523 <https://github.com/agronholm/typeguard/issues/523>`_)
14
+ - Added recognition of wildcard imports from ``typing`` and ``typing_extensions`` in the
15
+ import hook/instrumenter
16
+ (`#489 <https://github.com/agronholm/typeguard/issues/489>`_; PR by @ShipitAndPray)
17
+ - Fixed compatibility with Python 3.15
18
+ (`#554 <https://github.com/agronholm/typeguard/pull/554>`_; PR by @hrnciar)
19
+ - Fixed an assignment expression against an annotated name (``x: int``, then
20
+ ``if (x := ...)``) being instrumented as an unpacking target, which raised
21
+ ``TypeError`` for a non-iterable value and silently replaced an iterable value with
22
+ ``list(value)``
23
+ (`#557 <https://github.com/agronholm/typeguard/issues/557>`_)
24
+ - Fixed false positive when checking a class against ``type[SomeProtocol]`` where the
25
+ protocol declares non-``ClassVar`` (instance) attributes; only ``ClassVar`` members
26
+ are now required on the class itself
27
+ (`#499 <https://github.com/agronholm/typeguard/issues/499>`_)
28
+ - Fixed ``Literal`` checks depending on the order of the arguments, where a ``bool``
29
+ would not match if an ``==`` equal ``int`` came first (``Literal[1, True]`` rejected
30
+ ``True``, but ``Literal[True, 1]`` accepted it)
31
+ (`#566 <https://github.com/agronholm/typeguard/pull/566>`_; PR by @uttam12331)
32
+ - Fixed the import hook/instrumenter erasing the subscript of an empty tuple annotation
33
+ (``tuple[()]``) down to a bare ``tuple``, causing any tuple (including non-empty ones)
34
+ to pass the check
35
+ (`#565 <https://github.com/agronholm/typeguard/pull/565>`_; PR by @chuenchen309)
36
+ - Dropped support for Python 3.9
37
+
7
38
  **4.5.2** (2026-05-14)
8
39
 
9
40
  - Fixed ``IndexError`` raised from ``check_signature_compatible`` when the subject
@@ -589,7 +620,7 @@ This library adheres to
589
620
 
590
621
  **1.2.2** (2016-08-23)
591
622
 
592
- - Fixed checking of homogenous Tuple declarations (``Tuple[bool, ...]``)
623
+ - Fixed checking of homogeneous Tuple declarations (``Tuple[bool, ...]``)
593
624
 
594
625
  **1.2.1** (2016-06-29)
595
626
 
@@ -16,16 +16,15 @@ classifiers = [
16
16
  "Intended Audience :: Developers",
17
17
  "Programming Language :: Python",
18
18
  "Programming Language :: Python :: 3",
19
- "Programming Language :: Python :: 3.9",
20
19
  "Programming Language :: Python :: 3.10",
21
20
  "Programming Language :: Python :: 3.11",
22
21
  "Programming Language :: Python :: 3.12",
23
22
  "Programming Language :: Python :: 3.13",
24
23
  "Programming Language :: Python :: 3.14",
24
+ "Programming Language :: Python :: 3.15",
25
25
  ]
26
- requires-python = ">= 3.9"
26
+ requires-python = ">= 3.10"
27
27
  dependencies = [
28
- "importlib_metadata >= 3.6; python_version < '3.10'",
29
28
  "typing_extensions >= 4.14.0",
30
29
  ]
31
30
  dynamic = ["version"]
@@ -93,6 +92,7 @@ ignore = [
93
92
  "S307",
94
93
  "B008",
95
94
  "UP006",
95
+ "UP007",
96
96
  "UP035",
97
97
  ]
98
98
 
@@ -103,7 +103,7 @@ pretty = true
103
103
  files = ["src"]
104
104
 
105
105
  [tool.tox]
106
- env_list = ["py39", "py310", "py311", "py312", "py313", "py314"]
106
+ env_list = ["py310", "py311", "py312", "py313", "py314", "py315"]
107
107
  skip_missing_interpreters = true
108
108
  requires = ["tox >= 4.22"]
109
109
 
@@ -1,5 +1,6 @@
1
1
  from __future__ import annotations
2
2
 
3
+ import builtins
3
4
  import collections.abc
4
5
  import inspect
5
6
  import sys
@@ -8,10 +9,11 @@ import typing
8
9
  import warnings
9
10
  from collections.abc import Mapping, MutableMapping, Sequence
10
11
  from enum import Enum
11
- from inspect import Parameter, isclass, isfunction
12
+ from inspect import Parameter, isclass
12
13
  from io import BufferedIOBase, IOBase, RawIOBase, TextIOBase
13
14
  from itertools import zip_longest
14
15
  from textwrap import indent
16
+ from types import UnionType
15
17
  from typing import (
16
18
  IO,
17
19
  AbstractSet,
@@ -23,11 +25,11 @@ from typing import (
23
25
  ForwardRef,
24
26
  List,
25
27
  NewType,
26
- Optional,
27
28
  Set,
28
29
  TextIO,
29
30
  Tuple,
30
31
  Type,
32
+ TypeGuard,
31
33
  TypeVar,
32
34
  Union,
33
35
  )
@@ -71,18 +73,14 @@ else:
71
73
  get_origin,
72
74
  )
73
75
 
74
- if sys.version_info >= (3, 10):
75
- from importlib.metadata import entry_points
76
- from typing import ParamSpec
77
- else:
78
- from importlib_metadata import entry_points
79
- from typing_extensions import ParamSpec
76
+ from importlib.metadata import entry_points
77
+ from typing import ParamSpec
80
78
 
81
79
  TypeCheckerCallable: TypeAlias = Callable[
82
80
  [Any, Any, Tuple[Any, ...], TypeCheckMemo], Any
83
81
  ]
84
82
  TypeCheckLookupCallback: TypeAlias = Callable[
85
- [Any, Tuple[Any, ...], Tuple[Any, ...]], Optional[TypeCheckerCallable]
83
+ [Any, Tuple[Any, ...], Tuple[Any, ...]], TypeCheckerCallable | None
86
84
  ]
87
85
 
88
86
  checker_lookup_functions: list[TypeCheckLookupCallback] = []
@@ -95,6 +93,11 @@ generic_alias_types: tuple[type, ...] = (
95
93
  # Sentinel
96
94
  _missing = object()
97
95
 
96
+ # PEP 661 sentinel type instances (typing_extensions.Sentinel, built-in sentinel in 3.15+)
97
+ _sentinel_types: tuple[type, ...] = (typing_extensions.Sentinel,)
98
+ if sys.version_info >= (3, 15):
99
+ _sentinel_types += (builtins.sentinel,)
100
+
98
101
  # Lifted from mypy.sharedparse
99
102
  BINARY_MAGIC_METHODS = {
100
103
  "__add__",
@@ -451,7 +454,7 @@ def check_uniontype(
451
454
  memo: TypeCheckMemo,
452
455
  ) -> None:
453
456
  if not args:
454
- return check_instance(value, types.UnionType, (), memo)
457
+ return check_instance(value, UnionType, (), memo)
455
458
 
456
459
  errors: dict[str, TypeCheckError] = {}
457
460
  try:
@@ -608,12 +611,10 @@ def check_literal(
608
611
  return tuple(retval)
609
612
 
610
613
  final_args = tuple(get_literal_args(args))
611
- try:
612
- index = final_args.index(value)
613
- except ValueError:
614
- pass
615
- else:
616
- if type(final_args[index]) is type(value):
614
+ for arg in final_args:
615
+ # the type check has to come first, as bool is a subclass of int
616
+ # (so 1 == True) and it short-circuits any non-boolean __eq__ result
617
+ if type(arg) is type(value) and arg == value:
617
618
  return
618
619
 
619
620
  formatted_args = ", ".join(repr(arg) for arg in final_args)
@@ -648,6 +649,16 @@ def check_none(
648
649
  raise TypeCheckError("is not None")
649
650
 
650
651
 
652
+ def check_sentinel(
653
+ value: Any,
654
+ origin_type: Any,
655
+ args: tuple[Any, ...],
656
+ memo: TypeCheckMemo,
657
+ ) -> None:
658
+ if value is not origin_type:
659
+ raise TypeCheckError(f"is not {origin_type!r}")
660
+
661
+
651
662
  def check_number(
652
663
  value: Any,
653
664
  origin_type: Any,
@@ -838,8 +849,15 @@ def check_protocol(
838
849
  memo: TypeCheckMemo,
839
850
  ) -> None:
840
851
  origin_annotations = typing.get_type_hints(origin_type)
852
+ checking_class = isclass(value)
841
853
  for attrname in sorted(typing_extensions.get_protocol_members(origin_type)):
842
854
  if (annotation := origin_annotations.get(attrname)) is not None:
855
+ if checking_class and typing.get_origin(annotation) is not typing.ClassVar:
856
+ # a non-ClassVar annotation is an instance attribute (PEP 544) —
857
+ # a class object isn't expected to have it set, and type
858
+ # checkers accept that, so don't flag it as missing.
859
+ continue
860
+
843
861
  try:
844
862
  subject_member = getattr(value, attrname)
845
863
  except AttributeError:
@@ -1034,7 +1052,9 @@ origin_type_checkers: dict[
1034
1052
  Tuple: check_tuple,
1035
1053
  type: check_class,
1036
1054
  Type: check_class,
1055
+ TypeGuard: check_typeguard,
1037
1056
  Union: check_union,
1057
+ UnionType: check_uniontype,
1038
1058
  # On some versions of Python, these may simply be re-exports from "typing",
1039
1059
  # but exactly which Python versions is subject to change.
1040
1060
  # It's best to err on the safe side and just always specify these.
@@ -1043,9 +1063,6 @@ origin_type_checkers: dict[
1043
1063
  typing_extensions.Self: check_self,
1044
1064
  typing_extensions.TypeGuard: check_typeguard,
1045
1065
  }
1046
- if sys.version_info >= (3, 10):
1047
- origin_type_checkers[types.UnionType] = check_uniontype
1048
- origin_type_checkers[typing.TypeGuard] = check_typeguard
1049
1066
 
1050
1067
  if sys.version_info >= (3, 11):
1051
1068
  origin_type_checkers.update(
@@ -1079,16 +1096,9 @@ def builtin_checker_lookup(
1079
1096
  elif isinstance(origin_type, TypeVar):
1080
1097
  return check_typevar
1081
1098
  elif origin_type.__class__ is NewType:
1082
- # typing.NewType on Python 3.10+
1083
- return check_newtype
1084
- elif (
1085
- isfunction(origin_type)
1086
- and getattr(origin_type, "__module__", None) == "typing"
1087
- and getattr(origin_type, "__qualname__", "").startswith("NewType.")
1088
- and hasattr(origin_type, "__supertype__")
1089
- ):
1090
- # typing.NewType on Python 3.9
1091
1099
  return check_newtype
1100
+ elif isinstance(origin_type, _sentinel_types):
1101
+ return check_sentinel
1092
1102
 
1093
1103
  return None
1094
1104
 
@@ -82,7 +82,7 @@ def instrument(f: T_CallableOrType) -> FunctionType | str:
82
82
  if not new_code:
83
83
  return "cannot find the target function in the AST"
84
84
 
85
- if global_config.debug_instrumentation and sys.version_info >= (3, 9):
85
+ if global_config.debug_instrumentation:
86
86
  # Find the matching AST node, then unparse it to source and print to stdout
87
87
  print(
88
88
  f"Source code of {f.__qualname__}() after instrumentation:"
@@ -136,11 +136,7 @@ def check_argument_types() -> Literal[True]:
136
136
  func = find_function(frame)
137
137
  f_locals = frame.f_locals
138
138
  memo = TypeCheckMemo(frame.f_globals, frame.f_locals)
139
- if sys.version_info >= (3, 10):
140
- sig = signature(func, globals=frame.f_globals, locals=frame.f_locals)
141
- else:
142
- sig = signature(func)
143
-
139
+ sig = signature(func, globals=frame.f_globals, locals=frame.f_locals)
144
140
  arguments = {}
145
141
  for param in sig.parameters.values():
146
142
  if param.annotation is Parameter.empty or param.annotation is Any:
@@ -4,7 +4,7 @@ import ast
4
4
  import os
5
5
  import sys
6
6
  import types
7
- from collections.abc import Callable, Iterable, Sequence
7
+ from collections.abc import Callable, Collection, Iterable, Sequence
8
8
  from importlib.abc import MetaPathFinder
9
9
  from importlib.machinery import ModuleSpec, SourceFileLoader
10
10
  from importlib.util import cache_from_source, decode_source
@@ -27,10 +27,7 @@ if sys.version_info >= (3, 11):
27
27
  else:
28
28
  from typing_extensions import ParamSpec
29
29
 
30
- if sys.version_info >= (3, 10):
31
- from importlib.metadata import PackageNotFoundError, version
32
- else:
33
- from importlib_metadata import PackageNotFoundError, version
30
+ from importlib.metadata import PackageNotFoundError, version
34
31
 
35
32
  try:
36
33
  OPTIMIZATION = "typeguard" + "".join(version("typeguard").split(".")[:3])
@@ -48,8 +45,8 @@ def _call_with_frames_removed(
48
45
  return f(*args, **kwargs)
49
46
 
50
47
 
51
- def optimized_cache_from_source(path: str, debug_override: bool | None = None) -> str:
52
- return cache_from_source(path, debug_override, optimization=OPTIMIZATION)
48
+ def optimized_cache_from_source(path: str) -> str:
49
+ return cache_from_source(path, optimization=OPTIMIZATION)
53
50
 
54
51
 
55
52
  class TypeguardLoader(SourceFileLoader):
@@ -57,6 +54,7 @@ class TypeguardLoader(SourceFileLoader):
57
54
  def source_to_code(
58
55
  data: Buffer | str | ast.Module | ast.Expression | ast.Interactive,
59
56
  path: Buffer | str | PathLike[str] = "<string>",
57
+ fullname: str | None = None,
60
58
  *,
61
59
  _optimize: int = -1,
62
60
  ) -> CodeType:
@@ -73,17 +71,26 @@ class TypeguardLoader(SourceFileLoader):
73
71
  else:
74
72
  source = decode_source(data)
75
73
 
76
- module = _call_with_frames_removed(
77
- ast.parse,
78
- source,
79
- filename,
80
- "exec",
81
- )
74
+ if sys.version_info >= (3, 15):
75
+ module = _call_with_frames_removed(
76
+ ast.parse,
77
+ source,
78
+ filename,
79
+ "exec",
80
+ module=fullname,
81
+ )
82
+ else:
83
+ module = _call_with_frames_removed(
84
+ ast.parse,
85
+ source,
86
+ filename,
87
+ "exec",
88
+ )
82
89
 
83
90
  tree = TypeguardTransformer().visit(module)
84
91
  ast.fix_missing_locations(tree)
85
92
 
86
- if global_config.debug_instrumentation and sys.version_info >= (3, 9):
93
+ if global_config.debug_instrumentation:
87
94
  print(
88
95
  f"Source code of {path!r} after instrumentation:\n"
89
96
  "----------------------------------------------",
@@ -92,9 +99,25 @@ class TypeguardLoader(SourceFileLoader):
92
99
  print(ast.unparse(tree), file=sys.stderr)
93
100
  print("----------------------------------------------", file=sys.stderr)
94
101
 
95
- return _call_with_frames_removed(
96
- compile, tree, filename, "exec", 0, dont_inherit=True
97
- )
102
+ if sys.version_info >= (3, 15):
103
+ return _call_with_frames_removed(
104
+ compile,
105
+ tree,
106
+ filename,
107
+ "exec",
108
+ 0,
109
+ dont_inherit=True,
110
+ module=fullname,
111
+ )
112
+ else:
113
+ return _call_with_frames_removed(
114
+ compile,
115
+ tree,
116
+ filename,
117
+ "exec",
118
+ 0,
119
+ dont_inherit=True,
120
+ )
98
121
 
99
122
  def exec_module(self, module: ModuleType) -> None:
100
123
  # Use a custom optimization marker – the import lock should make this monkey
@@ -117,9 +140,15 @@ class TypeguardFinder(MetaPathFinder):
117
140
  .. versionadded:: 2.6
118
141
  """
119
142
 
120
- def __init__(self, packages: list[str] | None, original_pathfinder: MetaPathFinder):
143
+ def __init__(
144
+ self,
145
+ packages: list[str] | None,
146
+ original_pathfinder: MetaPathFinder,
147
+ ignore_packages: Collection[str] = (),
148
+ ):
121
149
  self.packages = packages
122
150
  self._original_pathfinder = original_pathfinder
151
+ self.ignore_packages = ignore_packages
123
152
 
124
153
  def find_spec(
125
154
  self,
@@ -143,6 +172,10 @@ class TypeguardFinder(MetaPathFinder):
143
172
  ``xyz.abc``)
144
173
 
145
174
  """
175
+ for package in self.ignore_packages:
176
+ if module_name == package or module_name.startswith(package + "."):
177
+ return False
178
+
146
179
  if self.packages is None:
147
180
  return True
148
181
 
@@ -182,6 +215,7 @@ class ImportHookManager:
182
215
 
183
216
  def install_import_hook(
184
217
  packages: Iterable[str] | None = None,
218
+ ignore_packages: Iterable[str] = (),
185
219
  *,
186
220
  cls: type[TypeguardFinder] = TypeguardFinder,
187
221
  ) -> ImportHookManager:
@@ -192,6 +226,8 @@ def install_import_hook(
192
226
 
193
227
  :param packages: an iterable of package names to instrument, or ``None`` to
194
228
  instrument all packages
229
+ :param ignore_packages: an iterable of package names to exclude from
230
+ instrumentation, even if they match ``packages``
195
231
  :param cls: a custom meta path finder class
196
232
  :return: a context manager that uninstalls the hook on exit (or when you call
197
233
  ``.uninstall()``)
@@ -206,6 +242,11 @@ def install_import_hook(
206
242
  else:
207
243
  target_packages = list(packages)
208
244
 
245
+ if isinstance(ignore_packages, str):
246
+ target_ignore_packages: list[str] = [ignore_packages]
247
+ else:
248
+ target_ignore_packages = list(ignore_packages)
249
+
209
250
  for finder in sys.meta_path:
210
251
  if (
211
252
  isclass(finder)
@@ -216,6 +257,6 @@ def install_import_hook(
216
257
  else:
217
258
  raise RuntimeError("Cannot find a PathFinder in sys.meta_path")
218
259
 
219
- hook = cls(target_packages, finder)
260
+ hook = cls(target_packages, finder, target_ignore_packages)
220
261
  sys.meta_path.insert(0, hook)
221
262
  return ImportHookManager(hook)
@@ -34,6 +34,14 @@ def pytest_addoption(parser: Parser) -> None:
34
34
  )
35
35
  add_ini_option("linelist")
36
36
 
37
+ group.addoption(
38
+ "--typeguard-packages-ignore",
39
+ action="store",
40
+ help="comma separated name list of packages and modules to exclude from type "
41
+ "checking",
42
+ )
43
+ add_ini_option("linelist")
44
+
37
45
  group.addoption(
38
46
  "--typeguard-debug-instrumentation",
39
47
  action="store_true",
@@ -82,6 +90,12 @@ def pytest_configure(config: Config) -> None:
82
90
  elif packages_ini := config.getini("typeguard-packages"):
83
91
  packages = packages_ini
84
92
 
93
+ ignore_packages: list[str] = []
94
+ if ignore_packages_option := config.getoption("typeguard_packages_ignore"):
95
+ ignore_packages = [pkg.strip() for pkg in ignore_packages_option.split(",")]
96
+ elif ignore_packages_ini := config.getini("typeguard-packages-ignore"):
97
+ ignore_packages = ignore_packages_ini
98
+
85
99
  if packages:
86
100
  if packages == [":all:"]:
87
101
  packages = None
@@ -97,7 +111,7 @@ def pytest_configure(config: Config) -> None:
97
111
  stacklevel=1,
98
112
  )
99
113
 
100
- install_import_hook(packages=packages)
114
+ install_import_hook(packages=packages, ignore_packages=ignore_packages)
101
115
 
102
116
  debug_option = getoption("typeguard-debug-instrumentation")
103
117
  if debug_option:
@@ -1,16 +1,10 @@
1
1
  from __future__ import annotations
2
2
 
3
- import sys
4
3
  from collections.abc import Callable, Generator
5
4
  from contextlib import contextmanager
6
5
  from functools import update_wrapper
7
6
  from threading import Lock
8
- from typing import ContextManager, TypeVar, overload
9
-
10
- if sys.version_info >= (3, 10):
11
- from typing import ParamSpec
12
- else:
13
- from typing_extensions import ParamSpec
7
+ from typing import ContextManager, ParamSpec, TypeVar, overload
14
8
 
15
9
  P = ParamSpec("P")
16
10
  T = TypeVar("T")