Загрузить файлы в «venv/Lib/site-packages/pydantic»

This commit is contained in:
2026-07-02 20:06:31 +00:00
parent cafb0ed1b7
commit 22146495c9
5 changed files with 244 additions and 0 deletions

View File

@@ -0,0 +1,5 @@
"""`typing` module is a backport module from V1."""
from ._migration import getattr_migration
__getattr__ = getattr_migration(__name__)

View File

@@ -0,0 +1,5 @@
"""The `utils` module is a backport module from V1."""
from ._migration import getattr_migration
__getattr__ = getattr_migration(__name__)

View File

@@ -0,0 +1,116 @@
"""Decorator for validating function calls."""
from __future__ import annotations as _annotations
import inspect
from functools import partial
from types import BuiltinFunctionType
from typing import TYPE_CHECKING, Any, Callable, TypeVar, cast, overload
from ._internal import _generate_schema, _typing_extra, _validate_call
from .errors import PydanticUserError
__all__ = ('validate_call',)
if TYPE_CHECKING:
from .config import ConfigDict
AnyCallableT = TypeVar('AnyCallableT', bound=Callable[..., Any])
_INVALID_TYPE_ERROR_CODE = 'validate-call-type'
def _check_function_type(function: object) -> None:
"""Check if the input function is a supported type for `validate_call`."""
if isinstance(function, _generate_schema.VALIDATE_CALL_SUPPORTED_TYPES):
try:
_typing_extra.signature_no_eval(cast(_generate_schema.ValidateCallSupportedTypes, function))
except (ValueError, TypeError):
raise PydanticUserError(
f"Input function `{function}` doesn't have a valid signature", code=_INVALID_TYPE_ERROR_CODE
)
if isinstance(function, partial):
try:
assert not isinstance(partial.func, partial), 'Partial of partial'
_check_function_type(function.func)
except PydanticUserError as e:
raise PydanticUserError(
f'Partial of `{function.func}` is invalid because the type of `{function.func}` is not supported by `validate_call`',
code=_INVALID_TYPE_ERROR_CODE,
) from e
return
if isinstance(function, BuiltinFunctionType):
raise PydanticUserError(f'Input built-in function `{function}` is not supported', code=_INVALID_TYPE_ERROR_CODE)
if isinstance(function, (classmethod, staticmethod, property)):
name = type(function).__name__
raise PydanticUserError(
f'The `@{name}` decorator should be applied after `@validate_call` (put `@{name}` on top)',
code=_INVALID_TYPE_ERROR_CODE,
)
if inspect.isclass(function):
raise PydanticUserError(
f'Unable to validate {function}: `validate_call` should be applied to functions, not classes (put `@validate_call` on top of `__init__` or `__new__` instead)',
code=_INVALID_TYPE_ERROR_CODE,
)
if callable(function):
raise PydanticUserError(
f'Unable to validate {function}: `validate_call` should be applied to functions, not instances or other callables. Use `validate_call` explicitly on `__call__` instead.',
code=_INVALID_TYPE_ERROR_CODE,
)
raise PydanticUserError(
f'Unable to validate {function}: `validate_call` should be applied to one of the following: function, method, partial, or lambda',
code=_INVALID_TYPE_ERROR_CODE,
)
@overload
def validate_call(
*, config: ConfigDict | None = None, validate_return: bool = False
) -> Callable[[AnyCallableT], AnyCallableT]: ...
@overload
def validate_call(func: AnyCallableT, /) -> AnyCallableT: ...
def validate_call(
func: AnyCallableT | None = None,
/,
*,
config: ConfigDict | None = None,
validate_return: bool = False,
) -> AnyCallableT | Callable[[AnyCallableT], AnyCallableT]:
"""!!! abstract "Usage Documentation"
[Validation Decorator](../concepts/validation_decorator.md)
Returns a decorated wrapper around the function that validates the arguments and, optionally, the return value.
Usage may be either as a plain decorator `@validate_call` or with arguments `@validate_call(...)`.
Args:
func: The function to be decorated.
config: The configuration dictionary.
validate_return: Whether to validate the return value.
Returns:
The decorated function.
"""
parent_namespace = _typing_extra.parent_frame_namespace()
def validate(function: AnyCallableT) -> AnyCallableT:
_check_function_type(function)
validate_call_wrapper = _validate_call.ValidateCallWrapper(
cast(_generate_schema.ValidateCallSupportedTypes, function), config, validate_return, parent_namespace
)
return _validate_call.update_wrapper_attributes(function, validate_call_wrapper.__call__) # type: ignore
if func is not None:
return validate(func)
else:
return validate

View File

@@ -0,0 +1,5 @@
"""The `validators` module is a backport module from V1."""
from ._migration import getattr_migration
__getattr__ = getattr_migration(__name__)

View File

@@ -0,0 +1,113 @@
"""The `version` module holds the version information for Pydantic."""
from __future__ import annotations as _annotations
import sys
from pydantic_core import __version__ as __pydantic_core_version__
__all__ = 'VERSION', 'version_info'
VERSION = '2.13.4'
"""The version of Pydantic.
This version specifier is guaranteed to be compliant with the [specification],
introduced by [PEP 440].
[specification]: https://packaging.python.org/en/latest/specifications/version-specifiers/
[PEP 440]: https://peps.python.org/pep-0440/
"""
# Keep this in sync with the version constraint in the `pyproject.toml` dependencies:
_COMPATIBLE_PYDANTIC_CORE_VERSION = '2.46.4'
def version_short() -> str:
"""Return the `major.minor` part of Pydantic version.
It returns '2.1' if Pydantic version is '2.1.1'.
"""
return '.'.join(VERSION.split('.')[:2])
def version_info() -> str:
"""Return complete version information for Pydantic and its dependencies."""
import importlib.metadata
import platform
from pathlib import Path
import pydantic_core._pydantic_core as pdc
from ._internal import _git as git
# get data about packages that are closely related to pydantic, use pydantic or often conflict with pydantic
package_names = {
'email-validator',
'fastapi',
'mypy',
'pydantic-extra-types',
'pydantic-settings',
'pyright',
'typing_extensions',
}
related_packages = []
for dist in importlib.metadata.distributions():
name = dist.metadata['Name']
if name in package_names:
related_packages.append(f'{name}-{dist.version}')
pydantic_dir = Path(__file__).parents[1].resolve()
most_recent_commit = (
git.git_revision(pydantic_dir) if git.is_git_repo(pydantic_dir) and git.have_git() else 'unknown'
)
info = {
'pydantic version': VERSION,
'pydantic-core version': __pydantic_core_version__,
'pydantic-core build': getattr(pdc, 'build_info', None) or pdc.build_profile, # pyright: ignore[reportPrivateImportUsage]
'python version': sys.version,
'platform': platform.platform(),
'related packages': ' '.join(related_packages),
'commit': most_recent_commit,
}
return '\n'.join('{:>30} {}'.format(k + ':', str(v).replace('\n', ' ')) for k, v in info.items())
def check_pydantic_core_version() -> bool:
"""Check that the installed `pydantic-core` dependency is compatible."""
return __pydantic_core_version__ == _COMPATIBLE_PYDANTIC_CORE_VERSION
def _ensure_pydantic_core_version() -> None: # pragma: no cover
if not check_pydantic_core_version():
raise_error = True
# Do not raise the error if pydantic is installed in editable mode (i.e. in development):
if sys.version_info >= (3, 13): # origin property added in 3.13
from importlib.metadata import distribution
dist = distribution('pydantic')
if getattr(getattr(dist.origin, 'dir_info', None), 'editable', False):
raise_error = False
if raise_error:
raise SystemError(
f'The installed pydantic-core version ({__pydantic_core_version__}) is incompatible '
f'with the current pydantic version, which requires {_COMPATIBLE_PYDANTIC_CORE_VERSION}. '
"If you encounter this error, make sure that you haven't upgraded pydantic-core manually."
)
def parse_mypy_version(version: str) -> tuple[int, int, int]:
"""Parse `mypy` string version to a 3-tuple of ints.
It parses normal version like `1.11.0` and extra info followed by a `+` sign
like `1.11.0+dev.d6d9d8cd4f27c52edac1f537e236ec48a01e54cb.dirty`.
Args:
version: The mypy version string.
Returns:
A triple of ints, e.g. `(1, 11, 0)`.
"""
return tuple(map(int, version.partition('+')[0].split('.'))) # pyright: ignore[reportReturnType]