Coverage for pydantic / _internal / _typing_extra.py: 97.45%

165 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-11-21 11:56 +0000

1"""Logic for interacting with type annotations, mostly extensions, shims and hacks to wrap Python's typing module.""" 

2 

3from __future__ import annotations 1pjkgabqlmhcdsrnoief

4 

5import re 1pjkgabqlmhcdsrnoief

6import sys 1pjkgabqlmhcdsrnoief

7import types 1pjkgabqlmhcdsrnoief

8import typing 1pjkgabqlmhcdsrnoief

9from collections.abc import Callable, MutableMapping 1pjkgabqlmhcdsrnoief

10from functools import partial 1pjkgabqlmhcdsrnoief

11from inspect import Signature, signature 1pjkgabqlmhcdsrnoief

12from types import NoneType 1pjkgabqlmhcdsrnoief

13from typing import TYPE_CHECKING, Any, ForwardRef, cast 1pjkgabqlmhcdsrnoief

14 

15import typing_extensions 1pjkgabqlmhcdsrnoief

16from typing_extensions import get_args, get_origin # noqa: UP035 (for `get_args` and `get_origin`) 1pjkgabqlmhcdsrnoief

17from typing_inspection import typing_objects 1pjkgabqlmhcdsrnoief

18from typing_inspection.introspection import is_union_origin 1pjkgabqlmhcdsrnoief

19 

20from pydantic.version import version_short 1pjkgabqlmhcdsrnoief

21 

22from ._namespace_utils import GlobalsNamespace, MappingNamespace, NsResolver, get_module_ns_of 1pjkgabqlmhcdsrnoief

23 

24if sys.version_info >= (3, 14): 1pjkgabqlmhcdsrnoief

25 import annotationlib 1gabhcdief

26 

27if TYPE_CHECKING: 1pjkgabqlmhcdsrnoief

28 from pydantic import BaseModel 

29 from pydantic.fields import FieldInfo 

30 

31# As per https://typing-extensions.readthedocs.io/en/latest/#runtime-use-of-types, 

32# always check for both `typing` and `typing_extensions` variants of a typing construct. 

33# (this is implemented differently than the suggested approach in the `typing_extensions` 

34# docs for performance). 

35 

36 

37_t_annotated = typing.Annotated 1pjkgabqlmhcdsrnoief

38_te_annotated = typing_extensions.Annotated 1pjkgabqlmhcdsrnoief

39 

40 

41def is_annotated(tp: Any, /) -> bool: 1pjkgabqlmhcdsrnoief

42 """Return whether the provided argument is a `Annotated` special form. 

43 

44 ```python {test="skip" lint="skip"} 

45 is_annotated(Annotated[int, ...]) 

46 #> True 

47 ``` 

48 """ 

49 origin = get_origin(tp) 

50 return origin is _t_annotated or origin is _te_annotated 

51 

52 

53def annotated_type(tp: Any, /) -> Any | None: 1pjkgabqlmhcdsrnoief

54 """Return the type of the `Annotated` special form, or `None`.""" 

55 return tp.__origin__ if typing_objects.is_annotated(get_origin(tp)) else None 1pjkgabqlmhcdrnoief

56 

57 

58def unpack_type(tp: Any, /) -> Any | None: 1pjkgabqlmhcdsrnoief

59 """Return the type wrapped by the `Unpack` special form, or `None`.""" 

60 return get_args(tp)[0] if typing_objects.is_unpack(get_origin(tp)) else None 1pjkgabqlmhcdrnoief

61 

62 

63_classvar_re = re.compile(r'((\w+\.)?Annotated\[)?(\w+\.)?ClassVar\[') 1pjkgabqlmhcdsrnoief

64 

65 

66def is_classvar_annotation(tp: Any, /) -> bool: 1pjkgabqlmhcdsrnoief

67 """Return whether the provided argument represents a class variable annotation. 

68 

69 Although not explicitly stated by the typing specification, `ClassVar` can be used 

70 inside `Annotated` and as such, this function checks for this specific scenario. 

71 

72 Because this function is used to detect class variables before evaluating forward references 

73 (or because evaluation failed), we also implement a naive regex match implementation. This is 

74 required because class variables are inspected before fields are collected, so we try to be 

75 as accurate as possible. 

76 """ 

77 if typing_objects.is_classvar(tp): 1pjkgabqlmhcdsrnoief

78 return True 1pjkgabqlmhcdrnoief

79 

80 origin = get_origin(tp) 1pjkgabqlmhcdsrnoief

81 

82 if typing_objects.is_classvar(origin): 1pjkgabqlmhcdsrnoief

83 return True 1pjkgabqlmhcdsrnoief

84 

85 if typing_objects.is_annotated(origin): 1pjkgabqlmhcdsrnoief

86 annotated_type = tp.__origin__ 1pjkgabqlmhcdrnoief

87 if typing_objects.is_classvar(annotated_type) or typing_objects.is_classvar(get_origin(annotated_type)): 1pjkgabqlmhcdrnoief

88 return True 1pjkgabqlmhcdrnoief

89 

90 str_ann: str | None = None 1pjkgabqlmhcdsrnoief

91 if isinstance(tp, typing.ForwardRef): 1pjkgabqlmhcdsrnoief

92 str_ann = tp.__forward_arg__ 1pjkgabqlmhcdsrnoief

93 if isinstance(tp, str): 1pjkgabqlmhcdsrnoief

94 str_ann = tp 1pjkgabqlmhcdrnoief

95 

96 if str_ann is not None and _classvar_re.match(str_ann): 1pjkgabqlmhcdsrnoief

97 # stdlib dataclasses do something similar, although a bit more advanced 

98 # (see `dataclass._is_type`). 

99 return True 1pjkgabqlmhcdrnoief

100 

101 return False 1pjkgabqlmhcdsrnoief

102 

103 

104def is_namedtuple(tp: Any, /) -> bool: 1pjkgabqlmhcdsrnoief

105 """Return whether the provided argument is a named tuple class. 

106 

107 The class can be created using `typing.NamedTuple` or `collections.namedtuple`. 

108 Parametrized generic classes are *not* assumed to be named tuples. 

109 """ 

110 from ._utils import lenient_issubclass # circ. import 1pjkgabqlmhcdsrnoief

111 

112 return lenient_issubclass(tp, tuple) and hasattr(tp, '_fields') 1pjkgabqlmhcdsrnoief

113 

114 

115# TODO In 2.12, delete this export. It is currently defined only to not break 

116# pydantic-settings which relies on it: 

117origin_is_union = is_union_origin 1pjkgabqlmhcdsrnoief

118 

119 

120def is_generic_alias(tp: Any, /) -> bool: 1pjkgabqlmhcdsrnoief

121 return isinstance(tp, (types.GenericAlias, typing._GenericAlias)) # pyright: ignore[reportAttributeAccessIssue] 1pjkgabqlmhcdrnoief

122 

123 

124# TODO: Ideally, we should avoid relying on the private `typing` constructs: 

125WithArgsTypes: tuple[Any, ...] = (typing._GenericAlias, types.GenericAlias, types.UnionType) # pyright: ignore[reportAttributeAccessIssue] 1pjkgabqlmhcdsrnoief

126 

127# Similarly, we shouldn't rely on this `_Final` class, which is even more private than `_GenericAlias`: 

128typing_base: Any = typing._Final # pyright: ignore[reportAttributeAccessIssue] 1pjkgabqlmhcdsrnoief

129 

130 

131### Annotation evaluations functions: 

132 

133 

134def parent_frame_namespace(*, parent_depth: int = 2, force: bool = False) -> MutableMapping[str, Any] | None: 1pjkgabqlmhcdsrnoief

135 """Fetch the local namespace of the parent frame where this function is called. 

136 

137 Using this function is mostly useful to resolve forward annotations pointing to members defined in a local namespace, 

138 such as assignments inside a function. Using the standard library tools, it is currently not possible to resolve 

139 such annotations: 

140 

141 ```python {lint="skip" test="skip"} 

142 from typing import get_type_hints 

143 

144 def func() -> None: 

145 Alias = int 

146 

147 class C: 

148 a: 'Alias' 

149 

150 # Raises a `NameError: 'Alias' is not defined` 

151 get_type_hints(C) 

152 ``` 

153 

154 Pydantic uses this function when a Pydantic model is being defined to fetch the parent frame locals. However, 

155 this only allows us to fetch the parent frame namespace and not other parents (e.g. a model defined in a function, 

156 itself defined in another function). Inspecting the next outer frames (using `f_back`) is not reliable enough 

157 (see https://discuss.python.org/t/20659). 

158 

159 Because this function is mostly used to better resolve forward annotations, nothing is returned if the parent frame's 

160 code object is defined at the module level. In this case, the locals of the frame will be the same as the module 

161 globals where the class is defined (see `_namespace_utils.get_module_ns_of`). However, if you still want to fetch 

162 the module globals (e.g. when rebuilding a model, where the frame where the rebuild call is performed might contain 

163 members that you want to use for forward annotations evaluation), you can use the `force` parameter. 

164 

165 Args: 

166 parent_depth: The depth at which to get the frame. Defaults to 2, meaning the parent frame where this function 

167 is called will be used. 

168 force: Whether to always return the frame locals, even if the frame's code object is defined at the module level. 

169 

170 Returns: 

171 The locals of the namespace, or `None` if it was skipped as per the described logic. 

172 """ 

173 frame = sys._getframe(parent_depth) 1pjkgabqlmhcdsrnoief

174 

175 if frame.f_code.co_name.startswith('<generic parameters of'): 1pjkgabqlmhcdsrnoief

176 # As `parent_frame_namespace` is mostly called in `ModelMetaclass.__new__`, 

177 # the parent frame can be the annotation scope if the PEP 695 generic syntax is used. 

178 # (see https://docs.python.org/3/reference/executionmodel.html#annotation-scopes, 

179 # https://docs.python.org/3/reference/compound_stmts.html#generic-classes). 

180 # In this case, the code name is set to `<generic parameters of MyClass>`, 

181 # and we need to skip this frame as it is irrelevant. 

182 frame = cast(types.FrameType, frame.f_back) # guaranteed to not be `None` 1jkgablmhcdnoief

183 

184 # note, we don't copy frame.f_locals here (or during the last return call), because we don't expect the namespace to be 

185 # modified down the line if this becomes a problem, we could implement some sort of frozen mapping structure to enforce this. 

186 if force: 1pjkgabqlmhcdsrnoief

187 return frame.f_locals 1pjkgabqlmhcdsrnoief

188 

189 # If either of the following conditions are true, the class is defined at the top module level. 

190 # To better understand why we need both of these checks, see 

191 # https://github.com/pydantic/pydantic/pull/10113#discussion_r1714981531. 

192 if frame.f_back is None or frame.f_code.co_name == '<module>': 1pjkgabqlmhcdsrnoief

193 return None 1pjkgabqlmhcdsrnoief

194 

195 return frame.f_locals 1pjkgabqlmhcdsrnoief

196 

197 

198def _type_convert(arg: Any) -> Any: 1pjkgabqlmhcdsrnoief

199 """Convert `None` to `NoneType` and strings to `ForwardRef` instances. 

200 

201 This is a vendored version of the private `typing._type_convert()` function. When 

202 evaluating a type, `ForwardRef._evaluate()` ends up being called, and is 

203 responsible for making this conversion. However, we still have to apply 

204 it for the first argument passed to our type evaluation functions, similarly 

205 to the `typing.get_type_hints()` function. 

206 """ 

207 if arg is None: 1pjkgabqlmhcdsrnoief

208 return NoneType 1pjkgabqlmhcdrnoief

209 if isinstance(arg, str): 1pjkgabqlmhcdsrnoief

210 # Like `typing.get_type_hints()`, assume the arg can be in any context, 

211 # hence the proper `is_argument` and `is_class` args: 

212 return ForwardRef(arg, is_argument=False, is_class=True) 1pjkgabqlmhcdsrnoief

213 return arg 1pjkgabqlmhcdsrnoief

214 

215 

216def safe_get_annotations(obj: Any) -> dict[str, Any]: 1pjkgabqlmhcdsrnoief

217 """Get the annotations for the provided object, accounting for potential deferred forward references. 

218 

219 Starting with Python 3.14, accessing the `__annotations__` attribute might raise a `NameError` if 

220 a referenced symbol isn't defined yet. In this case, we return the annotation in the *forward ref* 

221 format. 

222 """ 

223 if sys.version_info >= (3, 14): 1pjkgabqlmhcdsrnoief

224 return annotationlib.get_annotations(obj, format=annotationlib.Format.FORWARDREF) 1gabhcdief

225 else: 

226 if isinstance(obj, type): 1pjkqlmsrno

227 return obj.__dict__.get('__annotations__', {}) 1pjkqlmsrno

228 else: 

229 return getattr(obj, '__annotations__', {}) 1pjkqlmrno

230 

231 

232def get_model_type_hints( 1pjkgabqlmhcdsrnoief

233 model_class: type[BaseModel], 

234 *, 

235 ns_resolver: NsResolver | None = None, 

236) -> dict[str, tuple[Any, bool]]: 

237 """Collect annotations from a Pydantic model class, including those from parent classes. 

238 

239 Args: 

240 model_class: The Pydantic model class to inspect. 

241 ns_resolver: A namespace resolver instance to use. Defaults to an empty instance. 

242 

243 Returns: 

244 A dictionary mapping annotation names to a two-tuple: the first element is the evaluated 

245 type or the original annotation if a `NameError` occurred, the second element is a boolean 

246 indicating if whether the evaluation succeeded. 

247 """ 

248 hints: dict[str, Any] | dict[str, tuple[Any, bool]] = {} 1pjkgabqlmhcdsrnoief

249 ns_resolver = ns_resolver or NsResolver() 1pjkgabqlmhcdsrnoief

250 

251 for base in reversed(model_class.__mro__[:-1]): 1pjkgabqlmhcdsrnoief

252 # For Python 3.14, we could also use `Format.VALUE` and pass the globals/locals 

253 # from the ns_resolver, but we want to be able to know which specific field failed 

254 # to evaluate: 

255 ann = safe_get_annotations(base) 1pjkgabqlmhcdsrnoief

256 

257 if not ann: 1pjkgabqlmhcdsrnoief

258 continue 1pjkgabqlmhcdsrnoief

259 

260 with ns_resolver.push(base): 1pjkgabqlmhcdsrnoief

261 base_model_fields: dict[str, FieldInfo] | None = base.__dict__.get('__pydantic_fields__') 1pjkgabqlmhcdsrnoief

262 

263 for name, value in ann.items(): 1pjkgabqlmhcdsrnoief

264 if name.startswith('_'): 1pjkgabqlmhcdsrnoief

265 globalns, localns = ns_resolver.types_namespace 1pjkgabqlmhcdrnoief

266 

267 # For private attributes, we only need the annotation to detect the `ClassVar` special form. 

268 # For this reason, we still try to evaluate it, but we also catch any possible exception (on 

269 # top of the `NameError`s caught in `try_eval_type`) that could happen so that users are free 

270 # to use any kind of forward annotation for private fields (e.g. circular imports, new typing 

271 # syntax, etc). 

272 try: 1pjkgabqlmhcdrnoief

273 hints[name] = try_eval_type(value, globalns, localns) 1pjkgabqlmhcdrnoief

274 except Exception: 1pjkgabqlmhcdrnoief

275 hints[name] = (value, False) 1pjkgabqlmhcdrnoief

276 elif name == 'model_config': 1pjkgabqlmhcdsrnoief

277 # `model_config` is never a field, and `collect_model_fields()` ignores its annotation, 

278 # so there is no need to evaluate it: 

279 hints[name] = (value, False) 1pjkgabqlmhcdrnoief

280 else: 

281 if base_model_fields is not None and name in base_model_fields: 1pjkgabqlmhcdsrnoief

282 # Avoid unnecessarily evaluating annotations from parent models, as we'll end up 

283 # copying the `FieldInfo` instance from it anyway if we need to. 

284 # We use the `annotation` attribute here, but in reality could put anything here, 

285 # As we are guaranteed to not make use of it: 

286 hints[name] = (base_model_fields[name].annotation, True) 1pjkgabqlmhcdsrnoief

287 else: 

288 globalns, localns = ns_resolver.types_namespace 1pjkgabqlmhcdsrnoief

289 

290 hints[name] = try_eval_type(value, globalns, localns) 1pjkgabqlmhcdsrnoief

291 

292 return hints 1pjkgabqlmhcdsrnoief

293 

294 

295def get_cls_type_hints( 1pjkgabqlmhcdsrnoief

296 obj: type[Any], 

297 *, 

298 ns_resolver: NsResolver | None = None, 

299) -> dict[str, Any]: 

300 """Collect annotations from a class, including those from parent classes. 

301 

302 Args: 

303 obj: The class to inspect. 

304 ns_resolver: A namespace resolver instance to use. Defaults to an empty instance. 

305 """ 

306 hints: dict[str, Any] = {} 1pjkgabqlmhcdrnoief

307 ns_resolver = ns_resolver or NsResolver() 1pjkgabqlmhcdrnoief

308 

309 for base in reversed(obj.__mro__): 1pjkgabqlmhcdrnoief

310 # For Python 3.14, we could also use `Format.VALUE` and pass the globals/locals 

311 # from the ns_resolver, but we want to be able to know which specific field failed 

312 # to evaluate: 

313 ann = safe_get_annotations(base) 1pjkgabqlmhcdrnoief

314 

315 if not ann: 1pjkgabqlmhcdrnoief

316 continue 1pjkgabqlmhcdrnoief

317 

318 with ns_resolver.push(base): 1pjkgabqlmhcdrnoief

319 globalns, localns = ns_resolver.types_namespace 1pjkgabqlmhcdrnoief

320 for name, value in ann.items(): 1pjkgabqlmhcdrnoief

321 hints[name] = eval_type(value, globalns, localns) 1pjkgabqlmhcdrnoief

322 return hints 1pjkgabqlmhcdrnoief

323 

324 

325def try_eval_type( 1pjkgabqlmhcdsrnoief

326 value: Any, 

327 globalns: GlobalsNamespace | None = None, 

328 localns: MappingNamespace | None = None, 

329) -> tuple[Any, bool]: 

330 """Try evaluating the annotation using the provided namespaces. 

331 

332 Args: 

333 value: The value to evaluate. If `None`, it will be replaced by `type[None]`. If an instance 

334 of `str`, it will be converted to a `ForwardRef`. 

335 localns: The global namespace to use during annotation evaluation. 

336 globalns: The local namespace to use during annotation evaluation. 

337 

338 Returns: 

339 A two-tuple containing the possibly evaluated type and a boolean indicating 

340 whether the evaluation succeeded or not. 

341 """ 

342 try: 1pjkgabqlmhcdsrnoief

343 return eval_type(value, globalns, localns), True 1pjkgabqlmhcdsrnoief

344 except NameError: 1pjkgabqlmhcdsrnoief

345 return _type_convert(value), False 1pjkgabqlmhcdsrnoief

346 

347 

348def eval_type( 1pjkgabqlmhcdsrnoief

349 value: Any, 

350 globalns: GlobalsNamespace | None = None, 

351 localns: MappingNamespace | None = None, 

352 type_params: tuple[Any, ...] | None = None, 

353) -> Any: 

354 """Evaluate the annotation using the provided namespaces. 

355 

356 This function relies on our vendored `typing._eval_type()` function, and provide better error messages 

357 if possible. 

358 

359 Args: 

360 value: The value to evaluate (will be converted to `NoneType` if `None`, and to a `ForwardRef` instance if a string). 

361 localns: The global namespace to use during annotation evaluation. 

362 globalns: The local namespace to use during annotation evaluation. 

363 type_params: The type params belonging to the object being evaluated. 

364 """ 

365 value = _type_convert(value) 1pjkgabqlmhcdsrnoief

366 try: 1pjkgabqlmhcdsrnoief

367 return _eval_type(value, globalns, localns, type_params) 1pjkgabqlmhcdsrnoief

368 except ImportError as e: 1pjkgabqlmhcdsrnoief

369 # Starting in Python 3.15, resolving a lazy import during evaluation can fail, typically because of a 

370 # circular import between modules (an `ImportError` can also happen without lazy imports but this is 

371 # way less likely). Report it as a `NameError` so that callers treat the annotation as not resolvable 

372 # yet, exactly an undefined forward reference. 

373 if sys.version_info >= (3, 12): 373 ↛ 376line 373 didn't jump to line 376 because the condition on line 373 was always true1abcdef

374 name = e.name_from if e.name_from is not None else e.name 1abcdef

375 else: 

376 name = e.name 

377 raise NameError(f'Unable to resolve the import of {name!r}: {e}', name=name) from e 1abcdef

378 except TypeError as e: 1pjkgabqlmhcdsrnoief

379 if 'Unable to evaluate type annotation' in str(e): 379 ↛ 380line 379 didn't jump to line 380 because the condition on line 379 was never true1pjkgabqlmhcdrnoief

380 raise 

381 

382 # In most cases, value is a `ForwardRef`, otherwise the `TypeError` would have been raised when the annotation 

383 # was defined (at least on Python < 3.14). However, in rare cases, the `TypeError` can also appear when evaluating nested 

384 # parts of the annotation (e.g. `list["1 + 'a'"]`). 

385 if isinstance(value, ForwardRef): 1pjkgabqlmhcdrnoief

386 message = f'Unable to evaluate type annotation {value.__forward_arg__!r}.' 1pjkgabqlmhcdrnoief

387 else: 

388 message = f'Unable to evaluate type annotation {value!r}.' 1pjkgabqlmhcdrnoief

389 e.add_note(message) 1pjkgabqlmhcdrnoief

390 raise 1pjkgabqlmhcdrnoief

391 except RecursionError as e: 1pjkgabqlmhcdsrnoief

392 message = ( 1pjkgabqlmhcdrnoief

393 "If you made use of an implicit recursive type alias (e.g. `MyType = list['MyType']), " 

394 'consider using PEP 695 type aliases instead. For more details, refer to the documentation: ' 

395 f'https://pydantic.dev/docs/validation/{version_short()}/concepts/types/#named-recursive-types' 

396 ) 

397 e.add_note(message) 1pjkgabqlmhcdrnoief

398 raise 1pjkgabqlmhcdrnoief

399 

400 

401def _eval_type( 1pjkgabqlmhcdsrnoief

402 value: Any, 

403 globalns: GlobalsNamespace | None = None, 

404 localns: MappingNamespace | None = None, 

405 type_params: tuple[Any, ...] | None = None, 

406) -> Any: 

407 """Evaluate all forward references for a given type. 

408 

409 This is a vendored version of the private `typing._eval_type()` function, adapted to work for all supported Python versions. 

410 """ 

411 if sys.version_info >= (3, 14): 1pjkgabqlmhcdsrnoief

412 # Starting in 3.14, `_eval_type()` does *not* apply `_type_convert()` 

413 # anymore. This means the `None` -> `NoneType` conversion does not apply: 

414 evaluated = typing._eval_type( # type: ignore 1gabhcdief

415 value, 

416 globalns, 

417 localns, 

418 type_params=type_params, 

419 # This is relevant when evaluating types from `TypedDict` classes, where string annotations 

420 # are automatically converted to `ForwardRef` instances with a module set. In this case, 

421 # Our `globalns` is irrelevant and we need to indicate `typing._eval_type()` that it should 

422 # infer it from the `ForwardRef.__forward_module__` attribute instead (`typing.get_type_hints()` 

423 # does the same). Note that this would probably be unnecessary if we properly iterated over the 

424 # `__orig_bases__` for TypedDicts in `get_cls_type_hints()`: 

425 prefer_fwd_module=True, 

426 ) 

427 if evaluated is None: 1gabhcdief

428 evaluated = NoneType 1gabhcdief

429 return evaluated 1gabhcdief

430 elif sys.version_info >= (3, 13): 1pjkqlmsrno

431 return typing._eval_type( # type: ignore 1kmso

432 value, globalns, localns, type_params=type_params 

433 ) 

434 else: 

435 return typing._eval_type( # type: ignore 1pjqlrn

436 value, globalns, localns 

437 ) 

438 

439 

440def signature_no_eval(f: Callable[..., Any]) -> Signature: 1pjkgabqlmhcdsrnoief

441 """Get the signature of a callable without evaluating any annotations.""" 

442 if sys.version_info >= (3, 14): 1pjkgabqlmhcdsrnoief

443 from annotationlib import Format 1gabhcdief

444 

445 return signature(f, annotation_format=Format.FORWARDREF) 1gabhcdief

446 else: 

447 return signature(f) 1pjkqlmsrno

448 

449 

450def get_function_type_hints( 1pjkgabqlmhcdsrnoief

451 function: Callable[..., Any], 

452 *, 

453 include_keys: set[str] | None = None, 

454 globalns: GlobalsNamespace | None = None, 

455 localns: MappingNamespace | None = None, 

456) -> dict[str, Any]: 

457 """Return type hints for a function. 

458 

459 This is similar to the `typing.get_type_hints()` function, but with `functools.partial` support. 

460 """ 

461 if isinstance(function, partial): 1pjkgabqlmhcdrnoief

462 annotations = safe_get_annotations(function.func) 1pjkgabqlmhcdrnoief

463 else: 

464 annotations = safe_get_annotations(function) 1pjkgabqlmhcdrnoief

465 

466 if globalns is None: 1pjkgabqlmhcdrnoief

467 globalns = get_module_ns_of(function) 1pjkgabqlmhcdrnoief

468 type_params: tuple[Any, ...] | None = None 1pjkgabqlmhcdrnoief

469 if localns is None: 1pjkgabqlmhcdrnoief

470 # If localns was specified, it is assumed to already contain type params. This is because 

471 # Pydantic has more advanced logic to do so (see `_namespace_utils.ns_for_function`). 

472 type_params = getattr(function, '__type_params__', ()) 1pjkgabqlmhcdrnoief

473 

474 type_hints = {} 1pjkgabqlmhcdrnoief

475 for name, value in annotations.items(): 1pjkgabqlmhcdrnoief

476 if include_keys is not None and name not in include_keys: 1pjkgabqlmhcdrnoief

477 continue 1pjkgabqlmhcdrnoief

478 

479 type_hints[name] = eval_type(value, globalns, localns, type_params) 1pjkgabqlmhcdrnoief

480 

481 return type_hints 1pjkgabqlmhcdrnoief