diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5432bef346..1ba9f4336c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -131,7 +131,7 @@ jobs: fail-fast: false matrix: os: [macos, windows] - python-version: ['3.6', '3.7', '3.8', '3.9'] + python-version: ['3.6', '3.7', '3.8', '3.9', '3.10.0-beta.2'] env: PYTHON: ${{ matrix.python-version }} OS: ${{ matrix.os }} diff --git a/changes/2885-PrettyWood.md b/changes/2885-PrettyWood.md new file mode 100644 index 0000000000..1cc2afeb1a --- /dev/null +++ b/changes/2885-PrettyWood.md @@ -0,0 +1 @@ +add python 3.10 support diff --git a/docs/contributing.md b/docs/contributing.md index dfbacbcc11..b0e0dc52c6 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -33,7 +33,7 @@ To make contributing as easy and fast as possible, you'll want to run tests and *pydantic* has few dependencies, doesn't require compiling and tests don't need access to databases, etc. Because of this, setting up and running the tests should be very simple. -You'll need to have **python 3.6**, **3.7**, **3.8**, or **3.9**, **virtualenv**, **git**, and **make** installed. +You'll need to have a version between **python 3.6 and 3.10**, **virtualenv**, **git**, and **make** installed. ```bash # 1. clone your fork and cd into the repo directory diff --git a/docs/install.md b/docs/install.md index 0793196f6e..15341596b8 100644 --- a/docs/install.md +++ b/docs/install.md @@ -4,7 +4,7 @@ Installation is as simple as: pip install pydantic ``` -*pydantic* has no required dependencies except python 3.6, 3.7, 3.8, or 3.9, +*pydantic* has no required dependencies except python 3.6, 3.7, 3.8, 3.9 or 3.10, [`typing-extensions`](https://pypi.org/project/typing-extensions/), and the [`dataclasses`](https://pypi.org/project/dataclasses/) backport package for python 3.6. If you've got python 3.6+ and `pip` installed, you're good to go. diff --git a/pydantic/__init__.py b/pydantic/__init__.py index 16846d0888..7680ec3bec 100644 --- a/pydantic/__init__.py +++ b/pydantic/__init__.py @@ -2,6 +2,7 @@ from . import dataclasses from .annotated_types import create_model_from_namedtuple, create_model_from_typeddict from .class_validators import root_validator, validator +from .config import BaseConfig, Extra from .decorator import validate_arguments from .env_settings import BaseSettings from .error_wrappers import ValidationError @@ -27,6 +28,9 @@ # class_validators 'root_validator', 'validator', + # config + 'BaseConfig', + 'Extra', # decorator 'validate_arguments', # env_settings @@ -37,9 +41,7 @@ 'Field', 'Required', # main - 'BaseConfig', 'BaseModel', - 'Extra', 'compiled', 'create_model', 'validate_model', diff --git a/pydantic/annotated_types.py b/pydantic/annotated_types.py index bffcdc620c..0a2a24f367 100644 --- a/pydantic/annotated_types.py +++ b/pydantic/annotated_types.py @@ -42,9 +42,10 @@ def create_model_from_namedtuple(namedtuple_cls: Type['NamedTuple'], **kwargs: A but also with `collections.namedtuple`, in this case we consider all fields to have type `Any`. """ - namedtuple_annotations: Dict[str, Type[Any]] = getattr( - namedtuple_cls, '__annotations__', {k: Any for k in namedtuple_cls._fields} - ) + # With python 3.10+, `__annotations__` always exists but can be empty hence the `getattr... or...` logic + namedtuple_annotations: Dict[str, Type[Any]] = getattr(namedtuple_cls, '__annotations__', None) or { + k: Any for k in namedtuple_cls._fields + } field_definitions: Dict[str, Any] = { field_name: (field_type, Required) for field_name, field_type in namedtuple_annotations.items() } diff --git a/pydantic/class_validators.py b/pydantic/class_validators.py index 9cd951a58f..a93d570eae 100644 --- a/pydantic/class_validators.py +++ b/pydantic/class_validators.py @@ -33,8 +33,8 @@ def __init__( if TYPE_CHECKING: from inspect import Signature + from .config import BaseConfig from .fields import ModelField - from .main import BaseConfig from .types import ModelOrDc ValidatorCallable = Callable[[Optional[ModelOrDc], Any, Dict[str, Any], ModelField, Type[BaseConfig]], Any] diff --git a/pydantic/config.py b/pydantic/config.py new file mode 100644 index 0000000000..acd20da146 --- /dev/null +++ b/pydantic/config.py @@ -0,0 +1,124 @@ +import json +from enum import Enum +from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, Tuple, Type, Union + +from .typing import AnyCallable +from .utils import GetterDict + +if TYPE_CHECKING: + from typing import overload + + import typing_extensions + + from .fields import ModelField + from .main import BaseModel + + ConfigType = Type['BaseConfig'] + + class SchemaExtraCallable(typing_extensions.Protocol): + @overload + def __call__(self, schema: Dict[str, Any]) -> None: + pass + + @overload + def __call__(self, schema: Dict[str, Any], model_class: Type[BaseModel]) -> None: + pass + + +else: + SchemaExtraCallable = Callable[..., None] + +__all__ = 'BaseConfig', 'Extra', 'inherit_config', 'prepare_config' + + +class Extra(str, Enum): + allow = 'allow' + ignore = 'ignore' + forbid = 'forbid' + + +class BaseConfig: + title = None + anystr_lower = False + anystr_strip_whitespace = False + min_anystr_length = None + max_anystr_length = None + validate_all = False + extra = Extra.ignore + allow_mutation = True + frozen = False + allow_population_by_field_name = False + use_enum_values = False + fields: Dict[str, Union[str, Dict[str, str]]] = {} + validate_assignment = False + error_msg_templates: Dict[str, str] = {} + arbitrary_types_allowed = False + orm_mode: bool = False + getter_dict: Type[GetterDict] = GetterDict + alias_generator: Optional[Callable[[str], str]] = None + keep_untouched: Tuple[type, ...] = () + schema_extra: Union[Dict[str, Any], 'SchemaExtraCallable'] = {} + json_loads: Callable[[str], Any] = json.loads + json_dumps: Callable[..., str] = json.dumps + json_encoders: Dict[Type[Any], AnyCallable] = {} + underscore_attrs_are_private: bool = False + + # Whether or not inherited models as fields should be reconstructed as base model + copy_on_model_validation: bool = True + + @classmethod + def get_field_info(cls, name: str) -> Dict[str, Any]: + """ + Get properties of FieldInfo from the `fields` property of the config class. + """ + + fields_value = cls.fields.get(name) + + if isinstance(fields_value, str): + field_info: Dict[str, Any] = {'alias': fields_value} + elif isinstance(fields_value, dict): + field_info = fields_value + else: + field_info = {} + + if 'alias' in field_info: + field_info.setdefault('alias_priority', 2) + + if field_info.get('alias_priority', 0) <= 1 and cls.alias_generator: + alias = cls.alias_generator(name) + if not isinstance(alias, str): + raise TypeError(f'Config.alias_generator must return str, not {alias.__class__}') + field_info.update(alias=alias, alias_priority=1) + return field_info + + @classmethod + def prepare_field(cls, field: 'ModelField') -> None: + """ + Optional hook to check or modify fields during model creation. + """ + pass + + +def inherit_config(self_config: 'ConfigType', parent_config: 'ConfigType', **namespace: Any) -> 'ConfigType': + if not self_config: + base_classes: Tuple['ConfigType', ...] = (parent_config,) + elif self_config == parent_config: + base_classes = (self_config,) + else: + base_classes = self_config, parent_config + + namespace['json_encoders'] = { + **getattr(parent_config, 'json_encoders', {}), + **getattr(self_config, 'json_encoders', {}), + **namespace.get('json_encoders', {}), + } + + return type('Config', base_classes, namespace) + + +def prepare_config(config: Type[BaseConfig], cls_name: str) -> None: + if not isinstance(config.extra, Extra): + try: + config.extra = Extra(config.extra) + except ValueError: + raise ValueError(f'"{cls_name}": {config.extra} is not a valid value for "extra"') diff --git a/pydantic/dataclasses.py b/pydantic/dataclasses.py index 42ae685cac..a61dbc8781 100644 --- a/pydantic/dataclasses.py +++ b/pydantic/dataclasses.py @@ -9,7 +9,8 @@ from .utils import ClassAttribute if TYPE_CHECKING: - from .main import BaseConfig, BaseModel # noqa: F401 + from .config import BaseConfig + from .main import BaseModel from .typing import CallableGenerator, NoArgAnyCallable DataclassT = TypeVar('DataclassT', bound='Dataclass') diff --git a/pydantic/decorator.py b/pydantic/decorator.py index 266195ce50..869afee100 100644 --- a/pydantic/decorator.py +++ b/pydantic/decorator.py @@ -2,8 +2,9 @@ from typing import TYPE_CHECKING, Any, Callable, Dict, List, Mapping, Optional, Tuple, Type, TypeVar, Union, overload from . import validator +from .config import Extra from .errors import ConfigError -from .main import BaseModel, Extra, create_model +from .main import BaseModel, create_model from .typing import get_all_type_hints from .utils import to_camel diff --git a/pydantic/env_settings.py b/pydantic/env_settings.py index 71b5a976c2..2c8c11f4aa 100644 --- a/pydantic/env_settings.py +++ b/pydantic/env_settings.py @@ -3,8 +3,9 @@ from pathlib import Path from typing import AbstractSet, Any, Callable, Dict, List, Mapping, Optional, Tuple, Union +from .config import BaseConfig, Extra from .fields import ModelField -from .main import BaseConfig, BaseModel, Extra +from .main import BaseModel from .typing import display_as_type from .utils import deep_update, path_type, sequence_like diff --git a/pydantic/error_wrappers.py b/pydantic/error_wrappers.py index 92d957f8d9..59301eb57b 100644 --- a/pydantic/error_wrappers.py +++ b/pydantic/error_wrappers.py @@ -5,8 +5,8 @@ from .utils import Representation if TYPE_CHECKING: - from .main import BaseConfig # noqa: F401 - from .types import ModelOrDc # noqa: F401 + from .config import BaseConfig + from .types import ModelOrDc from .typing import ReprArgs Loc = Tuple[Union[int, str], ...] diff --git a/pydantic/fields.py b/pydantic/fields.py index dc79dbfa7c..33b9b7e0b9 100644 --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -1,5 +1,5 @@ from collections import defaultdict, deque -from collections.abc import Iterable as CollectionsIterable +from collections.abc import Hashable as CollectionsHashable, Iterable as CollectionsIterable from typing import ( TYPE_CHECKING, Any, @@ -41,6 +41,7 @@ is_literal_type, is_new_type, is_typeddict, + is_union, new_type_supertype, ) from .utils import PyObjectStr, Representation, ValueItems, lenient_issubclass, sequence_like, smart_deepcopy @@ -68,11 +69,11 @@ def __deepcopy__(self: T, _: Any) -> T: Undefined = UndefinedType() if TYPE_CHECKING: - from .class_validators import ValidatorsList # noqa: F401 + from .class_validators import ValidatorsList + from .config import BaseConfig from .error_wrappers import ErrorList - from .main import BaseConfig, BaseModel # noqa: F401 - from .types import ModelOrDc # noqa: F401 - from .typing import AbstractSetIntStr, MappingIntStrAny, ReprArgs # noqa: F401 + from .types import ModelOrDc + from .typing import AbstractSetIntStr, MappingIntStrAny, ReprArgs ValidateReturn = Tuple[Optional[Any], Optional[ErrorList]] LocStr = Union[Tuple[Union[int, str], ...], str] @@ -543,7 +544,8 @@ def _type_analysis(self) -> None: # noqa: C901 (ignore complexity) return origin = get_origin(self.type_) - if origin is None: + # add extra check for `collections.abc.Hashable` for python 3.10+ where origin is not `None` + if origin is None or origin is CollectionsHashable: # field is not "typing" object eg. Union, Dict, List etc. # allow None for virtual superclasses of NoneType, e.g. Hashable if isinstance(self.type_, type) and isinstance(None, self.type_): @@ -555,7 +557,7 @@ def _type_analysis(self) -> None: # noqa: C901 (ignore complexity) return if origin is Callable: return - if origin is Union: + if is_union(origin): types_ = [] for type_ in get_args(self.type_): if type_ is NoneType: @@ -948,7 +950,7 @@ def is_complex(self) -> bool: """ Whether the field is "complex" eg. env variables should be parsed as JSON. """ - from .main import BaseModel # noqa: F811 + from .main import BaseModel return ( self.shape != SHAPE_SINGLETON diff --git a/pydantic/main.py b/pydantic/main.py index a67237cfad..de6cd8ca2a 100644 --- a/pydantic/main.py +++ b/pydantic/main.py @@ -1,4 +1,3 @@ -import json import sys import warnings from abc import ABCMeta @@ -22,10 +21,10 @@ Union, cast, no_type_check, - overload, ) from .class_validators import ValidatorGroup, extract_root_validators, extract_validators, inherit_validators +from .config import BaseConfig, Extra, inherit_config, prepare_config from .error_wrappers import ErrorWrapper, ValidationError from .errors import ConfigError, DictError, ExtraError, MissingError from .fields import MAPPING_LIKE_SHAPES, ModelField, ModelPrivateAttr, PrivateAttr, Undefined @@ -39,6 +38,7 @@ get_origin, is_classvar, is_namedtuple, + is_union, resolve_annotations, update_field_forward_refs, ) @@ -61,11 +61,9 @@ if TYPE_CHECKING: from inspect import Signature - import typing_extensions - from .class_validators import ValidatorListDict from .types import ModelOrDc - from .typing import ( # noqa: F401 + from .typing import ( AbstractSetIntStr, CallableGenerator, DictAny, @@ -76,21 +74,8 @@ TupleGenerator, ) - ConfigType = Type['BaseConfig'] Model = TypeVar('Model', bound='BaseModel') - class SchemaExtraCallable(typing_extensions.Protocol): - @overload - def __call__(self, schema: Dict[str, Any]) -> None: - pass - - @overload # noqa: F811 - def __call__(self, schema: Dict[str, Any], model_class: Type['Model']) -> None: # noqa: F811 - pass - - -else: - SchemaExtraCallable = Callable[..., None] try: import cython # type: ignore @@ -102,103 +87,7 @@ def __call__(self, schema: Dict[str, Any], model_class: Type['Model']) -> None: except AttributeError: compiled = False -__all__ = 'BaseConfig', 'BaseModel', 'Extra', 'compiled', 'create_model', 'validate_model' - - -class Extra(str, Enum): - allow = 'allow' - ignore = 'ignore' - forbid = 'forbid' - - -class BaseConfig: - title = None - anystr_lower = False - anystr_strip_whitespace = False - min_anystr_length = None - max_anystr_length = None - validate_all = False - extra = Extra.ignore - allow_mutation = True - frozen = False - allow_population_by_field_name = False - use_enum_values = False - fields: Dict[str, Union[str, Dict[str, str]]] = {} - validate_assignment = False - error_msg_templates: Dict[str, str] = {} - arbitrary_types_allowed = False - orm_mode: bool = False - getter_dict: Type[GetterDict] = GetterDict - alias_generator: Optional[Callable[[str], str]] = None - keep_untouched: Tuple[type, ...] = () - schema_extra: Union[Dict[str, Any], 'SchemaExtraCallable'] = {} - json_loads: Callable[[str], Any] = json.loads - json_dumps: Callable[..., str] = json.dumps - json_encoders: Dict[Type[Any], AnyCallable] = {} - underscore_attrs_are_private: bool = False - - # Whether or not inherited models as fields should be reconstructed as base model - copy_on_model_validation: bool = True - - @classmethod - def get_field_info(cls, name: str) -> Dict[str, Any]: - """ - Get properties of FieldInfo from the `fields` property of the config class. - """ - - fields_value = cls.fields.get(name) - - if isinstance(fields_value, str): - field_info: Dict[str, Any] = {'alias': fields_value} - elif isinstance(fields_value, dict): - field_info = fields_value - else: - field_info = {} - - if 'alias' in field_info: - field_info.setdefault('alias_priority', 2) - - if field_info.get('alias_priority', 0) <= 1 and cls.alias_generator: - alias = cls.alias_generator(name) - if not isinstance(alias, str): - raise TypeError(f'Config.alias_generator must return str, not {alias.__class__}') - field_info.update(alias=alias, alias_priority=1) - return field_info - - @classmethod - def prepare_field(cls, field: 'ModelField') -> None: - """ - Optional hook to check or modify fields during model creation. - """ - pass - - -def inherit_config(self_config: 'ConfigType', parent_config: 'ConfigType', **namespace: Any) -> 'ConfigType': - if not self_config: - base_classes: Tuple['ConfigType', ...] = (parent_config,) - elif self_config == parent_config: - base_classes = (self_config,) - else: - base_classes = self_config, parent_config - - namespace['json_encoders'] = { - **getattr(parent_config, 'json_encoders', {}), - **getattr(self_config, 'json_encoders', {}), - **namespace.get('json_encoders', {}), - } - - return type('Config', base_classes, namespace) - - -EXTRA_LINK = 'https://pydantic-docs.helpmanual.io/usage/model_config/' - - -def prepare_config(config: Type[BaseConfig], cls_name: str) -> None: - if not isinstance(config.extra, Extra): - try: - config.extra = Extra(config.extra) - except ValueError: - raise ValueError(f'"{cls_name}": {config.extra} is not a valid value for "extra"') +__all__ = 'BaseModel', 'compiled', 'create_model', 'validate_model' def validate_custom_root_type(fields: Dict[str, ModelField]) -> None: @@ -287,7 +176,7 @@ def is_untouched(v: Any) -> bool: elif is_valid_field(ann_name): validate_field_name(bases, ann_name) value = namespace.get(ann_name, Undefined) - allowed_types = get_args(ann_type) if get_origin(ann_type) is Union else (ann_type,) + allowed_types = get_args(ann_type) if is_union(get_origin(ann_type)) else (ann_type,) if ( is_untouched(value) and ann_type != PyObject diff --git a/pydantic/networks.py b/pydantic/networks.py index 090b4fb4ad..69909967e1 100644 --- a/pydantic/networks.py +++ b/pydantic/networks.py @@ -32,8 +32,8 @@ if TYPE_CHECKING: import email_validator + from .config import BaseConfig from .fields import ModelField - from .main import BaseConfig # noqa: F401 from .typing import AnyCallable CallableGenerator = Generator[AnyCallable, None, None] diff --git a/pydantic/schema.py b/pydantic/schema.py index f990c5f4f5..e8f901d8ab 100644 --- a/pydantic/schema.py +++ b/pydantic/schema.py @@ -71,12 +71,13 @@ is_callable_type, is_literal_type, is_namedtuple, + is_union, ) from .utils import ROOT_KEY, get_model, lenient_issubclass, sequence_like if TYPE_CHECKING: - from .dataclasses import Dataclass # noqa: F401 - from .main import BaseModel # noqa: F401 + from .dataclasses import Dataclass + from .main import BaseModel default_prefix = '#/definitions/' default_ref_template = '#/definitions/{model}' @@ -364,7 +365,7 @@ def get_flat_models_from_field(field: ModelField, known_models: TypeModelSet) -> :return: a set with the model used in the declaration for this field, if any, and all its sub-models """ from .dataclasses import dataclass, is_builtin_dataclass - from .main import BaseModel # noqa: F811 + from .main import BaseModel flat_models: TypeModelSet = set() @@ -765,7 +766,7 @@ def field_singleton_schema( # noqa: C901 (ignore complexity) Take a single Pydantic ``ModelField``, and return its schema and any additional definitions from sub-models. """ - from .main import BaseModel # noqa: F811 + from .main import BaseModel definitions: Dict[str, Any] = {} nested_models: Set[str] = set() @@ -965,7 +966,7 @@ def go(type_: Any) -> Type[Any]: if origin is Annotated: return go(args[0]) - if origin is Union: + if is_union(origin): return Union[tuple(go(a) for a in args)] # type: ignore if issubclass(origin, List) and (field_info.min_items is not None or field_info.max_items is not None): diff --git a/pydantic/types.py b/pydantic/types.py index aede7f87d6..ca7ada5f53 100644 --- a/pydantic/types.py +++ b/pydantic/types.py @@ -109,8 +109,8 @@ StrIntFloat = Union[str, int, float] if TYPE_CHECKING: - from .dataclasses import Dataclass # noqa: F401 - from .main import BaseConfig, BaseModel # noqa: F401 + from .dataclasses import Dataclass + from .main import BaseModel from .typing import CallableGenerator ModelOrDc = Type[Union['BaseModel', 'Dataclass']] diff --git a/pydantic/typing.py b/pydantic/typing.py index 1a3bf43de4..b98b543cba 100644 --- a/pydantic/typing.py +++ b/pydantic/typing.py @@ -189,6 +189,19 @@ def get_args(tp: Type[Any]) -> Tuple[Any, ...]: return _typing_get_args(tp) or getattr(tp, '__args__', ()) or _generic_get_args(tp) +if sys.version_info < (3, 10): + + def is_union(tp: Type[Any]) -> bool: + return tp is Union + + +else: + import types + + def is_union(tp: Type[Any]) -> bool: + return tp is Union or tp is types.Union + + if TYPE_CHECKING: from .fields import ModelField @@ -238,6 +251,7 @@ def get_args(tp: Type[Any]) -> Tuple[Any, ...]: 'get_origin', 'typing_base', 'get_all_type_hints', + 'is_union', ) diff --git a/pydantic/utils.py b/pydantic/utils.py index c2a6e514f0..292d58d49d 100644 --- a/pydantic/utils.py +++ b/pydantic/utils.py @@ -30,10 +30,11 @@ from inspect import Signature from pathlib import Path - from .dataclasses import Dataclass # noqa: F401 - from .fields import ModelField # noqa: F401 - from .main import BaseConfig, BaseModel # noqa: F401 - from .typing import AbstractSetIntStr, DictIntStrAny, IntStr, MappingIntStrAny, ReprArgs # noqa: F401 + from .config import BaseConfig + from .dataclasses import Dataclass + from .fields import ModelField + from .main import BaseModel + from .typing import AbstractSetIntStr, DictIntStrAny, IntStr, MappingIntStrAny, ReprArgs __all__ = ( 'import_string', @@ -201,6 +202,8 @@ def generate_model_signature( """ from inspect import Parameter, Signature, signature + from .config import Extra + present_params = signature(init).parameters.values() merged_params: Dict[str, Parameter] = {} var_kw = None @@ -231,7 +234,7 @@ def generate_model_signature( param_name, Parameter.KEYWORD_ONLY, annotation=field.outer_type_, **kwargs ) - if config.extra is config.extra.allow: + if config.extra is Extra.allow: use_var_kw = True if var_kw and use_var_kw: @@ -257,7 +260,7 @@ def generate_model_signature( def get_model(obj: Union[Type['BaseModel'], Type['Dataclass']]) -> Type['BaseModel']: - from .main import BaseModel # noqa: F811 + from .main import BaseModel try: model_cls = obj.__pydantic_model__ # type: ignore diff --git a/pydantic/validators.py b/pydantic/validators.py index 57a1a23fcc..6d14c537ae 100644 --- a/pydantic/validators.py +++ b/pydantic/validators.py @@ -1,6 +1,6 @@ import re from collections import OrderedDict, deque -from collections.abc import Hashable +from collections.abc import Hashable as CollectionsHashable from datetime import date, datetime, time, timedelta from decimal import Decimal, DecimalException from enum import Enum, IntEnum @@ -14,6 +14,7 @@ Dict, FrozenSet, Generator, + Hashable, List, NamedTuple, Pattern, @@ -45,8 +46,8 @@ if TYPE_CHECKING: from .annotated_types import TypedDict + from .config import BaseConfig from .fields import ModelField - from .main import BaseConfig from .types import ConstrainedDecimal, ConstrainedFloat, ConstrainedInt ConstrainedNumber = Union[ConstrainedDecimal, ConstrainedFloat, ConstrainedInt] @@ -662,7 +663,7 @@ def find_validators( # noqa: C901 (ignore complexity) if type_ is Pattern: yield pattern_validator return - if type_ is Hashable: + if type_ is Hashable or type_ is CollectionsHashable: yield hashable_validator return if is_callable_type(type_): diff --git a/setup.cfg b/setup.cfg index b79fa54f2b..242bde3fa2 100644 --- a/setup.cfg +++ b/setup.cfg @@ -5,6 +5,9 @@ filterwarnings = error ignore::DeprecationWarning:distutils ignore::DeprecationWarning:Cython + # for python 3.10+: mypy still relies on distutils on windows. We hence ignore those warnings + ignore:The distutils package is deprecated and slated for removal in Python 3.12:DeprecationWarning + ignore:The distutils.sysconfig module is deprecated, use sysconfig instead:DeprecationWarning [flake8] max-line-length = 120 diff --git a/setup.py b/setup.py index e93107b0f5..fb22f35fbb 100644 --- a/setup.py +++ b/setup.py @@ -7,7 +7,7 @@ from setuptools import setup if os.name == 'nt': - from distutils.command import build_ext + from setuptools.command import build_ext def get_export_symbols(self, ext): """ @@ -108,6 +108,7 @@ def extra(self): 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', + 'Programming Language :: Python :: 3.10', 'Intended Audience :: Developers', 'Intended Audience :: Information Technology', 'Intended Audience :: System Administrators', diff --git a/tests/test_dataclasses.py b/tests/test_dataclasses.py index fd122f8a8a..c5e6a1ec6a 100644 --- a/tests/test_dataclasses.py +++ b/tests/test_dataclasses.py @@ -637,7 +637,7 @@ class MyDataclass: ] with pytest.raises(TypeError) as exc_info: MyDataclass() - assert str(exc_info.value) == "__init__() missing 1 required positional argument: 'v'" + assert "__init__() missing 1 required positional argument: 'v'" in str(exc_info.value) @pytest.mark.parametrize('default', [1, None, ...]) diff --git a/tests/test_decorator.py b/tests/test_decorator.py index 6b11fb285c..cbfc2dd557 100644 --- a/tests/test_decorator.py +++ b/tests/test_decorator.py @@ -267,7 +267,7 @@ async def run(): v = await foo(1, 2) assert v == 'a=1 b=2' - loop = asyncio.get_event_loop() + loop = asyncio.get_event_loop_policy().get_event_loop() loop.run_until_complete(run()) with pytest.raises(ValidationError) as exc_info: loop.run_until_complete(foo('x')) diff --git a/tests/test_edge_cases.py b/tests/test_edge_cases.py index 42a263d872..aaef35487e 100644 --- a/tests/test_edge_cases.py +++ b/tests/test_edge_cases.py @@ -859,7 +859,10 @@ class A(BaseModel): class B(A): integer = 2 - assert B.__annotations__['integer'] == int + if sys.version_info < (3, 10): + assert B.__annotations__['integer'] == int + else: + assert B.__annotations__ == {} assert B.__fields__['integer'].type_ == int class C(A): diff --git a/tests/test_main.py b/tests/test_main.py index d95ba2f8e7..3db4112ac1 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -803,10 +803,15 @@ class Config: with pytest.raises(ValidationError) as exc_info: Model(baz=FooEnum.bar) + if sys.version_info < (3, 10): + enum_repr = "" + else: + enum_repr = 'FooEnum.foo' + assert exc_info.value.errors() == [ { 'loc': ('baz',), - 'msg': "unexpected value; permitted: ", + 'msg': f'unexpected value; permitted: {enum_repr}', 'type': 'value_error.const', 'ctx': {'given': FooEnum.bar, 'permitted': (FooEnum.foo,)}, }, @@ -2026,3 +2031,21 @@ class Model(Base, some_config='new_value'): a: int assert Model.__config__.some_config == 'new_value' + + +@pytest.mark.skipif(sys.version_info < (3, 10), reason='need 3.10 version') +def test_new_union_origin(): + """On 3.10+, origin of `int | str` is `types.Union`, not `typing.Union`""" + + class Model(BaseModel): + x: int | str + + assert Model(x=3).x == 3 + assert Model(x='3').x == 3 + assert Model(x='pika').x == 'pika' + assert Model.schema() == { + 'title': 'Model', + 'type': 'object', + 'properties': {'x': {'title': 'X', 'anyOf': [{'type': 'integer'}, {'type': 'string'}]}}, + 'required': ['x'], + } diff --git a/tests/test_types.py b/tests/test_types.py index d40f8859a0..52a3998d7f 100644 --- a/tests/test_types.py +++ b/tests/test_types.py @@ -835,7 +835,10 @@ def test_enum_successful(): m = CookingModel(tool=2) assert m.fruit == FruitEnum.pear assert m.tool == ToolEnum.wrench - assert repr(m.tool) == '' + if sys.version_info < (3, 10): + assert repr(m.tool) == '' + else: + assert repr(m.tool) == 'ToolEnum.wrench' def test_enum_fails(): @@ -855,7 +858,10 @@ def test_enum_fails(): def test_int_enum_successful_for_str_int(): m = CookingModel(tool='2') assert m.tool == ToolEnum.wrench - assert repr(m.tool) == '' + if sys.version_info < (3, 10): + assert repr(m.tool) == '' + else: + assert repr(m.tool) == 'ToolEnum.wrench' def test_enum_type(): diff --git a/tests/test_utils.py b/tests/test_utils.py index bed8d7a940..5827735661 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -5,10 +5,10 @@ import string import sys from copy import copy, deepcopy -from distutils.version import StrictVersion from typing import Callable, Dict, List, NewType, Tuple, TypeVar, Union import pytest +from pkg_resources import safe_version from typing_extensions import Annotated, Literal from pydantic import VERSION, BaseModel, ConstrainedList, conlist @@ -377,8 +377,8 @@ def test_version_info(): assert s.count('\n') == 5 -def test_version_strict(): - assert str(StrictVersion(VERSION)) == VERSION +def test_standard_version(): + assert safe_version(VERSION) == VERSION def test_class_attribute():