typeguard 4.4.4__tar.gz → 4.5.1__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 (63) hide show
  1. typeguard-4.5.1/.github/FUNDING.yml +1 -0
  2. typeguard-4.5.1/.github/SECURITY.md +16 -0
  3. typeguard-4.5.1/.github/dependabot.yml +13 -0
  4. {typeguard-4.4.4 → typeguard-4.5.1}/.github/workflows/publish.yml +8 -5
  5. {typeguard-4.4.4 → typeguard-4.5.1}/.github/workflows/test.yml +2 -2
  6. {typeguard-4.4.4 → typeguard-4.5.1}/.pre-commit-config.yaml +4 -4
  7. {typeguard-4.4.4 → typeguard-4.5.1}/PKG-INFO +9 -2
  8. {typeguard-4.4.4 → typeguard-4.5.1}/README.rst +8 -1
  9. {typeguard-4.4.4 → typeguard-4.5.1}/docs/api.rst +4 -0
  10. {typeguard-4.4.4 → typeguard-4.5.1}/docs/userguide.rst +27 -0
  11. {typeguard-4.4.4 → typeguard-4.5.1}/docs/versionhistory.rst +29 -1
  12. {typeguard-4.4.4 → typeguard-4.5.1}/pyproject.toml +4 -0
  13. {typeguard-4.4.4 → typeguard-4.5.1}/src/typeguard/__init__.py +2 -0
  14. {typeguard-4.4.4 → typeguard-4.5.1}/src/typeguard/_checkers.py +61 -24
  15. {typeguard-4.4.4 → typeguard-4.5.1}/src/typeguard/_functions.py +95 -34
  16. {typeguard-4.4.4 → typeguard-4.5.1}/src/typeguard/_importhook.py +13 -5
  17. {typeguard-4.4.4 → typeguard-4.5.1}/src/typeguard/_transformer.py +55 -40
  18. {typeguard-4.4.4 → typeguard-4.5.1}/src/typeguard/_utils.py +50 -1
  19. {typeguard-4.4.4 → typeguard-4.5.1}/src/typeguard.egg-info/PKG-INFO +9 -2
  20. {typeguard-4.4.4 → typeguard-4.5.1}/src/typeguard.egg-info/SOURCES.txt +5 -1
  21. {typeguard-4.4.4 → typeguard-4.5.1}/tests/dummymodule.py +17 -0
  22. typeguard-4.4.4/tests/pep695.py → typeguard-4.5.1/tests/dummymodule_py312.py +12 -0
  23. {typeguard-4.4.4 → typeguard-4.5.1}/tests/test_checkers.py +138 -0
  24. typeguard-4.5.1/tests/test_functions.py +75 -0
  25. {typeguard-4.4.4 → typeguard-4.5.1}/tests/test_instrumentation.py +39 -13
  26. {typeguard-4.4.4 → typeguard-4.5.1}/tests/test_transformer.py +141 -103
  27. {typeguard-4.4.4 → typeguard-4.5.1}/tests/test_typechecked.py +5 -4
  28. {typeguard-4.4.4 → typeguard-4.5.1}/.github/ISSUE_TEMPLATE/bug_report.yaml +0 -0
  29. {typeguard-4.4.4 → typeguard-4.5.1}/.github/ISSUE_TEMPLATE/config.yml +0 -0
  30. {typeguard-4.4.4 → typeguard-4.5.1}/.github/ISSUE_TEMPLATE/features_request.yaml +0 -0
  31. {typeguard-4.4.4 → typeguard-4.5.1}/.github/pull_request_template.md +0 -0
  32. {typeguard-4.4.4 → typeguard-4.5.1}/.gitignore +0 -0
  33. {typeguard-4.4.4 → typeguard-4.5.1}/.readthedocs.yml +0 -0
  34. {typeguard-4.4.4 → typeguard-4.5.1}/LICENSE +0 -0
  35. {typeguard-4.4.4 → typeguard-4.5.1}/docs/conf.py +0 -0
  36. {typeguard-4.4.4 → typeguard-4.5.1}/docs/contributing.rst +0 -0
  37. {typeguard-4.4.4 → typeguard-4.5.1}/docs/extending.rst +0 -0
  38. {typeguard-4.4.4 → typeguard-4.5.1}/docs/features.rst +0 -0
  39. {typeguard-4.4.4 → typeguard-4.5.1}/docs/index.rst +0 -0
  40. {typeguard-4.4.4 → typeguard-4.5.1}/setup.cfg +0 -0
  41. {typeguard-4.4.4 → typeguard-4.5.1}/src/typeguard/_config.py +0 -0
  42. {typeguard-4.4.4 → typeguard-4.5.1}/src/typeguard/_decorators.py +0 -0
  43. {typeguard-4.4.4 → typeguard-4.5.1}/src/typeguard/_exceptions.py +0 -0
  44. {typeguard-4.4.4 → typeguard-4.5.1}/src/typeguard/_memo.py +0 -0
  45. {typeguard-4.4.4 → typeguard-4.5.1}/src/typeguard/_pytest_plugin.py +0 -0
  46. {typeguard-4.4.4 → typeguard-4.5.1}/src/typeguard/_suppression.py +0 -0
  47. {typeguard-4.4.4 → typeguard-4.5.1}/src/typeguard/py.typed +0 -0
  48. {typeguard-4.4.4 → typeguard-4.5.1}/src/typeguard.egg-info/dependency_links.txt +0 -0
  49. {typeguard-4.4.4 → typeguard-4.5.1}/src/typeguard.egg-info/entry_points.txt +0 -0
  50. {typeguard-4.4.4 → typeguard-4.5.1}/src/typeguard.egg-info/requires.txt +0 -0
  51. {typeguard-4.4.4 → typeguard-4.5.1}/src/typeguard.egg-info/top_level.txt +0 -0
  52. {typeguard-4.4.4 → typeguard-4.5.1}/tests/__init__.py +0 -0
  53. {typeguard-4.4.4 → typeguard-4.5.1}/tests/conftest.py +0 -0
  54. {typeguard-4.4.4 → typeguard-4.5.1}/tests/deferredannos.py +0 -0
  55. {typeguard-4.4.4 → typeguard-4.5.1}/tests/mypy/negative.py +0 -0
  56. {typeguard-4.4.4 → typeguard-4.5.1}/tests/mypy/positive.py +0 -0
  57. {typeguard-4.4.4 → typeguard-4.5.1}/tests/mypy/test_type_annotations.py +0 -0
  58. {typeguard-4.4.4 → typeguard-4.5.1}/tests/test_importhook.py +0 -0
  59. {typeguard-4.4.4 → typeguard-4.5.1}/tests/test_plugins.py +0 -0
  60. {typeguard-4.4.4 → typeguard-4.5.1}/tests/test_pytest_plugin.py +0 -0
  61. {typeguard-4.4.4 → typeguard-4.5.1}/tests/test_suppression.py +0 -0
  62. {typeguard-4.4.4 → typeguard-4.5.1}/tests/test_utils.py +0 -0
  63. {typeguard-4.4.4 → typeguard-4.5.1}/tests/test_warn_on_error.py +0 -0
@@ -0,0 +1 @@
1
+ tidelift: pypi/typeguard
@@ -0,0 +1,16 @@
1
+ # Security Policy
2
+
3
+ ## Supported Versions
4
+
5
+ The latest major/minor versions will get security updates and bug fixes.
6
+ Earlier versions are unsupported.
7
+
8
+ | Version | Supported |
9
+ |---------| ------------------ |
10
+ | 4.4.x | :white_check_mark: |
11
+ | < 4.4.0 | :x: |
12
+
13
+ ## Reporting a Vulnerability
14
+
15
+ See the [security](https://github.com/agronholm/typeguard/security)
16
+ section to view existing security advisories or to report a new vulnerability.
@@ -0,0 +1,13 @@
1
+ # Keep GitHub Actions up to date with GitHub's Dependabot...
2
+ # https://docs.github.com/en/code-security/dependabot/working-with-dependabot/keeping-your-actions-up-to-date-with-dependabot
3
+ # https://docs.github.com/en/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file#package-ecosystem
4
+ version: 2
5
+ updates:
6
+ - package-ecosystem: github-actions
7
+ directory: /
8
+ groups:
9
+ github-actions:
10
+ patterns:
11
+ - "*" # Group all Actions updates into a single larger pull request
12
+ schedule:
13
+ interval: quarterly
@@ -14,9 +14,9 @@ jobs:
14
14
  runs-on: ubuntu-latest
15
15
  environment: release
16
16
  steps:
17
- - uses: actions/checkout@v4
17
+ - uses: actions/checkout@v6
18
18
  - name: Set up Python
19
- uses: actions/setup-python@v5
19
+ uses: actions/setup-python@v6
20
20
  with:
21
21
  python-version: 3.x
22
22
  - name: Install dependencies
@@ -24,7 +24,7 @@ jobs:
24
24
  - name: Create packages
25
25
  run: python -m build
26
26
  - name: Archive packages
27
- uses: actions/upload-artifact@v4
27
+ uses: actions/upload-artifact@v6
28
28
  with:
29
29
  name: dist
30
30
  path: dist
@@ -38,7 +38,10 @@ jobs:
38
38
  id-token: write
39
39
  steps:
40
40
  - name: Retrieve packages
41
- uses: actions/download-artifact@v4
41
+ uses: actions/download-artifact@v7
42
+ with:
43
+ name: dist
44
+ path: dist
42
45
  - name: Upload packages
43
46
  uses: pypa/gh-action-pypi-publish@release/v1
44
47
 
@@ -49,7 +52,7 @@ jobs:
49
52
  permissions:
50
53
  contents: write
51
54
  steps:
52
- - uses: actions/checkout@v4
55
+ - uses: actions/checkout@v6
53
56
  - id: changelog
54
57
  uses: agronholm/release-notes@v1
55
58
  with:
@@ -13,9 +13,9 @@ jobs:
13
13
  python-version: ["3.9", "3.10", "3.11", "3.12", "3.13", "3.14", pypy-3.11]
14
14
  runs-on: ubuntu-latest
15
15
  steps:
16
- - uses: actions/checkout@v4
16
+ - uses: actions/checkout@v6
17
17
  - name: Set up Python ${{ matrix.python-version }}
18
- uses: actions/setup-python@v5
18
+ uses: actions/setup-python@v6
19
19
  with:
20
20
  python-version: ${{ matrix.python-version }}
21
21
  allow-prereleases: true
@@ -1,6 +1,6 @@
1
1
  repos:
2
2
  - repo: https://github.com/pre-commit/pre-commit-hooks
3
- rev: v5.0.0
3
+ rev: v6.0.0
4
4
  hooks:
5
5
  - id: check-case-conflict
6
6
  - id: check-merge-conflict
@@ -14,18 +14,18 @@ repos:
14
14
  - id: trailing-whitespace
15
15
 
16
16
  - repo: https://github.com/astral-sh/ruff-pre-commit
17
- rev: v0.11.4
17
+ rev: v0.15.0
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.15.0
24
+ rev: v1.19.1
25
25
  hooks:
26
26
  - id: mypy
27
+ pass_filenames: false
27
28
  additional_dependencies: [ "typing_extensions" ]
28
- exclude: "^tests/"
29
29
 
30
30
  - repo: https://github.com/pre-commit/pygrep-hooks
31
31
  rev: v1.10.0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: typeguard
3
- Version: 4.4.4
3
+ Version: 4.5.1
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
@@ -34,6 +34,9 @@ Dynamic: license-file
34
34
  .. image:: https://readthedocs.org/projects/typeguard/badge/?version=latest
35
35
  :target: https://typeguard.readthedocs.io/en/latest/?badge=latest
36
36
  :alt: Documentation
37
+ .. image:: https://tidelift.com/badges/package/pypi/typeguard
38
+ :target: https://tidelift.com/subscription/pkg/pypi-typeguard
39
+ :alt: Tidelift
37
40
 
38
41
  This library provides run-time type checking for functions defined with
39
42
  `PEP 484 <https://www.python.org/dev/peps/pep-0484/>`_ argument (and return) type
@@ -41,12 +44,16 @@ annotations, and any arbitrary objects. It can be used together with static type
41
44
  checkers as an additional layer of type safety, to catch type violations that could only
42
45
  be detected at run time.
43
46
 
44
- Two principal ways to do type checking are provided:
47
+ Three principal ways to do type checking are provided, each with its pros and cons:
45
48
 
46
49
  #. The ``check_type`` function:
47
50
 
48
51
  * like ``isinstance()``, but supports arbitrary type annotations (within limits)
49
52
  * can be used as a ``cast()`` replacement, but with actual checking of the value
53
+ #. The ``check_argument_types()`` and ``check_return_type()`` functions:
54
+
55
+ * debugger friendly (except when running with the pydev debugger with the C extension installed)
56
+ * does not work reliably with dynamically defined type hints (e.g. in nested functions)
50
57
  #. Code instrumentation:
51
58
 
52
59
  * entire modules, or individual functions (via ``@typechecked``) are recompiled, with
@@ -7,6 +7,9 @@
7
7
  .. image:: https://readthedocs.org/projects/typeguard/badge/?version=latest
8
8
  :target: https://typeguard.readthedocs.io/en/latest/?badge=latest
9
9
  :alt: Documentation
10
+ .. image:: https://tidelift.com/badges/package/pypi/typeguard
11
+ :target: https://tidelift.com/subscription/pkg/pypi-typeguard
12
+ :alt: Tidelift
10
13
 
11
14
  This library provides run-time type checking for functions defined with
12
15
  `PEP 484 <https://www.python.org/dev/peps/pep-0484/>`_ argument (and return) type
@@ -14,12 +17,16 @@ annotations, and any arbitrary objects. It can be used together with static type
14
17
  checkers as an additional layer of type safety, to catch type violations that could only
15
18
  be detected at run time.
16
19
 
17
- Two principal ways to do type checking are provided:
20
+ Three principal ways to do type checking are provided, each with its pros and cons:
18
21
 
19
22
  #. The ``check_type`` function:
20
23
 
21
24
  * like ``isinstance()``, but supports arbitrary type annotations (within limits)
22
25
  * can be used as a ``cast()`` replacement, but with actual checking of the value
26
+ #. The ``check_argument_types()`` and ``check_return_type()`` functions:
27
+
28
+ * debugger friendly (except when running with the pydev debugger with the C extension installed)
29
+ * does not work reliably with dynamically defined type hints (e.g. in nested functions)
23
30
  #. Code instrumentation:
24
31
 
25
32
  * entire modules, or individual functions (via ``@typechecked``) are recompiled, with
@@ -6,6 +6,10 @@ API reference
6
6
  Type checking
7
7
  -------------
8
8
 
9
+ .. autofunction:: check_argument_types
10
+
11
+ .. autofunction:: check_return_type
12
+
9
13
  .. autofunction:: check_type
10
14
 
11
15
  .. autodecorator:: typechecked
@@ -86,6 +86,33 @@ the import hook.
86
86
  its methods, such methods will not be instrumented. In contrast, the import hook
87
87
  has no such restrictions.
88
88
 
89
+ Explicitly checking arguments and return types
90
+ ----------------------------------------------
91
+
92
+ Two functions are provided for fine-grained checking of argument and return types:
93
+
94
+ * :func:`~typeguard.check_argument_types`
95
+ * :func:`~typeguard.check_return_type`
96
+
97
+ These functions use the previous stack frame and the garbage collector to find a reference
98
+ to the function to obtain the type annotations to check against.
99
+
100
+ Here's how to use them::
101
+
102
+ from typeguard import check_argument_types, check_return_type
103
+
104
+ def some_function(a: int, b: float, c: str, *args: str) -> bool:
105
+ # Must be called before anything else, or the results may not be valid
106
+ check_argument_types()
107
+ ...
108
+ return check_return_type(retval)
109
+
110
+ .. note:: This method is not reliable when used in nested functions (i.e. functions defined inside
111
+ other functions). This is because these functions rely on finding the correct function
112
+ object using the garbage collector, and when a nested function is running, its function object
113
+ may no longer be around anymore, as it is only bound to the closure of the enclosing function.
114
+ For this reason, it is recommended to use ``@typechecked`` instead for nested functions.
115
+
89
116
  Using the import hook
90
117
  ---------------------
91
118
 
@@ -4,7 +4,35 @@ Version history
4
4
  This library adheres to
5
5
  `Semantic Versioning 2.0 <https://semver.org/#semantic-versioning-200>`_.
6
6
 
7
- **4.4.4** (2026-06-18)
7
+ **4.5.1** (2026-02-19)
8
+
9
+ - Fixed iterable unpacking incorrectly calculating the cut-off offset of the item list
10
+ when assigning remaining values to the star variable
11
+ (`#546 <https://github.com/agronholm/typeguard/issues/546>`_)
12
+
13
+ **4.5.0** (2026-02-15)
14
+
15
+ - Restored the ``check_argument_types()`` and ``check_return_type()`` functions that
16
+ were dropped in v3.0.0, for users who want more fine-grained control over run-time
17
+ type checking (`#437 <https://github.com/agronholm/typeguard/issues/437>`_)
18
+ - Added support for ``extra_items`` in ``TypedDict``, allowing users to specify
19
+ the types for the values of "leftover" keys in a typed dict (keys that weren't
20
+ explicitly defined in the ``TypedDict`` subclass)
21
+ (`#538 <https://github.com/agronholm/typeguard/issues/538>`_)
22
+ - Fixed ``NameError`` when evaluating forward references on Python 3.14
23
+ (`#536 <https://github.com/agronholm/typeguard/issues/536>`_; PR by @dionhaefner)
24
+ - Fixed protocol check incorrectly rejecting inherited classmethods and staticmethods
25
+ (`#539 <https://github.com/agronholm/typeguard/issues/539>`_)
26
+ - Fixed missing ``TypeCheckError`` when checking ``TypedDict`` with ``Required[...]``
27
+ annotations
28
+ (`#533 <https://github.com/agronholm/typeguard/issues/533>`_; PR by @dionhaefner)
29
+ - Fixed type aliases (e.g. ``type Foo = list[int]``) not being resolved during type
30
+ checking (`#526 <https://github.com/agronholm/typeguard/issues/526>`_)
31
+ - Fixed type-checked assignments to a single tuple target (e.g. ``x, = ("foo",)``)
32
+ falsely raising ``TypeCheckedError``
33
+ (`#535 <https://github.com/agronholm/typeguard/issues/535>`_)
34
+
35
+ **4.4.4** (2025-06-18)
8
36
 
9
37
  - Fixed ``IndexError`` when using ``@typechecked`` on more than one function with the
10
38
  same name under certain circumstances
@@ -78,6 +78,9 @@ exclude_lines = [
78
78
  [tool.ruff]
79
79
  src = ["src"]
80
80
 
81
+ [tool.ruff.per-file-target-version]
82
+ "tests/dummymodule_py312.py" = "py312"
83
+
81
84
  [tool.ruff.lint]
82
85
  extend-select = [
83
86
  "B0", # flake8-bugbear
@@ -97,6 +100,7 @@ ignore = [
97
100
  python_version = "3.11"
98
101
  strict = true
99
102
  pretty = true
103
+ files = ["src"]
100
104
 
101
105
  [tool.tox]
102
106
  env_list = ["py39", "py310", "py311", "py312", "py313", "py314"]
@@ -16,6 +16,8 @@ from ._exceptions import TypeCheckError as TypeCheckError
16
16
  from ._exceptions import TypeCheckWarning as TypeCheckWarning
17
17
  from ._exceptions import TypeHintWarning as TypeHintWarning
18
18
  from ._functions import TypeCheckFailCallback as TypeCheckFailCallback
19
+ from ._functions import check_argument_types as check_argument_types
20
+ from ._functions import check_return_type as check_return_type
19
21
  from ._functions import check_type as check_type
20
22
  from ._functions import warn_on_error as warn_on_error
21
23
  from ._importhook import ImportHookManager as ImportHookManager
@@ -46,9 +46,15 @@ from ._exceptions import TypeCheckError, TypeHintWarning
46
46
  from ._memo import TypeCheckMemo
47
47
  from ._utils import evaluate_forwardref, get_stacklevel, get_type_name, qualified_name
48
48
 
49
+ if sys.version_info >= (3, 15):
50
+ from typing import NoExtraItems
51
+ else:
52
+ from typing_extensions import NoExtraItems
53
+
49
54
  if sys.version_info >= (3, 11):
50
55
  from typing import (
51
56
  NotRequired,
57
+ Required,
52
58
  TypeAlias,
53
59
  get_args,
54
60
  get_origin,
@@ -59,6 +65,7 @@ else:
59
65
  from typing_extensions import Any as SubclassableAny
60
66
  from typing_extensions import (
61
67
  NotRequired,
68
+ Required,
62
69
  TypeAlias,
63
70
  get_args,
64
71
  get_origin,
@@ -247,16 +254,24 @@ def check_typed_dict(
247
254
  raise TypeCheckError("is not a dict")
248
255
 
249
256
  declared_keys = frozenset(origin_type.__annotations__)
250
- if hasattr(origin_type, "__required_keys__"):
251
- required_keys = set(origin_type.__required_keys__)
252
- else: # py3.8 and lower
253
- required_keys = set(declared_keys) if origin_type.__total__ else set()
254
-
257
+ required_keys = set(origin_type.__required_keys__)
255
258
  existing_keys = set(value)
256
- extra_keys = existing_keys - declared_keys
257
- if extra_keys:
258
- keys_formatted = ", ".join(f'"{key}"' for key in sorted(extra_keys, key=repr))
259
- raise TypeCheckError(f"has unexpected extra key(s): {keys_formatted}")
259
+ if extra_keys := existing_keys - declared_keys:
260
+ if (
261
+ argtype := getattr(origin_type, "__extra_items__", NoExtraItems)
262
+ ) is NoExtraItems:
263
+ keys_formatted = ", ".join(
264
+ f'"{key}"' for key in sorted(extra_keys, key=repr)
265
+ )
266
+ raise TypeCheckError(f"has unexpected extra key(s): {keys_formatted}")
267
+
268
+ for key in extra_keys:
269
+ argvalue = value[key]
270
+ try:
271
+ check_type_internal(argvalue, argtype, memo)
272
+ except TypeCheckError as exc:
273
+ exc.append_path_element(f"value of key {key!r}")
274
+ raise
260
275
 
261
276
  # Detect NotRequired fields which are hidden by get_type_hints()
262
277
  type_hints: dict[str, type] = {}
@@ -267,11 +282,13 @@ def check_typed_dict(
267
282
  if get_origin(annotation) is NotRequired:
268
283
  required_keys.discard(key)
269
284
  annotation = get_args(annotation)[0]
285
+ elif get_origin(annotation) is Required:
286
+ required_keys.add(key)
287
+ annotation = get_args(annotation)[0]
270
288
 
271
289
  type_hints[key] = annotation
272
290
 
273
- missing_keys = required_keys - existing_keys
274
- if missing_keys:
291
+ if missing_keys := required_keys - existing_keys:
275
292
  keys_formatted = ", ".join(f'"{key}"' for key in sorted(missing_keys, key=repr))
276
293
  raise TypeCheckError(f"is missing required key(s): {keys_formatted}")
277
294
 
@@ -471,6 +488,9 @@ def check_class(
471
488
  else:
472
489
  expected_class = args[0]
473
490
 
491
+ if type(expected_class) in type_alias_types:
492
+ expected_class = expected_class.__value__
493
+
474
494
  if expected_class is Any:
475
495
  return
476
496
  elif expected_class is typing_extensions.Self:
@@ -668,20 +688,26 @@ def check_signature_compatible(subject: type, protocol: type, attrname: str) ->
668
688
  subject_type: typing.Literal["instance", "class", "static"] = "instance"
669
689
 
670
690
  # Check if the protocol-side method is a class method or static method
671
- if attrname in protocol.__dict__:
672
- descriptor = protocol.__dict__[attrname]
673
- if isinstance(descriptor, staticmethod):
674
- protocol_type = "static"
675
- elif isinstance(descriptor, classmethod):
676
- protocol_type = "class"
691
+ for klass in protocol.__mro__:
692
+ if attrname in klass.__dict__:
693
+ descriptor = klass.__dict__[attrname]
694
+ if isinstance(descriptor, staticmethod):
695
+ protocol_type = "static"
696
+ elif isinstance(descriptor, classmethod):
697
+ protocol_type = "class"
698
+
699
+ break
677
700
 
678
701
  # Check if the subject-side method is a class method or static method
679
- if attrname in subject.__dict__:
680
- descriptor = subject.__dict__[attrname]
681
- if isinstance(descriptor, staticmethod):
682
- subject_type = "static"
683
- elif isinstance(descriptor, classmethod):
684
- subject_type = "class"
702
+ for klass in subject.__mro__:
703
+ if attrname in klass.__dict__:
704
+ descriptor = klass.__dict__[attrname]
705
+ if isinstance(descriptor, staticmethod):
706
+ subject_type = "static"
707
+ elif isinstance(descriptor, classmethod):
708
+ subject_type = "class"
709
+
710
+ break
685
711
 
686
712
  if protocol_type == "instance" and subject_type != "instance":
687
713
  raise TypeCheckError(
@@ -927,6 +953,9 @@ def check_type_internal(
927
953
 
928
954
  return
929
955
 
956
+ if type(annotation) in type_alias_types:
957
+ annotation = annotation.__value__
958
+
930
959
  if annotation is Any or annotation is SubclassableAny or isinstance(value, Mock):
931
960
  return
932
961
 
@@ -973,7 +1002,9 @@ def check_type_internal(
973
1002
 
974
1003
 
975
1004
  # Equality checks are applied to these
976
- origin_type_checkers = {
1005
+ origin_type_checkers: dict[
1006
+ Any, Callable[[Any, Any, tuple[Any, ...], TypeCheckMemo], None]
1007
+ ] = {
977
1008
  bytes: check_byteslike,
978
1009
  AbstractSet: check_set,
979
1010
  BinaryIO: check_io,
@@ -1015,11 +1046,17 @@ origin_type_checkers = {
1015
1046
  if sys.version_info >= (3, 10):
1016
1047
  origin_type_checkers[types.UnionType] = check_uniontype
1017
1048
  origin_type_checkers[typing.TypeGuard] = check_typeguard
1049
+
1018
1050
  if sys.version_info >= (3, 11):
1019
1051
  origin_type_checkers.update(
1020
1052
  {typing.LiteralString: check_literal_string, typing.Self: check_self}
1021
1053
  )
1022
1054
 
1055
+ if sys.version_info >= (3, 12):
1056
+ type_alias_types = (typing_extensions.TypeAliasType, typing.TypeAliasType)
1057
+ else:
1058
+ type_alias_types = (typing_extensions.TypeAliasType,)
1059
+
1023
1060
 
1024
1061
  def builtin_checker_lookup(
1025
1062
  origin_type: Any, args: tuple[Any, ...], extras: tuple[Any, ...]
@@ -3,7 +3,8 @@ from __future__ import annotations
3
3
  import sys
4
4
  import warnings
5
5
  from collections.abc import Sequence
6
- from typing import Any, Callable, NoReturn, TypeVar, Union, overload
6
+ from inspect import Parameter, signature
7
+ from typing import Any, Callable, NoReturn, TypeVar, Union, get_type_hints, overload
7
8
 
8
9
  from . import _suppression
9
10
  from ._checkers import BINARY_MAGIC_METHODS, check_type_internal
@@ -14,7 +15,7 @@ from ._config import (
14
15
  )
15
16
  from ._exceptions import TypeCheckError, TypeCheckWarning
16
17
  from ._memo import TypeCheckMemo
17
- from ._utils import get_stacklevel, qualified_name
18
+ from ._utils import find_function, get_stacklevel, qualified_name
18
19
 
19
20
  if sys.version_info >= (3, 11):
20
21
  from typing import Literal, Never, TypeAlias
@@ -115,7 +116,49 @@ def check_type(
115
116
  return value
116
117
 
117
118
 
118
- def check_argument_types(
119
+ def check_argument_types() -> Literal[True]:
120
+ """
121
+ Check that the argument values match the annotated types.
122
+
123
+ Unless both ``args`` and ``kwargs`` are provided, the information will be retrieved from
124
+ the previous stack frame (ie. from the function that called this).
125
+
126
+ :return: ``True``
127
+ :raises TypeCheckError: if there is an argument type mismatch
128
+
129
+ .. version-changed:: 4.5.0
130
+ This function was restored since its removal in v3.0.0.
131
+
132
+ """
133
+ # faster than inspect.currentframe(), but not officially
134
+ # supported in all python implementations
135
+ frame = sys._getframe(1)
136
+ func = find_function(frame)
137
+ f_locals = frame.f_locals
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
+
144
+ arguments = {}
145
+ for param in sig.parameters.values():
146
+ if param.annotation is Parameter.empty or param.annotation is Any:
147
+ continue
148
+
149
+ if param.kind is Parameter.VAR_POSITIONAL:
150
+ annotation: Any = tuple[param.annotation, ...] # type: ignore[name-defined]
151
+ elif param.kind is Parameter.VAR_KEYWORD:
152
+ annotation = dict[str, param.annotation] # type: ignore[name-defined]
153
+ else:
154
+ annotation = param.annotation
155
+
156
+ arguments[param.name] = (f_locals[param.name], annotation)
157
+
158
+ return check_argument_types_internal(func.__name__, arguments, memo)
159
+
160
+
161
+ def check_argument_types_internal(
119
162
  func_name: str,
120
163
  arguments: dict[str, tuple[Any, Any]],
121
164
  memo: TypeCheckMemo,
@@ -146,7 +189,28 @@ def check_argument_types(
146
189
  return True
147
190
 
148
191
 
149
- def check_return_type(
192
+ def check_return_type(retval: T) -> T:
193
+ """
194
+ Check that the return value is compatible with the return value annotation in the function.
195
+
196
+ :param retval: the value about to be returned from the call
197
+ :return: ``retval`` unchanged
198
+ :raises TypeCheckError: if there is a type mismatch
199
+
200
+ .. version-changed:: 4.5.0
201
+ This function was restored since its removal in v3.0.0.
202
+
203
+ """
204
+ # faster than inspect.currentframe(), but not officially
205
+ # supported in all python implementations
206
+ frame = sys._getframe(1)
207
+ func = find_function(frame)
208
+ memo = TypeCheckMemo(frame.f_globals, frame.f_locals)
209
+ type_hints = get_type_hints(func, frame.f_globals, frame.f_locals)
210
+ return check_return_type_internal(func.__name__, retval, type_hints["return"], memo)
211
+
212
+
213
+ def check_return_type_internal(
150
214
  func_name: str,
151
215
  retval: T,
152
216
  annotation: Any,
@@ -243,42 +307,39 @@ def check_yield_type(
243
307
 
244
308
 
245
309
  def check_variable_assignment(
246
- value: Any, targets: Sequence[list[tuple[str, Any]]], memo: TypeCheckMemo
310
+ value: Any,
311
+ groups: Sequence[list[tuple[str, Any]] | tuple[str, Any]],
312
+ memo: TypeCheckMemo,
247
313
  ) -> Any:
248
314
  if _suppression.type_checks_suppressed:
249
315
  return value
250
316
 
251
317
  value_to_return = value
252
- for target in targets:
253
- star_variable_index = next(
254
- (i for i, (varname, _) in enumerate(target) if varname.startswith("*")),
255
- None,
256
- )
257
- if star_variable_index is not None:
258
- value_to_return = list(value)
259
- remaining_vars = len(target) - 1 - star_variable_index
260
- end_index = len(value_to_return) - remaining_vars
261
- values_to_check = (
262
- value_to_return[:star_variable_index]
263
- + [value_to_return[star_variable_index:end_index]]
264
- + value_to_return[end_index:]
265
- )
266
- elif len(target) > 1:
267
- values_to_check = value_to_return = []
268
- iterator = iter(value)
269
- for _ in target:
270
- try:
271
- values_to_check.append(next(iterator))
272
- except StopIteration:
273
- raise ValueError(
274
- f"not enough values to unpack (expected {len(target)}, got "
275
- f"{len(values_to_check)})"
276
- ) from None
277
-
278
- else:
279
- values_to_check = [value]
318
+ for targets in groups:
319
+ values_to_check: list[tuple[Any, str, Any]]
320
+ if isinstance(targets, list):
321
+ values_to_check = []
322
+
323
+ # Get all the available values from a generator or arbitrary iterator
324
+ if not isinstance(value_to_return, list):
325
+ value_to_return = list(value)
326
+
327
+ iterator = iter(value_to_return)
328
+ for index, (name, annotation) in enumerate(targets):
329
+ if name.startswith("*"):
330
+ remaining_values = list(iterator)
331
+ num_remaining_targets = len(targets) - 1 - index
332
+ cutoff_offset = len(remaining_values) - num_remaining_targets
333
+ star_values = remaining_values[:cutoff_offset]
334
+ iterator = iter(remaining_values[cutoff_offset:])
335
+ values_to_check.append((star_values, name[1:], annotation))
336
+ else:
337
+ next_value = next(iterator)
338
+ values_to_check.append((next_value, name, annotation))
339
+ else: # single target, no unpacking
340
+ values_to_check = [(value,) + targets]
280
341
 
281
- for val, (varname, annotation) in zip(values_to_check, target):
342
+ for val, varname, annotation in values_to_check:
282
343
  try:
283
344
  check_type_internal(val, annotation, memo)
284
345
  except TypeCheckError as exc: