|
2 | 2 |
|
3 | 3 | from __future__ import annotations |
4 | 4 |
|
5 | | -from collections.abc import Mapping, Sequence, Set |
| 5 | +from collections.abc import Callable, Mapping, Sequence |
| 6 | +from collections.abc import Set as AbstractSet |
6 | 7 | from dataclasses import fields, is_dataclass, replace |
7 | 8 | from functools import singledispatch |
8 | 9 | from typing import ( |
9 | 10 | Annotated, |
10 | 11 | Any, |
11 | 12 | ClassVar, |
12 | 13 | Literal, |
| 14 | + TypeVar, |
13 | 15 | get_args, |
14 | 16 | get_origin, |
15 | 17 | get_type_hints, |
16 | | - TypeVar, |
17 | 18 | ) |
18 | 19 |
|
19 | 20 | from annotated_types import Ge, Gt, Interval, Le, Len, Lt, MaxLen, MinLen, Predicate |
| 21 | + |
20 | 22 | from .annotation_types import is_union_type |
21 | 23 |
|
22 | 24 |
|
@@ -133,21 +135,21 @@ def validate_annotation_value( |
133 | 135 | ) |
134 | 136 | if origin is Literal: |
135 | 137 | choices = get_args(annotation) |
136 | | - if not any( |
137 | | - type(value) is type(choice) and value == choice |
138 | | - for choice in choices |
139 | | - ): |
| 138 | + if not any(type(value) is type(choice) and value == choice for choice in choices): |
140 | 139 | raise AnnotationValidationError(f"{path} must be one of {choices!r}.") |
141 | 140 | return |
142 | 141 | if origin is tuple: |
143 | 142 | _validate_tuple(annotation, value, path) |
144 | 143 | return |
145 | | - if origin in {list, set, frozenset, Sequence, Set}: |
| 144 | + if origin in {list, set, frozenset, Sequence, AbstractSet}: |
146 | 145 | _validate_sequence(annotation, value, path) |
147 | 146 | return |
148 | 147 | if origin in {dict, Mapping}: |
149 | 148 | _validate_mapping(annotation, value, path) |
150 | 149 | return |
| 150 | + if origin is Callable: |
| 151 | + _validate_callable(value, path) |
| 152 | + return |
151 | 153 | if origin is ClassVar: |
152 | 154 | return |
153 | 155 | if annotation is None or annotation is type(None): |
@@ -215,6 +217,11 @@ def _validate_mapping(annotation: object, value: object, path: str) -> None: |
215 | 217 | validate_annotation_value(item_type, item, path=f"{path}[{key!r}]") |
216 | 218 |
|
217 | 219 |
|
| 220 | +def _validate_callable(value: object, path: str) -> None: |
| 221 | + if not callable(value): |
| 222 | + raise TypeError(f"{path} must be callable; got {type(value).__name__}.") |
| 223 | + |
| 224 | + |
218 | 225 | def _annotation_label(annotation: object) -> str: |
219 | 226 | return annotation.__name__ if isinstance(annotation, type) else str(annotation) |
220 | 227 |
|
|
0 commit comments