instance_id
stringlengths
10
57
patch
stringlengths
261
37.7k
repo
stringlengths
7
53
base_commit
stringlengths
40
40
hints_text
stringclasses
301 values
test_patch
stringlengths
212
2.22M
problem_statement
stringlengths
23
37.7k
version
stringclasses
1 value
environment_setup_commit
stringlengths
40
40
FAIL_TO_PASS
listlengths
1
4.94k
PASS_TO_PASS
listlengths
0
7.82k
meta
dict
created_at
stringlengths
25
25
license
stringclasses
8 values
__index_level_0__
int64
0
6.41k
pydantic__pydantic-3182
diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -656,10 +656,10 @@ def validate(cls: Type['Model'], value: Any) -> 'Model': value = cls._enforce_dict_if_root(value) - if cls.__config__.orm_mode: - return cls.from_orm(value) - elif isinstance(value, dict): + if isinstance(value, dict): return cls(**value) + elif cls.__config__.orm_mode: + return cls.from_orm(value) else: try: value_as_dict = dict(value) @@ -669,6 +669,8 @@ def validate(cls: Type['Model'], value: Any) -> 'Model': @classmethod def _decompose_class(cls: Type['Model'], obj: Any) -> GetterDict: + if isinstance(obj, GetterDict): + return obj return cls.__config__.getter_dict(obj) @classmethod
pydantic/pydantic
45db4ad3aa558879824a91dd3b011d0449eb2977
Thanks for reporting! I'm so glad to have people messing around with `master`! It's always a great way to catch things beforehand 😄
diff --git a/tests/test_orm_mode.py b/tests/test_orm_mode.py --- a/tests/test_orm_mode.py +++ b/tests/test_orm_mode.py @@ -1,3 +1,4 @@ +from types import SimpleNamespace from typing import Any, Dict, List import pytest @@ -305,15 +306,14 @@ class Config: def test_recursive_parsing(): - from types import SimpleNamespace - class Getter(GetterDict): # try to read the modified property name # either as an attribute or as a key def get(self, key, default): key = key + key try: - return self._obj[key] + v = self._obj[key] + return Getter(v) if isinstance(v, dict) else v except TypeError: return getattr(self._obj, key, default) except KeyError: @@ -337,3 +337,24 @@ class ModelB(Model): # test recursive parsing with dict keys obj = dict(bb=dict(aa=1)) assert ModelB.from_orm(obj) == ModelB(b=ModelA(a=1)) + + +def test_nested_orm(): + class User(BaseModel): + first_name: str + last_name: str + + class Config: + orm_mode = True + + class State(BaseModel): + user: User + + class Config: + orm_mode = True + + # Pass an "orm instance" + State.from_orm(SimpleNamespace(user=SimpleNamespace(first_name='John', last_name='Appleseed'))) + + # Pass dictionary data directly + State(**{'user': {'first_name': 'John', 'last_name': 'Appleseed'}})
Nested ORM-mode models can no longer be initialized from nested dictionaries ### Checks * [x] I added a descriptive title to this issue * [x] I have searched (google, github) for similar issues and couldn't find anything * [x] I have read and followed [the docs](https://pydantic-docs.helpmanual.io/) and still think this is a bug # Bug I mentioned this as a comment on https://github.com/samuelcolvin/pydantic/pull/2718 but since it's already merged I figured I should open an issue. #2718 actually prevents models (that are ORM-enabled) from being initialized the normal way from dictionaries. Prior to that change, the following code worked: ```python from types import SimpleNamespace from pydantic import BaseModel class User(BaseModel): first_name: str last_name: str class Config: orm_mode = True class State(BaseModel): user: User # Pass an "orm instance" state = State.from_orm(SimpleNamespace(user=SimpleNamespace(first_name='John', last_name='Appleseed'))) # Pass dictionary data directly state = State(**{'user': {'first_name': 'John', 'last_name': 'Appleseed'}}) ``` After that change, the final line throws a validation error: ``` Traceback (most recent call last): File "/Users/luke/Developer/Clients/doctorschoice/flow/orm_issue.py", line 26, in <module> state = State(**{'user': {'first_name': 'John', 'last_name': 'Appleseed'}}) File "/Users/luke/.pyenv/versions/flow/lib/python3.9/site-packages/pydantic/main.py", line 330, in __init__ raise validation_error pydantic.error_wrappers.ValidationError: 2 validation errors for State user -> first_name field required (type=value_error.missing) user -> last_name field required (type=value_error.missing) ``` This is actually a bit of an issue given the way FastAPI handles response models. During the processing of a request, it serializes the data, and then passes it through a response model (if one was provided) to make sure the response matches the desired output schema. If you're using an ORM-mode model for convenience (like one generated from Tortoise-ORM's `pydantic_model_creator`), it now crashes with a validation error.
0.0
45db4ad3aa558879824a91dd3b011d0449eb2977
[ "tests/test_orm_mode.py::test_recursive_parsing", "tests/test_orm_mode.py::test_nested_orm" ]
[ "tests/test_orm_mode.py::test_getdict", "tests/test_orm_mode.py::test_orm_mode_root", "tests/test_orm_mode.py::test_orm_mode", "tests/test_orm_mode.py::test_not_orm_mode", "tests/test_orm_mode.py::test_object_with_getattr", "tests/test_orm_mode.py::test_properties", "tests/test_orm_mode.py::test_extra_allow", "tests/test_orm_mode.py::test_extra_forbid", "tests/test_orm_mode.py::test_root_validator", "tests/test_orm_mode.py::test_custom_getter_dict", "tests/test_orm_mode.py::test_custom_getter_dict_derived_model_class" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2021-09-06 20:50:05+00:00
mit
4,835
pydantic__pydantic-3194
diff --git a/pydantic/env_settings.py b/pydantic/env_settings.py --- a/pydantic/env_settings.py +++ b/pydantic/env_settings.py @@ -218,7 +218,14 @@ def __call__(self, settings: BaseSettings) -> Dict[str, Any]: for env_name in field.field_info.extra['env_names']: path = secrets_path / env_name if path.is_file(): - secrets[field.alias] = path.read_text().strip() + secret_value = path.read_text().strip() + if field.is_complex(): + try: + secret_value = settings.__config__.json_loads(secret_value) + except ValueError as e: + raise SettingsError(f'error parsing JSON for "{env_name}"') from e + + secrets[field.alias] = secret_value elif path.exists(): warnings.warn( f'attempted to load secret file "{path}" but found a {path_type(path)} instead.',
pydantic/pydantic
45db4ad3aa558879824a91dd3b011d0449eb2977
Hi @nat212 Your minimal example is not complete. Can you add what is actually run? (I'm surprised your `CloudConfig` is not a `BaseSettings`) Sure, I've updated it to include a little more detail. The example in the [Settings management docs](https://pydantic-docs.helpmanual.io/usage/settings/) use a `BaseModel` as the submodel, so that is why it is not a `BaseSettings`. Would it be better to make it a `BaseSettings`? If you look at the example, you can see that the `BaseModel` doesn't contain any secret and it's explain in the comment that you need to stringify a dict to override it. If you want to write only your `client_secret` into `/run/secrets/client_secret`, `CloudConfig` needs to be an `BaseSettings` and have the right `Config` declared Yes, the issue is that when using a JSON string as an environment variable, it sets the `cloud_config` model successfully. So the environment variable should get detected by the `Settings` model, and parsed as a JSON string, and used to set the `cloud_config` model. However, if I have a secret called `cloud_config` with the same JSON string, the secret just gets read as plain text, and the `Settings` model complains that it has not received a dict
diff --git a/tests/test_settings.py b/tests/test_settings.py --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -830,6 +830,33 @@ class Config: assert Settings().dict() == {'foo': 'http://www.example.com', 'bar': SecretStr('snap')} +def test_secrets_path_json(tmp_path): + p = tmp_path / 'foo' + p.write_text('{"a": "b"}') + + class Settings(BaseSettings): + foo: Dict[str, str] + + class Config: + secrets_dir = tmp_path + + assert Settings().dict() == {'foo': {'a': 'b'}} + + +def test_secrets_path_invalid_json(tmp_path): + p = tmp_path / 'foo' + p.write_text('{"a": "b"') + + class Settings(BaseSettings): + foo: Dict[str, str] + + class Config: + secrets_dir = tmp_path + + with pytest.raises(SettingsError, match='error parsing JSON for "foo"'): + Settings() + + def test_secrets_missing(tmp_path): class Settings(BaseSettings): foo: str
Cannot load JSON from secret files ### Checks * [x] I added a descriptive title to this issue * [x] I have searched (google, github) for similar issues and couldn't find anything * [x] I have read and followed [the docs](https://pydantic-docs.helpmanual.io/) and still think this is a bug <!-- Sorry to sound so draconian, but every second saved replying to issues is time spend improving pydantic :-) --> # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.8.2 pydantic compiled: True install path: /home/natasha/.local/share/virtualenvs/draperweb3-7iyfNlF4/lib/python3.8/site-packages/pydantic python version: 3.8.6 (default, May 27 2021, 13:28:02) [GCC 10.2.0] platform: Linux-5.11.0-7614-generic-x86_64-with-glibc2.32 optional deps. installed: ['dotenv', 'email-validator', 'typing-extensions'] ``` <!-- or if you're using pydantic prior to v1.3, manually include: OS, python version and pydantic version --> <!-- Please read the [docs](https://pydantic-docs.helpmanual.io/) and search through issues to confirm your bug hasn't already been reported. --> When loading settings values from a secrets file, values encoded in JSON do not get correctly parsed, leading to a ValidationError. After looking through the code, I discovered that `SecretsSettingsSource` simply reads the secret value as text instead of checking if it is a complex type. I'm not sure if this is intended, or if it's a bug, but either way, I think it would be beneficial if it were possible to load JSON from a secret file. Example: ``` pydantic.error_wrappers.ValidationError: 1 validation error for Settings cloud_config value is not a valid dict (type=type_error.dict) ``` <!-- Where possible please include a self-contained code snippet describing your bug: --> Minimal example ```py from pydantic import BaseSettings, BaseModel class CloudConfig(BaseModel): client_id: str client_secret: str token_url: str auth_url: str api_url: str class Settings(BaseSettings): cloud_config: CloudConfig class Config: case_sensitive = False secrets_dir = "/run/secrets" settings = Settings() print(settings.cloud_config.client_id) ``` This works if I have an environment variable `CLOUD_CONFIG='{"client_id": "...", ...}'`, but not if I have the same string in a secrets file
0.0
45db4ad3aa558879824a91dd3b011d0449eb2977
[ "tests/test_settings.py::test_secrets_path_json", "tests/test_settings.py::test_secrets_path_invalid_json" ]
[ "tests/test_settings.py::test_sub_env", "tests/test_settings.py::test_sub_env_override", "tests/test_settings.py::test_sub_env_missing", "tests/test_settings.py::test_other_setting", "tests/test_settings.py::test_with_prefix", "tests/test_settings.py::test_nested_env_with_basemodel", "tests/test_settings.py::test_nested_env_with_dict", "tests/test_settings.py::test_list", "tests/test_settings.py::test_set_dict_model", "tests/test_settings.py::test_invalid_json", "tests/test_settings.py::test_required_sub_model", "tests/test_settings.py::test_non_class", "tests/test_settings.py::test_env_str", "tests/test_settings.py::test_env_list", "tests/test_settings.py::test_env_list_field", "tests/test_settings.py::test_env_list_last", "tests/test_settings.py::test_env_inheritance", "tests/test_settings.py::test_env_inheritance_field", "tests/test_settings.py::test_env_prefix_inheritance_config", "tests/test_settings.py::test_env_inheritance_config", "tests/test_settings.py::test_env_invalid", "tests/test_settings.py::test_env_field", "tests/test_settings.py::test_aliases_warning", "tests/test_settings.py::test_aliases_no_warning", "tests/test_settings.py::test_case_sensitive", "tests/test_settings.py::test_nested_dataclass", "tests/test_settings.py::test_env_takes_precedence", "tests/test_settings.py::test_config_file_settings_nornir", "tests/test_settings.py::test_env_union_with_complex_subfields_parses_json", "tests/test_settings.py::test_env_union_with_complex_subfields_parses_plain_if_json_fails", "tests/test_settings.py::test_env_union_without_complex_subfields_does_not_parse_json", "tests/test_settings.py::test_env_file_config", "tests/test_settings.py::test_env_file_config_case_sensitive", "tests/test_settings.py::test_env_file_export", "tests/test_settings.py::test_env_file_config_custom_encoding", "tests/test_settings.py::test_env_file_home_directory", "tests/test_settings.py::test_env_file_none", "tests/test_settings.py::test_env_file_override_file", "tests/test_settings.py::test_env_file_override_none", "tests/test_settings.py::test_env_file_not_a_file", "tests/test_settings.py::test_read_env_file_cast_sensitive", "tests/test_settings.py::test_read_env_file_syntax_wrong", "tests/test_settings.py::test_env_file_example", "tests/test_settings.py::test_env_file_custom_encoding", "tests/test_settings.py::test_alias_set", "tests/test_settings.py::test_prefix_on_parent", "tests/test_settings.py::test_frozenset", "tests/test_settings.py::test_secrets_path", "tests/test_settings.py::test_secrets_path_url", "tests/test_settings.py::test_secrets_missing", "tests/test_settings.py::test_secrets_invalid_secrets_dir", "tests/test_settings.py::test_secrets_missing_location", "tests/test_settings.py::test_secrets_file_is_a_directory", "tests/test_settings.py::test_secrets_dotenv_precedence", "tests/test_settings.py::test_external_settings_sources_precedence", "tests/test_settings.py::test_external_settings_sources_filter_env_vars", "tests/test_settings.py::test_customise_sources_empty", "tests/test_settings.py::test_builtins_settings_source_repr" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2021-09-08 02:35:14+00:00
mit
4,836
pydantic__pydantic-3197
diff --git a/pydantic/schema.py b/pydantic/schema.py --- a/pydantic/schema.py +++ b/pydantic/schema.py @@ -909,7 +909,9 @@ def multitypes_literal_field_for_schema(values: Tuple[Any, ...], field: ModelFie def encode_default(dft: Any) -> Any: - if isinstance(dft, (int, float, str)): + if isinstance(dft, Enum): + return dft.value + elif isinstance(dft, (int, float, str)): return dft elif sequence_like(dft): t = dft.__class__
pydantic/pydantic
45db4ad3aa558879824a91dd3b011d0449eb2977
diff --git a/tests/test_schema.py b/tests/test_schema.py --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -1404,6 +1404,26 @@ class UserModel(BaseModel): } +def test_enum_str_default(): + class MyEnum(str, Enum): + FOO = 'foo' + + class UserModel(BaseModel): + friends: MyEnum = MyEnum.FOO + + assert UserModel.schema()['properties']['friends']['default'] is MyEnum.FOO.value + + +def test_enum_int_default(): + class MyEnum(IntEnum): + FOO = 1 + + class UserModel(BaseModel): + friends: MyEnum = MyEnum.FOO + + assert UserModel.schema()['properties']['friends']['default'] is MyEnum.FOO.value + + def test_dict_default(): class UserModel(BaseModel): friends: Dict[str, float] = {'a': 1.1, 'b': 2.2}
<Model>.schema() method handles Enum and IntEnum default field resolution differently ### Checks * [x] I added a descriptive title to this issue * [x] I have searched (google, github) for similar issues and couldn't find anything * [x] I have read and followed [the docs](https://pydantic-docs.helpmanual.io/) and still think this is a bug <!-- Sorry to sound so draconian, but every second saved replying to issues is time spend improving pydantic :-) --> # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.8.2 pydantic compiled: True install path: C:\Users\jmartins\.virtualenvs\pydantic_bug_report-NJE4-7fw\Lib\site-packages\pydantic python version: 3.9.6 (tags/v3.9.6:db3ff76, Jun 28 2021, 15:26:21) [MSC v.1929 64 bit (AMD64)] platform: Windows-10-10.0.19042-SP0 optional deps. installed: ['typing-extensions'] ``` <!-- or if you're using pydantic prior to v1.3, manually include: OS, python version and pydantic version --> <!-- Please read the [docs](https://pydantic-docs.helpmanual.io/) and search through issues to confirm your bug hasn't already been reported. --> <!-- Where possible please include a self-contained code snippet describing your bug: --> Generating a schema with the .schema() method works as expected when resolving default values of Enum type, while it does not resolve default values of IntEnum type the same way. A minimum example follows: ```py # std lib imports from enum import Enum, IntEnum # external imports from pydantic import BaseModel class ExampleEnum(Enum): A = "a" class ExampleIntEnum(IntEnum): A = 1 class ExampleModel(BaseModel): example_enum: ExampleEnum = ExampleEnum.A example_int_enum: ExampleIntEnum = ExampleIntEnum.A generated_schema_properties = ExampleModel.schema().get("properties", {}) example_enum_generated_default = generated_schema_properties.get("example_enum", {}).get("default", None) example_int_enum_generated_default = generated_schema_properties.get("example_int_enum", {}).get("default", None) print(example_enum_generated_default is ExampleEnum.A.value) # -> True print(example_int_enum_generated_default is ExampleIntEnum.A.value) # -> False ``` I've tracked the issue down to the `encode_default` function in `schema.py`: ```py def encode_default(dft: Any) -> Any: if isinstance(dft, (int, float, str)): return dft elif sequence_like(dft): t = dft.__class__ return t(encode_default(v) for v in dft) elif isinstance(dft, dict): return {encode_default(k): encode_default(v) for k, v in dft.items()} elif dft is None: return None else: return pydantic_encoder(dft) ``` When resolving defaults for Enum the else clause is correctly used, but since `isinstance(ExampleIntEnum.A, int)` is truthy it returns ExampleIntEnum.A when using an IntEnum. I would suggest changing the first if to a stricter direct 'primitive' type check like `if type(dft) in (int, float, str):`. I can do this myself and open a PR if there is interest and no opposition to a stricter type check.
0.0
45db4ad3aa558879824a91dd3b011d0449eb2977
[ "tests/test_schema.py::test_enum_str_default", "tests/test_schema.py::test_enum_int_default" ]
[ "tests/test_schema.py::test_key", "tests/test_schema.py::test_by_alias", "tests/test_schema.py::test_ref_template", "tests/test_schema.py::test_by_alias_generator", "tests/test_schema.py::test_sub_model", "tests/test_schema.py::test_schema_class", "tests/test_schema.py::test_schema_repr", "tests/test_schema.py::test_schema_class_by_alias", "tests/test_schema.py::test_choices", "tests/test_schema.py::test_enum_modify_schema", "tests/test_schema.py::test_enum_schema_custom_field", "tests/test_schema.py::test_enum_and_model_have_same_behaviour", "tests/test_schema.py::test_list_enum_schema_extras", "tests/test_schema.py::test_json_schema", "tests/test_schema.py::test_list_sub_model", "tests/test_schema.py::test_optional", "tests/test_schema.py::test_any", "tests/test_schema.py::test_set", "tests/test_schema.py::test_const_str", "tests/test_schema.py::test_const_false", "tests/test_schema.py::test_tuple[tuple-expected_schema0]", "tests/test_schema.py::test_tuple[field_type1-expected_schema1]", "tests/test_schema.py::test_tuple[field_type2-expected_schema2]", "tests/test_schema.py::test_deque", "tests/test_schema.py::test_bool", "tests/test_schema.py::test_strict_bool", "tests/test_schema.py::test_dict", "tests/test_schema.py::test_list", "tests/test_schema.py::test_list_union_dict[field_type0-expected_schema0]", "tests/test_schema.py::test_list_union_dict[field_type1-expected_schema1]", "tests/test_schema.py::test_list_union_dict[field_type2-expected_schema2]", "tests/test_schema.py::test_list_union_dict[field_type3-expected_schema3]", "tests/test_schema.py::test_list_union_dict[field_type4-expected_schema4]", "tests/test_schema.py::test_date_types[datetime-expected_schema0]", "tests/test_schema.py::test_date_types[date-expected_schema1]", "tests/test_schema.py::test_date_types[time-expected_schema2]", "tests/test_schema.py::test_date_types[timedelta-expected_schema3]", "tests/test_schema.py::test_str_basic_types[field_type0-expected_schema0]", "tests/test_schema.py::test_str_basic_types[field_type1-expected_schema1]", "tests/test_schema.py::test_str_basic_types[field_type2-expected_schema2]", "tests/test_schema.py::test_str_basic_types[field_type3-expected_schema3]", "tests/test_schema.py::test_str_constrained_types[StrictStr-expected_schema0]", "tests/test_schema.py::test_str_constrained_types[ConstrainedStr-expected_schema1]", "tests/test_schema.py::test_str_constrained_types[ConstrainedStrValue-expected_schema2]", "tests/test_schema.py::test_special_str_types[AnyUrl-expected_schema0]", "tests/test_schema.py::test_special_str_types[UrlValue-expected_schema1]", "tests/test_schema.py::test_email_str_types[EmailStr-email]", "tests/test_schema.py::test_email_str_types[NameEmail-name-email]", "tests/test_schema.py::test_secret_types[SecretBytes-string]", "tests/test_schema.py::test_secret_types[SecretStr-string]", "tests/test_schema.py::test_special_int_types[ConstrainedInt-expected_schema0]", "tests/test_schema.py::test_special_int_types[ConstrainedIntValue-expected_schema1]", "tests/test_schema.py::test_special_int_types[ConstrainedIntValue-expected_schema2]", "tests/test_schema.py::test_special_int_types[ConstrainedIntValue-expected_schema3]", "tests/test_schema.py::test_special_int_types[PositiveInt-expected_schema4]", "tests/test_schema.py::test_special_int_types[NegativeInt-expected_schema5]", "tests/test_schema.py::test_special_int_types[NonNegativeInt-expected_schema6]", "tests/test_schema.py::test_special_int_types[NonPositiveInt-expected_schema7]", "tests/test_schema.py::test_special_float_types[ConstrainedFloat-expected_schema0]", "tests/test_schema.py::test_special_float_types[ConstrainedFloatValue-expected_schema1]", "tests/test_schema.py::test_special_float_types[ConstrainedFloatValue-expected_schema2]", "tests/test_schema.py::test_special_float_types[ConstrainedFloatValue-expected_schema3]", "tests/test_schema.py::test_special_float_types[PositiveFloat-expected_schema4]", "tests/test_schema.py::test_special_float_types[NegativeFloat-expected_schema5]", "tests/test_schema.py::test_special_float_types[NonNegativeFloat-expected_schema6]", "tests/test_schema.py::test_special_float_types[NonPositiveFloat-expected_schema7]", "tests/test_schema.py::test_special_float_types[ConstrainedDecimal-expected_schema8]", "tests/test_schema.py::test_special_float_types[ConstrainedDecimalValue-expected_schema9]", "tests/test_schema.py::test_special_float_types[ConstrainedDecimalValue-expected_schema10]", "tests/test_schema.py::test_special_float_types[ConstrainedDecimalValue-expected_schema11]", "tests/test_schema.py::test_uuid_types[UUID-uuid]", "tests/test_schema.py::test_uuid_types[UUID1-uuid1]", "tests/test_schema.py::test_uuid_types[UUID3-uuid3]", "tests/test_schema.py::test_uuid_types[UUID4-uuid4]", "tests/test_schema.py::test_uuid_types[UUID5-uuid5]", "tests/test_schema.py::test_path_types[FilePath-file-path]", "tests/test_schema.py::test_path_types[DirectoryPath-directory-path]", "tests/test_schema.py::test_path_types[Path-path]", "tests/test_schema.py::test_json_type", "tests/test_schema.py::test_ipv4address_type", "tests/test_schema.py::test_ipv6address_type", "tests/test_schema.py::test_ipvanyaddress_type", "tests/test_schema.py::test_ipv4interface_type", "tests/test_schema.py::test_ipv6interface_type", "tests/test_schema.py::test_ipvanyinterface_type", "tests/test_schema.py::test_ipv4network_type", "tests/test_schema.py::test_ipv6network_type", "tests/test_schema.py::test_ipvanynetwork_type", "tests/test_schema.py::test_callable_type[type_0-default_value0]", "tests/test_schema.py::test_callable_type[type_1-<lambda>]", "tests/test_schema.py::test_callable_type[type_2-default_value2]", "tests/test_schema.py::test_callable_type[type_3-<lambda>]", "tests/test_schema.py::test_error_non_supported_types", "tests/test_schema.py::test_flat_models_unique_models", "tests/test_schema.py::test_flat_models_with_submodels", "tests/test_schema.py::test_flat_models_with_submodels_from_sequence", "tests/test_schema.py::test_model_name_maps", "tests/test_schema.py::test_schema_overrides", "tests/test_schema.py::test_schema_overrides_w_union", "tests/test_schema.py::test_schema_from_models", "tests/test_schema.py::test_schema_with_refs[#/components/schemas/-None]", "tests/test_schema.py::test_schema_with_refs[None-#/components/schemas/{model}]", "tests/test_schema.py::test_schema_with_refs[#/components/schemas/-#/{model}/schemas/]", "tests/test_schema.py::test_schema_with_custom_ref_template", "tests/test_schema.py::test_schema_ref_template_key_error", "tests/test_schema.py::test_schema_no_definitions", "tests/test_schema.py::test_list_default", "tests/test_schema.py::test_dict_default", "tests/test_schema.py::test_constraints_schema[kwargs0-str-expected_extra0]", "tests/test_schema.py::test_constraints_schema[kwargs1-ConstrainedStrValue-expected_extra1]", "tests/test_schema.py::test_constraints_schema[kwargs2-str-expected_extra2]", "tests/test_schema.py::test_constraints_schema[kwargs3-bytes-expected_extra3]", "tests/test_schema.py::test_constraints_schema[kwargs4-str-expected_extra4]", "tests/test_schema.py::test_constraints_schema[kwargs5-int-expected_extra5]", "tests/test_schema.py::test_constraints_schema[kwargs6-int-expected_extra6]", "tests/test_schema.py::test_constraints_schema[kwargs7-int-expected_extra7]", "tests/test_schema.py::test_constraints_schema[kwargs8-int-expected_extra8]", "tests/test_schema.py::test_constraints_schema[kwargs9-int-expected_extra9]", "tests/test_schema.py::test_constraints_schema[kwargs10-float-expected_extra10]", "tests/test_schema.py::test_constraints_schema[kwargs11-float-expected_extra11]", "tests/test_schema.py::test_constraints_schema[kwargs12-float-expected_extra12]", "tests/test_schema.py::test_constraints_schema[kwargs13-float-expected_extra13]", "tests/test_schema.py::test_constraints_schema[kwargs14-float-expected_extra14]", "tests/test_schema.py::test_constraints_schema[kwargs15-float-expected_extra15]", "tests/test_schema.py::test_constraints_schema[kwargs16-float-expected_extra16]", "tests/test_schema.py::test_constraints_schema[kwargs17-float-expected_extra17]", "tests/test_schema.py::test_constraints_schema[kwargs18-float-expected_extra18]", "tests/test_schema.py::test_constraints_schema[kwargs19-Decimal-expected_extra19]", "tests/test_schema.py::test_constraints_schema[kwargs20-Decimal-expected_extra20]", "tests/test_schema.py::test_constraints_schema[kwargs21-Decimal-expected_extra21]", "tests/test_schema.py::test_constraints_schema[kwargs22-Decimal-expected_extra22]", "tests/test_schema.py::test_constraints_schema[kwargs23-Decimal-expected_extra23]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs0-int]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs1-float]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs2-Decimal]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs3-bool]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs4-int]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs5-str]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs6-bytes]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs7-str]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs8-bool]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs9-type_9]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs10-type_10]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs11-ConstrainedListValue]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs12-ConstrainedSetValue]", "tests/test_schema.py::test_constraints_schema_validation[kwargs0-str-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs1-str-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs2-bytes-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs3-str-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs4-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs5-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs6-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs7-int-2]", "tests/test_schema.py::test_constraints_schema_validation[kwargs8-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs9-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs10-int-5]", "tests/test_schema.py::test_constraints_schema_validation[kwargs11-float-3.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs12-float-2.1]", "tests/test_schema.py::test_constraints_schema_validation[kwargs13-float-3.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs14-float-4.9]", "tests/test_schema.py::test_constraints_schema_validation[kwargs15-float-3.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs16-float-2.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs17-float-3.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs18-float-5.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs19-float-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs20-float-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs21-Decimal-value21]", "tests/test_schema.py::test_constraints_schema_validation[kwargs22-Decimal-value22]", "tests/test_schema.py::test_constraints_schema_validation[kwargs23-Decimal-value23]", "tests/test_schema.py::test_constraints_schema_validation[kwargs24-Decimal-value24]", "tests/test_schema.py::test_constraints_schema_validation[kwargs25-Decimal-value25]", "tests/test_schema.py::test_constraints_schema_validation[kwargs26-Decimal-value26]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs0-str-foobar]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs1-str-f]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs2-str-bar]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs3-int-2]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs4-int-5]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs5-int-1]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs6-int-6]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs7-float-2.0]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs8-float-5.0]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs9-float-1.9]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs10-float-5.1]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs11-Decimal-value11]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs12-Decimal-value12]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs13-Decimal-value13]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs14-Decimal-value14]", "tests/test_schema.py::test_schema_kwargs", "tests/test_schema.py::test_schema_dict_constr", "tests/test_schema.py::test_bytes_constrained_types[ConstrainedBytes-expected_schema0]", "tests/test_schema.py::test_bytes_constrained_types[ConstrainedBytesValue-expected_schema1]", "tests/test_schema.py::test_optional_dict", "tests/test_schema.py::test_optional_validator", "tests/test_schema.py::test_field_with_validator", "tests/test_schema.py::test_unparameterized_schema_generation", "tests/test_schema.py::test_known_model_optimization", "tests/test_schema.py::test_root", "tests/test_schema.py::test_root_list", "tests/test_schema.py::test_root_nested_model", "tests/test_schema.py::test_new_type_schema", "tests/test_schema.py::test_literal_schema", "tests/test_schema.py::test_literal_enum", "tests/test_schema.py::test_color_type", "tests/test_schema.py::test_model_with_schema_extra", "tests/test_schema.py::test_model_with_schema_extra_callable", "tests/test_schema.py::test_model_with_schema_extra_callable_no_model_class", "tests/test_schema.py::test_model_with_schema_extra_callable_classmethod", "tests/test_schema.py::test_model_with_schema_extra_callable_instance_method", "tests/test_schema.py::test_model_with_extra_forbidden", "tests/test_schema.py::test_enforced_constraints[int-kwargs0-field_schema0]", "tests/test_schema.py::test_enforced_constraints[annotation1-kwargs1-field_schema1]", "tests/test_schema.py::test_enforced_constraints[annotation2-kwargs2-field_schema2]", "tests/test_schema.py::test_enforced_constraints[annotation3-kwargs3-field_schema3]", "tests/test_schema.py::test_enforced_constraints[annotation4-kwargs4-field_schema4]", "tests/test_schema.py::test_enforced_constraints[annotation5-kwargs5-field_schema5]", "tests/test_schema.py::test_enforced_constraints[annotation6-kwargs6-field_schema6]", "tests/test_schema.py::test_enforced_constraints[annotation7-kwargs7-field_schema7]", "tests/test_schema.py::test_real_vs_phony_constraints", "tests/test_schema.py::test_subfield_field_info", "tests/test_schema.py::test_dataclass", "tests/test_schema.py::test_schema_attributes", "tests/test_schema.py::test_model_process_schema_enum", "tests/test_schema.py::test_path_modify_schema", "tests/test_schema.py::test_frozen_set", "tests/test_schema.py::test_iterable", "tests/test_schema.py::test_new_type", "tests/test_schema.py::test_multiple_models_with_same_name", "tests/test_schema.py::test_multiple_enums_with_same_name", "tests/test_schema.py::test_schema_for_generic_field", "tests/test_schema.py::test_namedtuple_default", "tests/test_schema.py::test_advanced_generic_schema", "tests/test_schema.py::test_nested_generic", "tests/test_schema.py::test_nested_generic_model", "tests/test_schema.py::test_complex_nested_generic" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2021-09-08 17:12:27+00:00
mit
4,837
pydantic__pydantic-3201
diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -580,6 +580,24 @@ def construct(cls: Type['Model'], _fields_set: Optional['SetStr'] = None, **valu m._init_private_attributes() return m + def _copy_and_set_values(self: 'Model', values: 'DictStrAny', fields_set: 'SetStr', *, deep: bool) -> 'Model': + if deep: + # chances of having empty dict here are quite low for using smart_deepcopy + values = deepcopy(values) + + cls = self.__class__ + m = cls.__new__(cls) + object_setattr(m, '__dict__', values) + object_setattr(m, '__fields_set__', fields_set) + for name in self.__private_attributes__: + value = getattr(self, name, Undefined) + if value is not Undefined: + if deep: + value = deepcopy(value) + object_setattr(m, name, value) + + return m + def copy( self: 'Model', *, @@ -599,32 +617,18 @@ def copy( :return: new model instance """ - v = dict( + values = dict( self._iter(to_dict=False, by_alias=False, include=include, exclude=exclude, exclude_unset=False), **(update or {}), ) - if deep: - # chances of having empty dict here are quite low for using smart_deepcopy - v = deepcopy(v) - - cls = self.__class__ - m = cls.__new__(cls) - object_setattr(m, '__dict__', v) # new `__fields_set__` can have unset optional fields with a set value in `update` kwarg if update: fields_set = self.__fields_set__ | update.keys() else: fields_set = set(self.__fields_set__) - object_setattr(m, '__fields_set__', fields_set) - for name in self.__private_attributes__: - value = getattr(self, name, Undefined) - if value is not Undefined: - if deep: - value = deepcopy(value) - object_setattr(m, name, value) - return m + return self._copy_and_set_values(values, fields_set, deep=deep) @classmethod def schema(cls, by_alias: bool = True, ref_template: str = default_ref_template) -> 'DictStrAny': @@ -652,7 +656,10 @@ def __get_validators__(cls) -> 'CallableGenerator': @classmethod def validate(cls: Type['Model'], value: Any) -> 'Model': if isinstance(value, cls): - return value.copy() if cls.__config__.copy_on_model_validation else value + if cls.__config__.copy_on_model_validation: + return value._copy_and_set_values(value.__dict__, value.__fields_set__, deep=False) + else: + return value value = cls._enforce_dict_if_root(value)
pydantic/pydantic
c256dccbb383a7fd462f62fcb5d55558eb3cb108
diff --git a/tests/test_main.py b/tests/test_main.py --- a/tests/test_main.py +++ b/tests/test_main.py @@ -16,7 +16,9 @@ Field, NoneBytes, NoneStr, + PrivateAttr, Required, + SecretStr, ValidationError, constr, root_validator, @@ -1504,6 +1506,45 @@ class Config: assert Model.__fields__['b'].field_info.exclude == {'foo': ..., 'bar': ...} +def test_model_exclude_copy_on_model_validation(): + """When `Config.copy_on_model_validation` is set, it should keep private attributes and excluded fields""" + + class User(BaseModel): + _priv: int = PrivateAttr() + id: int + username: str + password: SecretStr = Field(exclude=True) + hobbies: List[str] + + my_user = User(id=42, username='JohnDoe', password='hashedpassword', hobbies=['scuba diving']) + + my_user._priv = 13 + assert my_user.id == 42 + assert my_user.password.get_secret_value() == 'hashedpassword' + assert my_user.dict() == {'id': 42, 'username': 'JohnDoe', 'hobbies': ['scuba diving']} + + class Transaction(BaseModel): + id: str + user: User = Field(..., exclude={'username'}) + value: int + + class Config: + fields = {'value': {'exclude': True}} + + t = Transaction( + id='1234567890', + user=my_user, + value=9876543210, + ) + + assert t.user is not my_user + assert t.user.hobbies == ['scuba diving'] + assert t.user.hobbies is my_user.hobbies # `Config.copy_on_model_validation` only does a shallow copy + assert t.user._priv == 13 + assert t.user.password.get_secret_value() == 'hashedpassword' + assert t.dict() == {'id': '1234567890', 'user': {'id': 42, 'hobbies': ['scuba diving']}} + + @pytest.mark.parametrize( 'kinds', [
Field(..., exclude=True) are missing from nested BaseModel objects ### Checks * [X] I added a descriptive title to this issue * [X] I have searched (google, github) for similar issues and couldn't find anything * [X] I have read and followed [the docs](https://pydantic-docs.helpmanual.io/) and still think this is a bug <!-- Sorry to sound so draconian, but every second saved replying to issues is time spend improving pydantic :-) --> # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.8.2 pydantic compiled: False install path: /home/venv/lib/python3.7/site-packages/pydantic python version: 3.7.10 (default, May 4 2021, 13:51:36) [GCC 11.1.1 20210428 (Red Hat 11.1.1-1)] platform: Linux-4.4.0-19041-Microsoft-x86_64-with-fedora-34-Thirty_Four optional deps. installed: ['email-validator', 'typing-extensions'] ``` <!-- or if you're using pydantic prior to v1.3, manually include: OS, python version and pydantic version --> <!-- Please read the [docs](https://pydantic-docs.helpmanual.io/) and search through issues to confirm your bug hasn't already been reported. --> <!-- Where possible please include a self-contained code snippet describing your bug: --> ```py from pydantic import BaseModel, Field, SecretStr class User(BaseModel): id: int username: str password: SecretStr = Field(..., exclude=True) class Transaction(BaseModel): id: str user: User = Field(..., exclude={'username'}) value: int class Config: fields = {'value': {'exclude': True}} t = Transaction( id='1234567890', user=User( id=42, username='JohnDoe', password='hashedpassword' ), value=9876543210, ) print(t.user.password) print(t.dict()) ``` Hi, I'm currently interested by the exclude parameter (tested from commit 45db4ad3aa558879824a91dd3b011d0449eb2977). After BaseModel initialization, `excluded` fields are missing from nested objects. the BaseModel __init__ uses the `validate()` function that uses `copy()` ( and -> _iter) under the hood. https://github.com/samuelcolvin/pydantic/blob/45db4ad3aa558879824a91dd3b011d0449eb2977/pydantic/main.py#L652-L656 as a result, all excluded fields are missing after validation. I do not know if this behavior is intended. But as far as I can see the exclude should only affect exports function, right ? my issue looks in contradiction with this comment bellow. let me know if I misinterpreted the exclude purpose. https://github.com/samuelcolvin/pydantic/issues/830#issuecomment-842313022 thank you very much
0.0
c256dccbb383a7fd462f62fcb5d55558eb3cb108
[ "tests/test_main.py::test_model_exclude_copy_on_model_validation" ]
[ "tests/test_main.py::test_success", "tests/test_main.py::test_ultra_simple_missing", "tests/test_main.py::test_ultra_simple_failed", "tests/test_main.py::test_ultra_simple_repr", "tests/test_main.py::test_default_factory_field", "tests/test_main.py::test_default_factory_no_type_field", "tests/test_main.py::test_comparing", "tests/test_main.py::test_nullable_strings_success", "tests/test_main.py::test_nullable_strings_fails", "tests/test_main.py::test_recursion", "tests/test_main.py::test_recursion_fails", "tests/test_main.py::test_not_required", "tests/test_main.py::test_infer_type", "tests/test_main.py::test_allow_extra", "tests/test_main.py::test_forbidden_extra_success", "tests/test_main.py::test_forbidden_extra_fails", "tests/test_main.py::test_disallow_mutation", "tests/test_main.py::test_extra_allowed", "tests/test_main.py::test_extra_ignored", "tests/test_main.py::test_set_attr", "tests/test_main.py::test_set_attr_invalid", "tests/test_main.py::test_any", "tests/test_main.py::test_alias", "tests/test_main.py::test_population_by_field_name", "tests/test_main.py::test_field_order", "tests/test_main.py::test_required", "tests/test_main.py::test_mutability", "tests/test_main.py::test_immutability[False-False]", "tests/test_main.py::test_immutability[False-True]", "tests/test_main.py::test_immutability[True-True]", "tests/test_main.py::test_not_frozen_are_not_hashable", "tests/test_main.py::test_with_declared_hash", "tests/test_main.py::test_frozen_with_hashable_fields_are_hashable", "tests/test_main.py::test_frozen_with_unhashable_fields_are_not_hashable", "tests/test_main.py::test_hash_function_give_different_result_for_different_object", "tests/test_main.py::test_const_validates", "tests/test_main.py::test_const_uses_default", "tests/test_main.py::test_const_validates_after_type_validators", "tests/test_main.py::test_const_with_wrong_value", "tests/test_main.py::test_const_with_validator", "tests/test_main.py::test_const_list", "tests/test_main.py::test_const_list_with_wrong_value", "tests/test_main.py::test_const_validation_json_serializable", "tests/test_main.py::test_validating_assignment_pass", "tests/test_main.py::test_validating_assignment_fail", "tests/test_main.py::test_validating_assignment_pre_root_validator_fail", "tests/test_main.py::test_validating_assignment_post_root_validator_fail", "tests/test_main.py::test_root_validator_many_values_change", "tests/test_main.py::test_enum_values", "tests/test_main.py::test_literal_enum_values", "tests/test_main.py::test_enum_raw", "tests/test_main.py::test_set_tuple_values", "tests/test_main.py::test_default_copy", "tests/test_main.py::test_arbitrary_type_allowed_validation_success", "tests/test_main.py::test_arbitrary_type_allowed_validation_fails", "tests/test_main.py::test_arbitrary_types_not_allowed", "tests/test_main.py::test_type_type_validation_success", "tests/test_main.py::test_type_type_subclass_validation_success", "tests/test_main.py::test_type_type_validation_fails_for_instance", "tests/test_main.py::test_type_type_validation_fails_for_basic_type", "tests/test_main.py::test_bare_type_type_validation_success", "tests/test_main.py::test_bare_type_type_validation_fails", "tests/test_main.py::test_annotation_field_name_shadows_attribute", "tests/test_main.py::test_value_field_name_shadows_attribute", "tests/test_main.py::test_class_var", "tests/test_main.py::test_fields_set", "tests/test_main.py::test_exclude_unset_dict", "tests/test_main.py::test_exclude_unset_recursive", "tests/test_main.py::test_dict_exclude_unset_populated_by_alias", "tests/test_main.py::test_dict_exclude_unset_populated_by_alias_with_extra", "tests/test_main.py::test_exclude_defaults", "tests/test_main.py::test_dir_fields", "tests/test_main.py::test_dict_with_extra_keys", "tests/test_main.py::test_root", "tests/test_main.py::test_root_list", "tests/test_main.py::test_root_nested", "tests/test_main.py::test_encode_nested_root", "tests/test_main.py::test_root_failed", "tests/test_main.py::test_root_undefined_failed", "tests/test_main.py::test_parse_root_as_mapping", "tests/test_main.py::test_parse_obj_non_mapping_root", "tests/test_main.py::test_parse_obj_nested_root", "tests/test_main.py::test_untouched_types", "tests/test_main.py::test_custom_types_fail_without_keep_untouched", "tests/test_main.py::test_model_iteration", "tests/test_main.py::test_model_export_nested_list[excluding", "tests/test_main.py::test_model_export_nested_list[should", "tests/test_main.py::test_model_export_nested_list[using", "tests/test_main.py::test_model_export_dict_exclusion[excluding", "tests/test_main.py::test_model_export_dict_exclusion[using", "tests/test_main.py::test_model_export_dict_exclusion[exclude", "tests/test_main.py::test_model_exclude_config_field_merging", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[None-expected0-kinds0]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[None-expected0-kinds1]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[None-expected0-kinds2]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[None-expected0-kinds3]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[None-expected0-kinds4]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[None-expected0-kinds5]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[None-expected0-kinds6]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude1-expected1-kinds0]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude1-expected1-kinds1]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude1-expected1-kinds2]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude1-expected1-kinds3]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude1-expected1-kinds4]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude1-expected1-kinds5]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude1-expected1-kinds6]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude2-expected2-kinds0]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude2-expected2-kinds1]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude2-expected2-kinds2]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude2-expected2-kinds3]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude2-expected2-kinds4]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude2-expected2-kinds5]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude2-expected2-kinds6]", "tests/test_main.py::test_model_export_exclusion_inheritance", "tests/test_main.py::test_model_export_with_true_instead_of_ellipsis", "tests/test_main.py::test_model_export_inclusion", "tests/test_main.py::test_model_export_inclusion_inheritance", "tests/test_main.py::test_custom_init_subclass_params", "tests/test_main.py::test_update_forward_refs_does_not_modify_module_dict", "tests/test_main.py::test_two_defaults", "tests/test_main.py::test_default_factory", "tests/test_main.py::test_default_factory_called_once", "tests/test_main.py::test_default_factory_called_once_2", "tests/test_main.py::test_default_factory_validate_children", "tests/test_main.py::test_default_factory_parse", "tests/test_main.py::test_none_min_max_items", "tests/test_main.py::test_reuse_same_field", "tests/test_main.py::test_base_config_type_hinting", "tests/test_main.py::test_allow_mutation_field", "tests/test_main.py::test_repr_field", "tests/test_main.py::test_inherited_model_field_copy", "tests/test_main.py::test_inherited_model_field_untouched", "tests/test_main.py::test_mapping_retains_type_subclass", "tests/test_main.py::test_mapping_retains_type_defaultdict", "tests/test_main.py::test_mapping_retains_type_fallback_error", "tests/test_main.py::test_typing_coercion_dict", "tests/test_main.py::test_typing_coercion_defaultdict", "tests/test_main.py::test_typing_coercion_counter", "tests/test_main.py::test_typing_counter_value_validation", "tests/test_main.py::test_class_kwargs_config", "tests/test_main.py::test_class_kwargs_config_json_encoders", "tests/test_main.py::test_class_kwargs_config_and_attr_conflict", "tests/test_main.py::test_class_kwargs_custom_config" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_git_commit_hash" ], "has_test_patch": true, "is_lite": false }
2021-09-11 10:11:20+00:00
mit
4,838
pydantic__pydantic-3216
diff --git a/pydantic/class_validators.py b/pydantic/class_validators.py --- a/pydantic/class_validators.py +++ b/pydantic/class_validators.py @@ -75,6 +75,11 @@ def validator( "validators should be used with fields and keyword arguments, not bare. " # noqa: Q000 "E.g. usage should be `@validator('<field_name>', ...)`" ) + elif not all(isinstance(field, str) for field in fields): + raise ConfigError( + "validator fields should be passed as separate string args. " # noqa: Q000 + "E.g. usage should be `@validator('<field_name_1>', '<field_name_2>', ...)`" + ) if whole is not None: warnings.warn(
pydantic/pydantic
2ac10affe5359269d4a084149959423ac8328a4f
diff --git a/tests/test_validators.py b/tests/test_validators.py --- a/tests/test_validators.py +++ b/tests/test_validators.py @@ -658,6 +658,22 @@ def check_a(cls, v): assert Model().a == 'default value' +def test_validator_bad_fields_throws_configerror(): + """ + Attempts to create a validator with fields set as a list of strings, + rather than just multiple string args. Expects ConfigError to be raised. + """ + with pytest.raises(ConfigError, match='validator fields should be passed as separate string args.'): + + class Model(BaseModel): + a: str + b: str + + @validator(['a', 'b']) + def check_fields(cls, v): + return v + + def test_datetime_validator(): check_calls = 0
Throw descriptive exception for incorrectly defined validator fields. ### Discussed in https://github.com/samuelcolvin/pydantic/discussions/3129 <div type='discussions-op-text'> <sup>Originally posted by **SunsetOrange** August 24, 2021</sup> I had been trying to locate a bug in my code for an hour or so, which I eventually narrowed down to an incorrectly defined custom validator decorator. I had placed multiple field strings into the decorator call, inside a list rather than as multiple args. My own mistake, but Pydantic had been throwing a very unhelpful exception stating that my model was not hashable. The exception was pointing at the class definition line, not the validator decorator. `Exception has occurred: TypeError unhashable type: 'list'` This confused me greatly for a good while as I tried to find a possible location in the model and its super classes where a list was being used as a dictionary key. As this is a mistake that others could easily make (and I think I have made it in the past as well), it would be nice and helpful to output an exception that identifies the mistake and provides helpful feedback. Else wise, the source of the exception is difficult to identify. I proposing that the following code be added to class_validators.py at line 75. ``` elif not all([isinstance(field, str) for field in fields]): raise ConfigError( "validator fields should be passed as separate string args. Do not pass multiple fields as a list, etc. " "E.g. usage should be `@validator('<field_name_1>', '<field_name_2>', ...)` " "NOT `@validator(['<field_name_1>', '<field_name_2>', ...], ...)`" ) ``` </div> Throw descriptive exception for incorrectly defined validator fields. ### Discussed in https://github.com/samuelcolvin/pydantic/discussions/3129 <div type='discussions-op-text'> <sup>Originally posted by **SunsetOrange** August 24, 2021</sup> I had been trying to locate a bug in my code for an hour or so, which I eventually narrowed down to an incorrectly defined custom validator decorator. I had placed multiple field strings into the decorator call, inside a list rather than as multiple args. My own mistake, but Pydantic had been throwing a very unhelpful exception stating that my model was not hashable. The exception was pointing at the class definition line, not the validator decorator. `Exception has occurred: TypeError unhashable type: 'list'` This confused me greatly for a good while as I tried to find a possible location in the model and its super classes where a list was being used as a dictionary key. As this is a mistake that others could easily make (and I think I have made it in the past as well), it would be nice and helpful to output an exception that identifies the mistake and provides helpful feedback. Else wise, the source of the exception is difficult to identify. I proposing that the following code be added to class_validators.py at line 75. ``` elif not all([isinstance(field, str) for field in fields]): raise ConfigError( "validator fields should be passed as separate string args. Do not pass multiple fields as a list, etc. " "E.g. usage should be `@validator('<field_name_1>', '<field_name_2>', ...)` " "NOT `@validator(['<field_name_1>', '<field_name_2>', ...], ...)`" ) ``` </div>
0.0
2ac10affe5359269d4a084149959423ac8328a4f
[ "tests/test_validators.py::test_validator_bad_fields_throws_configerror" ]
[ "tests/test_validators.py::test_simple", "tests/test_validators.py::test_int_validation", "tests/test_validators.py::test_frozenset_validation", "tests/test_validators.py::test_deque_validation", "tests/test_validators.py::test_validate_whole", "tests/test_validators.py::test_validate_kwargs", "tests/test_validators.py::test_validate_pre_error", "tests/test_validators.py::test_validating_assignment_ok", "tests/test_validators.py::test_validating_assignment_fail", "tests/test_validators.py::test_validating_assignment_value_change", "tests/test_validators.py::test_validating_assignment_extra", "tests/test_validators.py::test_validating_assignment_dict", "tests/test_validators.py::test_validating_assignment_values_dict", "tests/test_validators.py::test_validate_multiple", "tests/test_validators.py::test_classmethod", "tests/test_validators.py::test_duplicates", "tests/test_validators.py::test_use_bare", "tests/test_validators.py::test_use_no_fields", "tests/test_validators.py::test_validate_always", "tests/test_validators.py::test_validate_always_on_inheritance", "tests/test_validators.py::test_validate_not_always", "tests/test_validators.py::test_wildcard_validators", "tests/test_validators.py::test_wildcard_validator_error", "tests/test_validators.py::test_invalid_field", "tests/test_validators.py::test_validate_child", "tests/test_validators.py::test_validate_child_extra", "tests/test_validators.py::test_validate_child_all", "tests/test_validators.py::test_validate_parent", "tests/test_validators.py::test_validate_parent_all", "tests/test_validators.py::test_inheritance_keep", "tests/test_validators.py::test_inheritance_replace", "tests/test_validators.py::test_inheritance_new", "tests/test_validators.py::test_validation_each_item", "tests/test_validators.py::test_validation_each_item_one_sublevel", "tests/test_validators.py::test_key_validation", "tests/test_validators.py::test_validator_always_optional", "tests/test_validators.py::test_validator_always_pre", "tests/test_validators.py::test_validator_always_post", "tests/test_validators.py::test_validator_always_post_optional", "tests/test_validators.py::test_datetime_validator", "tests/test_validators.py::test_pre_called_once", "tests/test_validators.py::test_make_generic_validator[fields0-_v_]", "tests/test_validators.py::test_make_generic_validator[fields1-_v_]", "tests/test_validators.py::test_make_generic_validator[fields2-_v_,_field_]", "tests/test_validators.py::test_make_generic_validator[fields3-_v_,_config_]", "tests/test_validators.py::test_make_generic_validator[fields4-_v_,_values_]", "tests/test_validators.py::test_make_generic_validator[fields5-_v_,_field_,_config_]", "tests/test_validators.py::test_make_generic_validator[fields6-_v_,_field_,_values_]", "tests/test_validators.py::test_make_generic_validator[fields7-_v_,_config_,_values_]", "tests/test_validators.py::test_make_generic_validator[fields8-_v_,_field_,_values_,_config_]", "tests/test_validators.py::test_make_generic_validator[fields9-_cls_,_v_]", "tests/test_validators.py::test_make_generic_validator[fields10-_cls_,_v_]", "tests/test_validators.py::test_make_generic_validator[fields11-_cls_,_v_,_field_]", "tests/test_validators.py::test_make_generic_validator[fields12-_cls_,_v_,_config_]", "tests/test_validators.py::test_make_generic_validator[fields13-_cls_,_v_,_values_]", "tests/test_validators.py::test_make_generic_validator[fields14-_cls_,_v_,_field_,_config_]", "tests/test_validators.py::test_make_generic_validator[fields15-_cls_,_v_,_field_,_values_]", "tests/test_validators.py::test_make_generic_validator[fields16-_cls_,_v_,_config_,_values_]", "tests/test_validators.py::test_make_generic_validator[fields17-_cls_,_v_,_field_,_values_,_config_]", "tests/test_validators.py::test_make_generic_validator_kwargs", "tests/test_validators.py::test_make_generic_validator_invalid", "tests/test_validators.py::test_make_generic_validator_cls_kwargs", "tests/test_validators.py::test_make_generic_validator_cls_invalid", "tests/test_validators.py::test_make_generic_validator_self", "tests/test_validators.py::test_assert_raises_validation_error", "tests/test_validators.py::test_whole", "tests/test_validators.py::test_root_validator", "tests/test_validators.py::test_root_validator_pre", "tests/test_validators.py::test_root_validator_repeat", "tests/test_validators.py::test_root_validator_repeat2", "tests/test_validators.py::test_root_validator_self", "tests/test_validators.py::test_root_validator_extra", "tests/test_validators.py::test_root_validator_types", "tests/test_validators.py::test_root_validator_inheritance", "tests/test_validators.py::test_root_validator_returns_none_exception", "tests/test_validators.py::test_reuse_global_validators", "tests/test_validators.py::test_allow_reuse[True-True-True-True]", "tests/test_validators.py::test_allow_reuse[True-True-True-False]", "tests/test_validators.py::test_allow_reuse[True-True-False-True]", "tests/test_validators.py::test_allow_reuse[True-True-False-False]", "tests/test_validators.py::test_allow_reuse[True-False-True-True]", "tests/test_validators.py::test_allow_reuse[True-False-True-False]", "tests/test_validators.py::test_allow_reuse[True-False-False-True]", "tests/test_validators.py::test_allow_reuse[True-False-False-False]", "tests/test_validators.py::test_allow_reuse[False-True-True-True]", "tests/test_validators.py::test_allow_reuse[False-True-True-False]", "tests/test_validators.py::test_allow_reuse[False-True-False-True]", "tests/test_validators.py::test_allow_reuse[False-True-False-False]", "tests/test_validators.py::test_allow_reuse[False-False-True-True]", "tests/test_validators.py::test_allow_reuse[False-False-True-False]", "tests/test_validators.py::test_allow_reuse[False-False-False-True]", "tests/test_validators.py::test_allow_reuse[False-False-False-False]", "tests/test_validators.py::test_root_validator_classmethod[True-True]", "tests/test_validators.py::test_root_validator_classmethod[True-False]", "tests/test_validators.py::test_root_validator_classmethod[False-True]", "tests/test_validators.py::test_root_validator_classmethod[False-False]", "tests/test_validators.py::test_root_validator_skip_on_failure", "tests/test_validators.py::test_assignment_validator_cls", "tests/test_validators.py::test_literal_validator", "tests/test_validators.py::test_literal_validator_str_enum", "tests/test_validators.py::test_nested_literal_validator", "tests/test_validators.py::test_union_literal_with_constraints", "tests/test_validators.py::test_field_that_is_being_validated_is_excluded_from_validator_values", "tests/test_validators.py::test_exceptions_in_field_validators_restore_original_field_value", "tests/test_validators.py::test_overridden_root_validators" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2021-09-15 01:05:12+00:00
mit
4,839
pydantic__pydantic-3241
diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -853,7 +853,9 @@ def __eq__(self, other: Any) -> bool: return self.dict() == other def __repr_args__(self) -> 'ReprArgs': - return [(k, v) for k, v in self.__dict__.items() if self.__fields__[k].field_info.repr] + return [ + (k, v) for k, v in self.__dict__.items() if k not in self.__fields__ or self.__fields__[k].field_info.repr + ] _is_base_model_class_defined = True
pydantic/pydantic
c256dccbb383a7fd462f62fcb5d55558eb3cb108
diff --git a/tests/test_main.py b/tests/test_main.py --- a/tests/test_main.py +++ b/tests/test_main.py @@ -194,6 +194,16 @@ class Config: assert Model(a='10.2', b=12).dict() == {'a': 10.2, 'b': 12} +def test_allow_extra_repr(): + class Model(BaseModel): + a: float = ... + + class Config: + extra = Extra.allow + + assert str(Model(a='10.2', b=12)) == 'a=10.2 b=12' + + def test_forbidden_extra_success(): class ForbiddenExtra(BaseModel): foo = 'whatever'
when extra is allowed, representation is break ### Checks * [x] I added a descriptive title to this issue * [x] I have searched (google, github) for similar issues and couldn't find anything * [x] I have read and followed [the docs](https://pydantic-docs.helpmanual.io/) and still think this is a bug <!-- Sorry to sound so draconian, but every second saved replying to issues is time spend improving pydantic :-) --> # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` python -c "import pydantic.utils; print(pydantic.utils.version_info())" pydantic version: 1.8.2 pydantic compiled: False install path: /Users/Sol/Project/pydantic/pydantic python version: 3.9.5 (default, Jun 23 2021, 22:47:04) [Clang 11.0.3 (clang-1103.0.32.62)] platform: macOS-10.15.6-x86_64-i386-64bit optional deps. installed: ['devtools', 'dotenv', 'email-validator', 'typing-extensions'] ``` <!-- or if you're using pydantic prior to v1.3, manually include: OS, python version and pydantic version --> <!-- Please read the [docs](https://pydantic-docs.helpmanual.io/) and search through issues to confirm your bug hasn't already been reported. --> <!-- Where possible please include a self-contained code snippet describing your bug: --> ```py from pydantic import BaseModel from pydantic import Extra class Foo(BaseModel): a: int class Config: extra = Extra.allow f = Foo(a=1, b=2) breakpoint() print(f) # << raise error. not only 'print', also str(Model), breakpoint().. etc ``` because field b that allowed is not in Model.fields in `main.BaseModel` ``` class BaseModel(Representation, metaclass=ModelMetaclass): ... def __repr_args__(self) -> 'ReprArgs': return [(k, v) for k, v in self.__dict__.items() if self.__fields__[k].field_info.repr] # KeyError ```
0.0
c256dccbb383a7fd462f62fcb5d55558eb3cb108
[ "tests/test_main.py::test_allow_extra_repr" ]
[ "tests/test_main.py::test_success", "tests/test_main.py::test_ultra_simple_missing", "tests/test_main.py::test_ultra_simple_failed", "tests/test_main.py::test_ultra_simple_repr", "tests/test_main.py::test_default_factory_field", "tests/test_main.py::test_default_factory_no_type_field", "tests/test_main.py::test_comparing", "tests/test_main.py::test_nullable_strings_success", "tests/test_main.py::test_nullable_strings_fails", "tests/test_main.py::test_recursion", "tests/test_main.py::test_recursion_fails", "tests/test_main.py::test_not_required", "tests/test_main.py::test_infer_type", "tests/test_main.py::test_allow_extra", "tests/test_main.py::test_forbidden_extra_success", "tests/test_main.py::test_forbidden_extra_fails", "tests/test_main.py::test_disallow_mutation", "tests/test_main.py::test_extra_allowed", "tests/test_main.py::test_extra_ignored", "tests/test_main.py::test_set_attr", "tests/test_main.py::test_set_attr_invalid", "tests/test_main.py::test_any", "tests/test_main.py::test_alias", "tests/test_main.py::test_population_by_field_name", "tests/test_main.py::test_field_order", "tests/test_main.py::test_required", "tests/test_main.py::test_mutability", "tests/test_main.py::test_immutability[False-False]", "tests/test_main.py::test_immutability[False-True]", "tests/test_main.py::test_immutability[True-True]", "tests/test_main.py::test_not_frozen_are_not_hashable", "tests/test_main.py::test_with_declared_hash", "tests/test_main.py::test_frozen_with_hashable_fields_are_hashable", "tests/test_main.py::test_frozen_with_unhashable_fields_are_not_hashable", "tests/test_main.py::test_hash_function_give_different_result_for_different_object", "tests/test_main.py::test_const_validates", "tests/test_main.py::test_const_uses_default", "tests/test_main.py::test_const_validates_after_type_validators", "tests/test_main.py::test_const_with_wrong_value", "tests/test_main.py::test_const_with_validator", "tests/test_main.py::test_const_list", "tests/test_main.py::test_const_list_with_wrong_value", "tests/test_main.py::test_const_validation_json_serializable", "tests/test_main.py::test_validating_assignment_pass", "tests/test_main.py::test_validating_assignment_fail", "tests/test_main.py::test_validating_assignment_pre_root_validator_fail", "tests/test_main.py::test_validating_assignment_post_root_validator_fail", "tests/test_main.py::test_root_validator_many_values_change", "tests/test_main.py::test_enum_values", "tests/test_main.py::test_literal_enum_values", "tests/test_main.py::test_enum_raw", "tests/test_main.py::test_set_tuple_values", "tests/test_main.py::test_default_copy", "tests/test_main.py::test_arbitrary_type_allowed_validation_success", "tests/test_main.py::test_arbitrary_type_allowed_validation_fails", "tests/test_main.py::test_arbitrary_types_not_allowed", "tests/test_main.py::test_type_type_validation_success", "tests/test_main.py::test_type_type_subclass_validation_success", "tests/test_main.py::test_type_type_validation_fails_for_instance", "tests/test_main.py::test_type_type_validation_fails_for_basic_type", "tests/test_main.py::test_bare_type_type_validation_success", "tests/test_main.py::test_bare_type_type_validation_fails", "tests/test_main.py::test_annotation_field_name_shadows_attribute", "tests/test_main.py::test_value_field_name_shadows_attribute", "tests/test_main.py::test_class_var", "tests/test_main.py::test_fields_set", "tests/test_main.py::test_exclude_unset_dict", "tests/test_main.py::test_exclude_unset_recursive", "tests/test_main.py::test_dict_exclude_unset_populated_by_alias", "tests/test_main.py::test_dict_exclude_unset_populated_by_alias_with_extra", "tests/test_main.py::test_exclude_defaults", "tests/test_main.py::test_dir_fields", "tests/test_main.py::test_dict_with_extra_keys", "tests/test_main.py::test_root", "tests/test_main.py::test_root_list", "tests/test_main.py::test_root_nested", "tests/test_main.py::test_encode_nested_root", "tests/test_main.py::test_root_failed", "tests/test_main.py::test_root_undefined_failed", "tests/test_main.py::test_parse_root_as_mapping", "tests/test_main.py::test_parse_obj_non_mapping_root", "tests/test_main.py::test_parse_obj_nested_root", "tests/test_main.py::test_untouched_types", "tests/test_main.py::test_custom_types_fail_without_keep_untouched", "tests/test_main.py::test_model_iteration", "tests/test_main.py::test_model_export_nested_list[excluding", "tests/test_main.py::test_model_export_nested_list[should", "tests/test_main.py::test_model_export_nested_list[using", "tests/test_main.py::test_model_export_dict_exclusion[excluding", "tests/test_main.py::test_model_export_dict_exclusion[using", "tests/test_main.py::test_model_export_dict_exclusion[exclude", "tests/test_main.py::test_model_exclude_config_field_merging", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[None-expected0-kinds0]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[None-expected0-kinds1]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[None-expected0-kinds2]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[None-expected0-kinds3]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[None-expected0-kinds4]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[None-expected0-kinds5]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[None-expected0-kinds6]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude1-expected1-kinds0]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude1-expected1-kinds1]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude1-expected1-kinds2]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude1-expected1-kinds3]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude1-expected1-kinds4]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude1-expected1-kinds5]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude1-expected1-kinds6]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude2-expected2-kinds0]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude2-expected2-kinds1]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude2-expected2-kinds2]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude2-expected2-kinds3]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude2-expected2-kinds4]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude2-expected2-kinds5]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude2-expected2-kinds6]", "tests/test_main.py::test_model_export_exclusion_inheritance", "tests/test_main.py::test_model_export_with_true_instead_of_ellipsis", "tests/test_main.py::test_model_export_inclusion", "tests/test_main.py::test_model_export_inclusion_inheritance", "tests/test_main.py::test_custom_init_subclass_params", "tests/test_main.py::test_update_forward_refs_does_not_modify_module_dict", "tests/test_main.py::test_two_defaults", "tests/test_main.py::test_default_factory", "tests/test_main.py::test_default_factory_called_once", "tests/test_main.py::test_default_factory_called_once_2", "tests/test_main.py::test_default_factory_validate_children", "tests/test_main.py::test_default_factory_parse", "tests/test_main.py::test_none_min_max_items", "tests/test_main.py::test_reuse_same_field", "tests/test_main.py::test_base_config_type_hinting", "tests/test_main.py::test_allow_mutation_field", "tests/test_main.py::test_repr_field", "tests/test_main.py::test_inherited_model_field_copy", "tests/test_main.py::test_inherited_model_field_untouched", "tests/test_main.py::test_mapping_retains_type_subclass", "tests/test_main.py::test_mapping_retains_type_defaultdict", "tests/test_main.py::test_mapping_retains_type_fallback_error", "tests/test_main.py::test_typing_coercion_dict", "tests/test_main.py::test_typing_coercion_defaultdict", "tests/test_main.py::test_typing_coercion_counter", "tests/test_main.py::test_typing_counter_value_validation", "tests/test_main.py::test_class_kwargs_config", "tests/test_main.py::test_class_kwargs_config_json_encoders", "tests/test_main.py::test_class_kwargs_config_and_attr_conflict", "tests/test_main.py::test_class_kwargs_custom_config" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2021-09-22 05:08:37+00:00
mit
4,840
pydantic__pydantic-3304
diff --git a/pydantic/env_settings.py b/pydantic/env_settings.py --- a/pydantic/env_settings.py +++ b/pydantic/env_settings.py @@ -269,7 +269,11 @@ def __call__(self, settings: BaseSettings) -> Dict[str, Any]: for field in settings.__fields__.values(): for env_name in field.field_info.extra['env_names']: - path = secrets_path / env_name + path = find_case_path(secrets_path, env_name, settings.__config__.case_sensitive) + if not path: + # path does not exist, we curently don't return a warning for this + continue + if path.is_file(): secret_value = path.read_text().strip() if field.is_complex(): @@ -279,12 +283,11 @@ def __call__(self, settings: BaseSettings) -> Dict[str, Any]: raise SettingsError(f'error parsing JSON for "{env_name}"') from e secrets[field.alias] = secret_value - elif path.exists(): + else: warnings.warn( f'attempted to load secret file "{path}" but found a {path_type(path)} instead.', stacklevel=4, ) - return secrets def __repr__(self) -> str: @@ -304,3 +307,15 @@ def read_env_file( return {k.lower(): v for k, v in file_vars.items()} else: return file_vars + + +def find_case_path(dir_path: Path, file_name: str, case_sensitive: bool) -> Optional[Path]: + """ + Find a file within path's directory matching filename, optionally ignoring case. + """ + for f in dir_path.iterdir(): + if f.name == file_name: + return f + elif not case_sensitive and f.name.lower() == file_name.lower(): + return f + return None
pydantic/pydantic
d53259aa58732f34c92dd48586d0693bdc8edfec
diff --git a/tests/test_settings.py b/tests/test_settings.py --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -890,6 +890,33 @@ class Config: assert Settings().dict() == {'foo': 'foo_secret_value_str'} +def test_secrets_case_sensitive(tmp_path): + (tmp_path / 'SECRET_VAR').write_text('foo_env_value_str') + + class Settings(BaseSettings): + secret_var: Optional[str] + + class Config: + secrets_dir = tmp_path + case_sensitive = True + + assert Settings().dict() == {'secret_var': None} + + +def test_secrets_case_insensitive(tmp_path): + (tmp_path / 'SECRET_VAR').write_text('foo_env_value_str') + + class Settings(BaseSettings): + secret_var: Optional[str] + + class Config: + secrets_dir = tmp_path + case_sensitive = False + + settings = Settings().dict() + assert settings == {'secret_var': 'foo_env_value_str'} + + def test_secrets_path_url(tmp_path): (tmp_path / 'foo').write_text('http://www.example.com') (tmp_path / 'bar').write_text('snap') @@ -940,6 +967,7 @@ class Config: with pytest.raises(ValidationError) as exc_info: Settings() + assert exc_info.value.errors() == [{'loc': ('foo',), 'msg': 'field required', 'type': 'value_error.missing'}]
Pydantic fails to read content of files in secrets_dir on Linux ### Checks * [x] I added a descriptive title to this issue * [x] I have searched (google, github) for similar issues and couldn't find anything * [x] I have read and followed [the docs](https://pydantic-docs.helpmanual.io/) and still think this is a bug <!-- Sorry to sound so draconian, but every second saved replying to issues is time spend improving pydantic :-) --> # Bug To reproduce, on Linux OS: - build a config manager that subclasses `BaseSettings` - add `secrets_dir` config pointing to dir with text file(s), as per docs - add class attributes to use the files in `secrets_dir`, as per docs - run the code and inspect/print the attributes - observe that vars coming from .env file work fine, but those from `secrets_dir` are None, or error if not Optional, and there is no user warning for the `secrets_dir` itself Repeat the same on MacOS - it should work OK, the content is read correctly. I have added a repo with Dockerfile replicating the setup: https://github.com/dimitri-b/pydantic-secrets-dir-issue Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.8.2 pydantic compiled: True install path: /usr/local/lib/python3.8/site-packages/pydantic python version: 3.8.12 (default, Sep 3 2021, 02:35:42) [GCC 8.3.0] platform: Linux-5.10.47-linuxkit-x86_64-with-glibc2.2.5 optional deps. installed: ['dotenv', 'typing-extensions'] ``` <!-- or if you're using pydantic prior to v1.3, manually include: OS, python version and pydantic version --> <!-- Please read the [docs](https://pydantic-docs.helpmanual.io/) and search through issues to confirm your bug hasn't already been reported. --> <!-- Where possible please include a self-contained code snippet describing your bug: --> ```py import pydantic class SettingsLocal(pydantic.BaseSettings): NORMAL_VAR: Optional[str] SECRET_VAR: Optional[str] class Config: env_file = "./.env" secrets_dir = "./secrets-in-project" ... ```
0.0
d53259aa58732f34c92dd48586d0693bdc8edfec
[ "tests/test_settings.py::test_secrets_case_insensitive" ]
[ "tests/test_settings.py::test_sub_env", "tests/test_settings.py::test_sub_env_override", "tests/test_settings.py::test_sub_env_missing", "tests/test_settings.py::test_other_setting", "tests/test_settings.py::test_with_prefix", "tests/test_settings.py::test_nested_env_with_basemodel", "tests/test_settings.py::test_merge_dict", "tests/test_settings.py::test_nested_env_delimiter", "tests/test_settings.py::test_nested_env_delimiter_complex_required", "tests/test_settings.py::test_nested_env_delimiter_aliases", "tests/test_settings.py::test_list", "tests/test_settings.py::test_set_dict_model", "tests/test_settings.py::test_invalid_json", "tests/test_settings.py::test_required_sub_model", "tests/test_settings.py::test_non_class", "tests/test_settings.py::test_env_str", "tests/test_settings.py::test_env_list", "tests/test_settings.py::test_env_list_field", "tests/test_settings.py::test_env_list_last", "tests/test_settings.py::test_env_inheritance", "tests/test_settings.py::test_env_inheritance_field", "tests/test_settings.py::test_env_prefix_inheritance_config", "tests/test_settings.py::test_env_inheritance_config", "tests/test_settings.py::test_env_invalid", "tests/test_settings.py::test_env_field", "tests/test_settings.py::test_aliases_warning", "tests/test_settings.py::test_aliases_no_warning", "tests/test_settings.py::test_case_sensitive", "tests/test_settings.py::test_nested_dataclass", "tests/test_settings.py::test_env_takes_precedence", "tests/test_settings.py::test_config_file_settings_nornir", "tests/test_settings.py::test_env_union_with_complex_subfields_parses_json", "tests/test_settings.py::test_env_union_with_complex_subfields_parses_plain_if_json_fails", "tests/test_settings.py::test_env_union_without_complex_subfields_does_not_parse_json", "tests/test_settings.py::test_env_file_config", "tests/test_settings.py::test_env_file_config_case_sensitive", "tests/test_settings.py::test_env_file_export", "tests/test_settings.py::test_env_file_config_custom_encoding", "tests/test_settings.py::test_env_file_home_directory", "tests/test_settings.py::test_env_file_none", "tests/test_settings.py::test_env_file_override_file", "tests/test_settings.py::test_env_file_override_none", "tests/test_settings.py::test_env_file_not_a_file", "tests/test_settings.py::test_read_env_file_cast_sensitive", "tests/test_settings.py::test_read_env_file_syntax_wrong", "tests/test_settings.py::test_env_file_example", "tests/test_settings.py::test_env_file_custom_encoding", "tests/test_settings.py::test_alias_set", "tests/test_settings.py::test_prefix_on_parent", "tests/test_settings.py::test_frozenset", "tests/test_settings.py::test_secrets_path", "tests/test_settings.py::test_secrets_case_sensitive", "tests/test_settings.py::test_secrets_path_url", "tests/test_settings.py::test_secrets_path_json", "tests/test_settings.py::test_secrets_path_invalid_json", "tests/test_settings.py::test_secrets_missing", "tests/test_settings.py::test_secrets_invalid_secrets_dir", "tests/test_settings.py::test_secrets_missing_location", "tests/test_settings.py::test_secrets_file_is_a_directory", "tests/test_settings.py::test_secrets_dotenv_precedence", "tests/test_settings.py::test_external_settings_sources_precedence", "tests/test_settings.py::test_external_settings_sources_filter_env_vars", "tests/test_settings.py::test_customise_sources_empty", "tests/test_settings.py::test_builtins_settings_source_repr" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2021-10-08 15:48:32+00:00
mit
4,841
pydantic__pydantic-3403
diff --git a/pydantic/typing.py b/pydantic/typing.py --- a/pydantic/typing.py +++ b/pydantic/typing.py @@ -332,7 +332,9 @@ def resolve_annotations(raw_annotations: Dict[str, Type[Any]], module_name: Opti annotations = {} for name, value in raw_annotations.items(): if isinstance(value, str): - if sys.version_info >= (3, 7): + if (3, 10) > sys.version_info >= (3, 9, 8) or sys.version_info >= (3, 10, 1): + value = ForwardRef(value, is_argument=False, is_class=True) + elif sys.version_info >= (3, 7): value = ForwardRef(value, is_argument=False) else: value = ForwardRef(value)
pydantic/pydantic
8afdaab4acefb2f50e056b6661fbbda36b63b2b8
diff --git a/tests/test_forward_ref.py b/tests/test_forward_ref.py --- a/tests/test_forward_ref.py +++ b/tests/test_forward_ref.py @@ -519,3 +519,20 @@ class NestedTuple(BaseModel): NestedTuple.update_forward_refs() obj = NestedTuple.parse_obj({'x': ('1', {'x': ('2', {'x': ('3', None)})})}) assert obj.dict() == {'x': (1, {'x': (2, {'x': (3, None)})})} + + +@skip_pre_37 +def test_class_var_as_string(create_module): + module = create_module( + # language=Python + """ +from __future__ import annotations +from typing import ClassVar +from pydantic import BaseModel + +class Model(BaseModel): + a: ClassVar[int] +""" + ) + + assert module.Model.__class_vars__ == {'a'}
Pydantic fail to parse ClassVar annotation when it's a string ### Checks * [x] I added a descriptive title to this issue * [x] I have searched (google, github) for similar issues and couldn't find anything * [x] I have read and followed [the docs](https://pydantic-docs.helpmanual.io/) and still think this is a bug <!-- Sorry to sound so draconian, but every second saved replying to issues is time spend improving pydantic :-) --> # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.8.2 pydantic compiled: False install path: /Users/yuriikarabas/my-projects/pydantic/pydantic python version: 3.9.8 (tags/v3.9.8:bb3fdcfe95, Nov 10 2021, 14:54:52) [Clang 13.0.0 (clang-1300.0.29.3)] platform: macOS-12.0.1-x86_64-i386-64bit optional deps. installed: ['devtools', 'dotenv', 'email-validator', 'typing-extensions'] ``` <!-- or if you're using pydantic prior to v1.3, manually include: OS, python version and pydantic version --> <!-- Please read the [docs](https://pydantic-docs.helpmanual.io/) and search through issues to confirm your bug hasn't already been reported. --> <!-- Where possible please include a self-contained code snippet describing your bug: --> ```py from typing import ClassVar from pydantic import BaseModel class Model(BaseModel): val: "ClassVar[int]" = 10 ``` ``` Traceback (most recent call last): File "/Users/yuriikarabas/my-projects/pydantic/temp.py", line 6, in <module> class Model(BaseModel): File "/Users/yuriikarabas/my-projects/pydantic/pydantic/main.py", line 187, in __new__ annotations = resolve_annotations(namespace.get('__annotations__', {}), namespace.get('__module__', None)) File "/Users/yuriikarabas/my-projects/pydantic/pydantic/typing.py", line 340, in resolve_annotations value = _eval_type(value, base_globals, None) File "/Users/yuriikarabas/my-projects/cpython/Lib/typing.py", line 292, in _eval_type return t._evaluate(globalns, localns, recursive_guard) File "/Users/yuriikarabas/my-projects/cpython/Lib/typing.py", line 553, in _evaluate type_ = _type_check( File "/Users/yuriikarabas/my-projects/cpython/Lib/typing.py", line 158, in _type_check raise TypeError(f"{arg} is not valid as type argument") TypeError: typing.ClassVar[int] is not valid as type argument ```
0.0
8afdaab4acefb2f50e056b6661fbbda36b63b2b8
[ "tests/test_forward_ref.py::test_class_var_as_string" ]
[ "tests/test_forward_ref.py::test_postponed_annotations", "tests/test_forward_ref.py::test_postponed_annotations_optional", "tests/test_forward_ref.py::test_basic_forward_ref", "tests/test_forward_ref.py::test_self_forward_ref_module", "tests/test_forward_ref.py::test_self_forward_ref_collection", "tests/test_forward_ref.py::test_self_forward_ref_local", "tests/test_forward_ref.py::test_missing_update_forward_refs", "tests/test_forward_ref.py::test_forward_ref_dataclass", "tests/test_forward_ref.py::test_forward_ref_dataclass_with_future_annotations", "tests/test_forward_ref.py::test_forward_ref_sub_types", "tests/test_forward_ref.py::test_forward_ref_nested_sub_types", "tests/test_forward_ref.py::test_self_reference_json_schema", "tests/test_forward_ref.py::test_self_reference_json_schema_with_future_annotations", "tests/test_forward_ref.py::test_circular_reference_json_schema", "tests/test_forward_ref.py::test_circular_reference_json_schema_with_future_annotations", "tests/test_forward_ref.py::test_forward_ref_with_field", "tests/test_forward_ref.py::test_forward_ref_optional", "tests/test_forward_ref.py::test_forward_ref_with_create_model", "tests/test_forward_ref.py::test_resolve_forward_ref_dataclass", "tests/test_forward_ref.py::test_nested_forward_ref" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2021-11-10 13:40:26+00:00
mit
4,842
pydantic__pydantic-3452
diff --git a/pydantic/fields.py b/pydantic/fields.py --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -34,7 +34,6 @@ Callable, ForwardRef, NoArgAnyCallable, - NoneType, display_as_type, get_args, get_origin, @@ -563,10 +562,11 @@ def _type_analysis(self) -> None: # noqa: C901 (ignore complexity) if is_union(origin): types_ = [] for type_ in get_args(self.type_): - if type_ is NoneType: + if is_none_type(type_) or type_ is Any or type_ is object: if self.required is Undefined: self.required = False self.allow_none = True + if is_none_type(type_): continue types_.append(type_)
pydantic/pydantic
7421579480148cdfbd7752b17b49a3dbbc7557bc
`allow_none` attribute for field `a` remains `False`. Possible fix may be in pydantic/fields.py:566: ``` if is_union_origin(origin): types_ = [] for type_ in get_args(self.type_): if type_ is NoneType or type_ is Any or type_ is object: if self.required is Undefined: self.required = False self.allow_none = True continue types_.append(type_) ``` @mykhailoleskiv That almost works, except it doesn't add `Any` or `object` to `types_` (which eventually becomes `ModelField.sub_fields`). So `M(a="abcd")` or something like that no longer works. I'll open a PR
diff --git a/tests/test_edge_cases.py b/tests/test_edge_cases.py --- a/tests/test_edge_cases.py +++ b/tests/test_edge_cases.py @@ -83,6 +83,23 @@ class Model(BaseModel): ] +def test_union_int_any(): + class Model(BaseModel): + v: Union[int, Any] + + m = Model(v=123) + assert m.v == 123 + + m = Model(v='123') + assert m.v == 123 + + m = Model(v='foobar') + assert m.v == 'foobar' + + m = Model(v=None) + assert m.v is None + + def test_union_priority(): class ModelOne(BaseModel): v: Union[int, str] = ...
"none is not an allowed value" when using Union with Any ### Checks * [x] I added a descriptive title to this issue * [x] I have searched (google, github) for similar issues and couldn't find anything * [x] I have read and followed [the docs](https://pydantic-docs.helpmanual.io/) and still think this is a bug # Bug It seems that `None` is allowed when a field's type is `Any` (as is expected, stated in the docs), but `None` is not allowed when a field's type is `Union[SomeType, Any]`. Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.8.2 pydantic compiled: True install path: C:\Users\TobyHarradine\PycharmProjects\orchestration\.venv\Lib\site-packages\pydantic python version: 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)] platform: Windows-10-10.0.19041-SP0 optional deps. installed: ['typing-extensions'] ``` Code which reproduces the issue: ```pycon >>> import pydantic >>> class M(pydantic.BaseModel): ... a: Any ... >>> M(a=1) M(a=1) >>> M(a=None) M(a=None) >>> class M(pydantic.BaseModel): ... a: Union[int, Any] ... >>> M(a=1) M(a=1) >>> M(a="abcd") M(a='abcd') >>> M(a=None) Traceback (most recent call last): File "<input>", line 1, in <module> File "pydantic\main.py", line 406, in pydantic.main.BaseModel.__init__ pydantic.error_wrappers.ValidationError: 1 validation error for M a none is not an allowed value (type=type_error.none.not_allowed) ``` This may be somewhat related to #1624.
0.0
7421579480148cdfbd7752b17b49a3dbbc7557bc
[ "tests/test_edge_cases.py::test_union_int_any" ]
[ "tests/test_edge_cases.py::test_str_bytes", "tests/test_edge_cases.py::test_str_bytes_none", "tests/test_edge_cases.py::test_union_int_str", "tests/test_edge_cases.py::test_union_priority", "tests/test_edge_cases.py::test_typed_list", "tests/test_edge_cases.py::test_typed_set", "tests/test_edge_cases.py::test_dict_dict", "tests/test_edge_cases.py::test_none_list", "tests/test_edge_cases.py::test_typed_dict[value0-result0]", "tests/test_edge_cases.py::test_typed_dict[value1-result1]", "tests/test_edge_cases.py::test_typed_dict[value2-result2]", "tests/test_edge_cases.py::test_typed_dict_error[1-errors0]", "tests/test_edge_cases.py::test_typed_dict_error[value1-errors1]", "tests/test_edge_cases.py::test_typed_dict_error[value2-errors2]", "tests/test_edge_cases.py::test_dict_key_error", "tests/test_edge_cases.py::test_tuple", "tests/test_edge_cases.py::test_tuple_more", "tests/test_edge_cases.py::test_tuple_length_error", "tests/test_edge_cases.py::test_tuple_invalid", "tests/test_edge_cases.py::test_tuple_value_error", "tests/test_edge_cases.py::test_recursive_list", "tests/test_edge_cases.py::test_recursive_list_error", "tests/test_edge_cases.py::test_list_unions", "tests/test_edge_cases.py::test_recursive_lists", "tests/test_edge_cases.py::test_str_enum", "tests/test_edge_cases.py::test_any_dict", "tests/test_edge_cases.py::test_success_values_include", "tests/test_edge_cases.py::test_include_exclude_unset", "tests/test_edge_cases.py::test_include_exclude_defaults", "tests/test_edge_cases.py::test_skip_defaults_deprecated", "tests/test_edge_cases.py::test_advanced_exclude", "tests/test_edge_cases.py::test_advanced_exclude_by_alias", "tests/test_edge_cases.py::test_advanced_value_include", "tests/test_edge_cases.py::test_advanced_value_exclude_include", "tests/test_edge_cases.py::test_advanced_exclude_nested_lists[exclude0-expected0]", "tests/test_edge_cases.py::test_advanced_exclude_nested_lists[exclude1-expected1]", "tests/test_edge_cases.py::test_advanced_exclude_nested_lists[exclude2-expected2]", "tests/test_edge_cases.py::test_advanced_exclude_nested_lists[exclude3-expected3]", "tests/test_edge_cases.py::test_advanced_exclude_nested_lists[exclude4-expected4]", "tests/test_edge_cases.py::test_advanced_exclude_nested_lists[exclude5-expected5]", "tests/test_edge_cases.py::test_advanced_exclude_nested_lists[exclude6-expected6]", "tests/test_edge_cases.py::test_advanced_exclude_nested_lists[exclude7-expected7]", "tests/test_edge_cases.py::test_advanced_exclude_nested_lists[exclude8-expected8]", "tests/test_edge_cases.py::test_advanced_exclude_nested_lists[exclude9-expected9]", "tests/test_edge_cases.py::test_advanced_exclude_nested_lists[exclude10-expected10]", "tests/test_edge_cases.py::test_advanced_exclude_nested_lists[exclude11-expected11]", "tests/test_edge_cases.py::test_advanced_exclude_nested_lists[exclude12-expected12]", "tests/test_edge_cases.py::test_advanced_exclude_nested_lists[exclude13-expected13]", "tests/test_edge_cases.py::test_advanced_exclude_nested_lists[exclude14-expected14]", "tests/test_edge_cases.py::test_advanced_include_nested_lists[include0-expected0]", "tests/test_edge_cases.py::test_advanced_include_nested_lists[include1-expected1]", "tests/test_edge_cases.py::test_advanced_include_nested_lists[include2-expected2]", "tests/test_edge_cases.py::test_advanced_include_nested_lists[include3-expected3]", "tests/test_edge_cases.py::test_advanced_include_nested_lists[include4-expected4]", "tests/test_edge_cases.py::test_advanced_include_nested_lists[include5-expected5]", "tests/test_edge_cases.py::test_advanced_include_nested_lists[include6-expected6]", "tests/test_edge_cases.py::test_advanced_include_nested_lists[include7-expected7]", "tests/test_edge_cases.py::test_advanced_include_nested_lists[include8-expected8]", "tests/test_edge_cases.py::test_advanced_include_nested_lists[include9-expected9]", "tests/test_edge_cases.py::test_advanced_include_nested_lists[include10-expected10]", "tests/test_edge_cases.py::test_advanced_include_nested_lists[include11-expected11]", "tests/test_edge_cases.py::test_advanced_include_nested_lists[include12-expected12]", "tests/test_edge_cases.py::test_advanced_include_nested_lists[include13-expected13]", "tests/test_edge_cases.py::test_advanced_include_nested_lists[include14-expected14]", "tests/test_edge_cases.py::test_field_set_ignore_extra", "tests/test_edge_cases.py::test_field_set_allow_extra", "tests/test_edge_cases.py::test_field_set_field_name", "tests/test_edge_cases.py::test_values_order", "tests/test_edge_cases.py::test_inheritance", "tests/test_edge_cases.py::test_inheritance_subclass_default", "tests/test_edge_cases.py::test_invalid_type", "tests/test_edge_cases.py::test_valid_string_types[a", "tests/test_edge_cases.py::test_valid_string_types[some", "tests/test_edge_cases.py::test_valid_string_types[value2-foobar]", "tests/test_edge_cases.py::test_valid_string_types[123-123]", "tests/test_edge_cases.py::test_valid_string_types[123.45-123.45]", "tests/test_edge_cases.py::test_valid_string_types[value5-12.45]", "tests/test_edge_cases.py::test_valid_string_types[True-True]", "tests/test_edge_cases.py::test_valid_string_types[False-False]", "tests/test_edge_cases.py::test_valid_string_types[a10-a10]", "tests/test_edge_cases.py::test_valid_string_types[whatever-whatever]", "tests/test_edge_cases.py::test_invalid_string_types[value0-errors0]", "tests/test_edge_cases.py::test_invalid_string_types[value1-errors1]", "tests/test_edge_cases.py::test_inheritance_config", "tests/test_edge_cases.py::test_partial_inheritance_config", "tests/test_edge_cases.py::test_annotation_inheritance", "tests/test_edge_cases.py::test_string_none", "tests/test_edge_cases.py::test_return_errors_ok", "tests/test_edge_cases.py::test_return_errors_error", "tests/test_edge_cases.py::test_optional_required", "tests/test_edge_cases.py::test_invalid_validator", "tests/test_edge_cases.py::test_unable_to_infer", "tests/test_edge_cases.py::test_multiple_errors", "tests/test_edge_cases.py::test_validate_all", "tests/test_edge_cases.py::test_force_extra", "tests/test_edge_cases.py::test_illegal_extra_value", "tests/test_edge_cases.py::test_multiple_inheritance_config", "tests/test_edge_cases.py::test_submodel_different_type", "tests/test_edge_cases.py::test_self", "tests/test_edge_cases.py::test_self_recursive[BaseModel]", "tests/test_edge_cases.py::test_self_recursive[BaseSettings]", "tests/test_edge_cases.py::test_nested_init[BaseModel]", "tests/test_edge_cases.py::test_nested_init[BaseSettings]", "tests/test_edge_cases.py::test_init_inspection", "tests/test_edge_cases.py::test_type_on_annotation", "tests/test_edge_cases.py::test_assign_type", "tests/test_edge_cases.py::test_optional_subfields", "tests/test_edge_cases.py::test_not_optional_subfields", "tests/test_edge_cases.py::test_optional_field_constraints", "tests/test_edge_cases.py::test_field_str_shape", "tests/test_edge_cases.py::test_field_type_display[int-int]", "tests/test_edge_cases.py::test_field_type_display[type_1-Optional[int]]", "tests/test_edge_cases.py::test_field_type_display[type_2-Union[NoneType,", "tests/test_edge_cases.py::test_field_type_display[type_3-Union[int,", "tests/test_edge_cases.py::test_field_type_display[type_4-List[int]]", "tests/test_edge_cases.py::test_field_type_display[type_5-Tuple[int,", "tests/test_edge_cases.py::test_field_type_display[type_6-Union[List[int],", "tests/test_edge_cases.py::test_field_type_display[type_7-List[Tuple[int,", "tests/test_edge_cases.py::test_field_type_display[type_8-Mapping[int,", "tests/test_edge_cases.py::test_field_type_display[type_9-FrozenSet[int]]", "tests/test_edge_cases.py::test_field_type_display[type_10-Tuple[int,", "tests/test_edge_cases.py::test_field_type_display[type_11-Optional[List[int]]]", "tests/test_edge_cases.py::test_field_type_display[dict-dict]", "tests/test_edge_cases.py::test_field_type_display[type_13-DisplayGen[bool,", "tests/test_edge_cases.py::test_any_none", "tests/test_edge_cases.py::test_type_var_any", "tests/test_edge_cases.py::test_type_var_constraint", "tests/test_edge_cases.py::test_type_var_bound", "tests/test_edge_cases.py::test_dict_bare", "tests/test_edge_cases.py::test_list_bare", "tests/test_edge_cases.py::test_dict_any", "tests/test_edge_cases.py::test_modify_fields", "tests/test_edge_cases.py::test_exclude_none", "tests/test_edge_cases.py::test_exclude_none_recursive", "tests/test_edge_cases.py::test_exclude_none_with_extra", "tests/test_edge_cases.py::test_str_method_inheritance", "tests/test_edge_cases.py::test_repr_method_inheritance", "tests/test_edge_cases.py::test_optional_validator", "tests/test_edge_cases.py::test_required_optional", "tests/test_edge_cases.py::test_required_any", "tests/test_edge_cases.py::test_custom_generic_validators", "tests/test_edge_cases.py::test_custom_generic_arbitrary_allowed", "tests/test_edge_cases.py::test_custom_generic_disallowed", "tests/test_edge_cases.py::test_hashable_required", "tests/test_edge_cases.py::test_hashable_optional[1]", "tests/test_edge_cases.py::test_hashable_optional[None]", "tests/test_edge_cases.py::test_default_factory_called_once", "tests/test_edge_cases.py::test_default_factory_validator_child", "tests/test_edge_cases.py::test_cython_function_untouched", "tests/test_edge_cases.py::test_resolve_annotations_module_missing", "tests/test_edge_cases.py::test_iter_coverage", "tests/test_edge_cases.py::test_config_field_info", "tests/test_edge_cases.py::test_config_field_info_alias", "tests/test_edge_cases.py::test_config_field_info_merge", "tests/test_edge_cases.py::test_config_field_info_allow_mutation", "tests/test_edge_cases.py::test_arbitrary_types_allowed_custom_eq" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2021-11-25 23:06:55+00:00
mit
4,843
pydantic__pydantic-3473
diff --git a/pydantic/utils.py b/pydantic/utils.py --- a/pydantic/utils.py +++ b/pydantic/utils.py @@ -303,6 +303,13 @@ def to_camel(string: str) -> str: return ''.join(word.capitalize() for word in string.split('_')) +def to_lower_camel(string: str) -> str: + if len(string) >= 1: + pascal_string = to_camel(string) + return pascal_string[0].lower() + pascal_string[1:] + return string.lower() + + T = TypeVar('T')
pydantic/pydantic
5885e6ce12fbb931301b1de922c0eff30db292c1
after a debate today with a fellow programmer I had my eyes opened to the fact that pascal case is a type of camel case... so the naming isn't wrong. I think ill submit a PR of the second option, as I'm sure I'm not the only one that would make use of the `to_lower_camel()` function.
diff --git a/tests/test_utils.py b/tests/test_utils.py --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -37,6 +37,7 @@ lenient_issubclass, path_type, smart_deepcopy, + to_lower_camel, truncate, unique_list, ) @@ -528,6 +529,18 @@ def test_undefined_pickle(): assert undefined2 is Undefined +def test_on_lower_camel_zero_length(): + assert to_lower_camel('') == '' + + +def test_on_lower_camel_one_length(): + assert to_lower_camel('a') == 'a' + + +def test_on_lower_camel_many_length(): + assert to_lower_camel('i_like_turtles') == 'iLikeTurtles' + + def test_limited_dict(): d = LimitedDict(10) d[1] = '1'
pydantic.utils.to_camel() is actually to_pascal() ### Checks * [ y ] I added a descriptive title to this issue * [ y ] I have searched (google, github) for similar issues and couldn't find anything * [ y ] I have read and followed [the docs](https://pydantic-docs.helpmanual.io/) and still think this is a bug # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.8.1 pydantic compiled: True install path: /home/schlerp/projects/pelt-studio/venv/lib/python3.8/site-packages/pydantic python version: 3.8.5 (default, Sep 4 2020, 07:30:14) [GCC 7.3.0] platform: Linux-5.15.2-zen1-1-zen-x86_64-with-glibc2.10 optional deps. installed: ['typing-extensions'] ``` Camel case and pascal case are similar however, they differ by the capitalisation of the first letter. The current implementation of camel_case in pydantic us actually pascal case and not camel case at all. I suggest renaming this and also implementing a camel case. See below for code expressing the issue and suggested fix. **Pascal Case** (aka init case or upper camel case) All spaces/underscores removed and the start of every word is capitalised. **Camel Case** (aka lower camel case) All spaces and underscores removed and the start of every word, is capitalised, except the first word which is always lower case. Issue: ```py from pydantic.utils import to_camel valid_pascal = "PascalCase" valid_camel = "camelCase" example = to_camel("i_shouldnt_be_capitalised") assert valid_pascal == to_camel("pascal_case") assert valid_camel != to_camel("camel_case") ``` suggested fix, rename `to_camel()` -> `to_pascal()`, and write new `to_camel()` function: ```py def to_pascal(string: str) -> str: return "".join(word.capitalize() for word in string.split("_")) def to_camel(string: str) -> str: if len(string) >= 1: pascal_string = to_pascal(string) return pascal_string[0].lower() + pascal_string[1:] return string.lower() ``` Alternatively, if there is code which will break because it is dependent on the `camel_case()` function remaining pascal case, then i propose we implement a new function called `to_lower_camel()` which implements the first letter lower case variant: ```py def to_camel(string: str) -> str: return "".join(word.capitalize() for word in string.split("_")) def to_lower_camel(string: str) -> str: if len(string) >= 1: pascal_string = to_camel(string) return pascal_string[0].lower() + pascal_string[1:] return string.lower() ```
0.0
5885e6ce12fbb931301b1de922c0eff30db292c1
[ "tests/test_utils.py::test_import_module", "tests/test_utils.py::test_import_module_invalid", "tests/test_utils.py::test_import_no_attr", "tests/test_utils.py::test_display_as_type[str-str]", "tests/test_utils.py::test_display_as_type[string-str]", "tests/test_utils.py::test_display_as_type[value2-Union[str,", "tests/test_utils.py::test_display_as_type[list-list]", "tests/test_utils.py::test_lenient_issubclass", "tests/test_utils.py::test_lenient_issubclass_is_lenient", "tests/test_utils.py::test_truncate[object-<class", "tests/test_utils.py::test_truncate[abcdefghijklmnopqrstuvwxyz-'abcdefghijklmnopq\\u2026']", "tests/test_utils.py::test_truncate[input_value2-[0,", "tests/test_utils.py::test_unique_list[input_value0-output0]", "tests/test_utils.py::test_unique_list[input_value1-output1]", "tests/test_utils.py::test_unique_list[input_value2-output2]", "tests/test_utils.py::test_value_items", "tests/test_utils.py::test_value_items_merge[base0-override0-False-expected0]", "tests/test_utils.py::test_value_items_merge[None-None-False-None]", "tests/test_utils.py::test_value_items_merge[base2-override2-False-expected2]", "tests/test_utils.py::test_value_items_merge[base3-None-False-expected3]", "tests/test_utils.py::test_value_items_merge[None-override4-False-expected4]", "tests/test_utils.py::test_value_items_merge[None-override5-False-expected5]", "tests/test_utils.py::test_value_items_merge[base6-None-False-expected6]", "tests/test_utils.py::test_value_items_merge[base7-override7-False-expected7]", "tests/test_utils.py::test_value_items_merge[base8-override8-False-expected8]", "tests/test_utils.py::test_value_items_merge[base9-override9-False-expected9]", "tests/test_utils.py::test_value_items_merge[base10-override10-False-expected10]", "tests/test_utils.py::test_value_items_merge[base11-override11-False-expected11]", "tests/test_utils.py::test_value_items_merge[base12-override12-False-expected12]", "tests/test_utils.py::test_value_items_merge[base13-override13-False-expected13]", "tests/test_utils.py::test_value_items_merge[base14-override14-False-expected14]", "tests/test_utils.py::test_value_items_merge[base15-override15-False-expected15]", "tests/test_utils.py::test_value_items_merge[base16-override16-True-expected16]", "tests/test_utils.py::test_value_items_merge[None-None-True-None]", "tests/test_utils.py::test_value_items_merge[base18-override18-True-expected18]", "tests/test_utils.py::test_value_items_merge[base19-None-True-expected19]", "tests/test_utils.py::test_value_items_merge[None-override20-True-expected20]", "tests/test_utils.py::test_value_items_merge[None-override21-True-expected21]", "tests/test_utils.py::test_value_items_merge[base22-None-True-expected22]", "tests/test_utils.py::test_value_items_merge[base23-override23-True-expected23]", "tests/test_utils.py::test_value_items_merge[base24-override24-True-expected24]", "tests/test_utils.py::test_value_items_merge[base25-override25-True-expected25]", "tests/test_utils.py::test_value_items_merge[base26-override26-True-expected26]", "tests/test_utils.py::test_value_items_merge[base27-override27-True-expected27]", "tests/test_utils.py::test_value_items_merge[base28-override28-True-expected28]", "tests/test_utils.py::test_value_items_merge[base29-override29-True-expected29]", "tests/test_utils.py::test_value_items_merge[base30-override30-True-expected30]", "tests/test_utils.py::test_value_items_merge[base31-override31-True-expected31]", "tests/test_utils.py::test_value_items_merge[base32-True-False-True]", "tests/test_utils.py::test_value_items_merge[True-override33-False-expected33]", "tests/test_utils.py::test_value_items_merge[True-None-False-True]", "tests/test_utils.py::test_value_items_merge[base35-override35-False-expected35]", "tests/test_utils.py::test_value_items_error", "tests/test_utils.py::test_is_new_type", "tests/test_utils.py::test_new_type_supertype", "tests/test_utils.py::test_pretty", "tests/test_utils.py::test_pretty_color", "tests/test_utils.py::test_devtools_output", "tests/test_utils.py::test_devtools_output_validation_error", "tests/test_utils.py::test_deep_update[mapping0-updating_mapping0-expected_mapping0-extra", "tests/test_utils.py::test_deep_update[mapping1-updating_mapping1-expected_mapping1-values", "tests/test_utils.py::test_deep_update[mapping2-updating_mapping2-expected_mapping2-values", "tests/test_utils.py::test_deep_update[mapping3-updating_mapping3-expected_mapping3-deeply", "tests/test_utils.py::test_deep_update_is_not_mutating", "tests/test_utils.py::test_undefined_repr", "tests/test_utils.py::test_undefined_copy", "tests/test_utils.py::test_get_model", "tests/test_utils.py::test_version_info", "tests/test_utils.py::test_standard_version", "tests/test_utils.py::test_class_attribute", "tests/test_utils.py::test_all_literal_values", "tests/test_utils.py::test_path_type", "tests/test_utils.py::test_path_type_unknown", "tests/test_utils.py::test_smart_deepcopy_immutable_non_sequence[10]", "tests/test_utils.py::test_smart_deepcopy_immutable_non_sequence[1.0]", "tests/test_utils.py::test_smart_deepcopy_immutable_non_sequence[11]", "tests/test_utils.py::test_smart_deepcopy_immutable_non_sequence[12]", "tests/test_utils.py::test_smart_deepcopy_immutable_non_sequence[int]", "tests/test_utils.py::test_smart_deepcopy_immutable_non_sequence[None]", "tests/test_utils.py::test_smart_deepcopy_immutable_non_sequence[test_all_literal_values]", "tests/test_utils.py::test_smart_deepcopy_immutable_non_sequence[len]", "tests/test_utils.py::test_smart_deepcopy_immutable_non_sequence[obj8]", "tests/test_utils.py::test_smart_deepcopy_immutable_non_sequence[<lambda>]", "tests/test_utils.py::test_smart_deepcopy_immutable_non_sequence[obj10]", "tests/test_utils.py::test_smart_deepcopy_empty_collection[empty_collection0]", "tests/test_utils.py::test_smart_deepcopy_empty_collection[empty_collection1]", "tests/test_utils.py::test_smart_deepcopy_empty_collection[empty_collection2]", "tests/test_utils.py::test_smart_deepcopy_empty_collection[empty_collection3]", "tests/test_utils.py::test_smart_deepcopy_empty_collection[empty_collection4]", "tests/test_utils.py::test_smart_deepcopy_empty_collection[empty_collection5]", "tests/test_utils.py::test_smart_deepcopy_empty_collection[empty_collection6]", "tests/test_utils.py::test_smart_deepcopy_empty_collection[empty_collection7]", "tests/test_utils.py::test_smart_deepcopy_collection[collection0]", "tests/test_utils.py::test_smart_deepcopy_collection[collection1]", "tests/test_utils.py::test_smart_deepcopy_collection[collection2]", "tests/test_utils.py::test_smart_deepcopy_collection[collection3]", "tests/test_utils.py::test_smart_deepcopy_collection[collection4]", "tests/test_utils.py::test_smart_deepcopy_collection[collection5]", "tests/test_utils.py::test_smart_deepcopy_collection[collection6]", "tests/test_utils.py::test_smart_deepcopy_collection[collection7]", "tests/test_utils.py::test_get_origin[input_value0-Annotated]", "tests/test_utils.py::test_get_origin[input_value1-Callable]", "tests/test_utils.py::test_get_origin[input_value2-dict]", "tests/test_utils.py::test_get_origin[input_value3-list]", "tests/test_utils.py::test_get_origin[input_value4-output_value4]", "tests/test_utils.py::test_get_origin[int-None]", "tests/test_utils.py::test_resolve_annotations_no_module", "tests/test_utils.py::test_all_identical", "tests/test_utils.py::test_undefined_pickle", "tests/test_utils.py::test_on_lower_camel_zero_length", "tests/test_utils.py::test_on_lower_camel_one_length", "tests/test_utils.py::test_on_lower_camel_many_length", "tests/test_utils.py::test_limited_dict" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2021-12-02 06:28:33+00:00
mit
4,844
pydantic__pydantic-3543
diff --git a/pydantic/fields.py b/pydantic/fields.py --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -50,6 +50,7 @@ ValueItems, get_discriminator_alias_and_values, get_unique_discriminator_alias, + lenient_isinstance, lenient_issubclass, sequence_like, smart_deepcopy, @@ -1048,7 +1049,7 @@ def _validate_singleton( return v, None except TypeError: # compound type - if isinstance(v, get_origin(field.outer_type_)): + if lenient_isinstance(v, get_origin(field.outer_type_)): value, error = field.validate(v, values, loc=loc, cls=cls) if not error: return value, None diff --git a/pydantic/utils.py b/pydantic/utils.py --- a/pydantic/utils.py +++ b/pydantic/utils.py @@ -53,6 +53,7 @@ 'import_string', 'sequence_like', 'validate_field_name', + 'lenient_isinstance', 'lenient_issubclass', 'in_ipython', 'deep_update', @@ -163,6 +164,13 @@ def validate_field_name(bases: List[Type['BaseModel']], field_name: str) -> None ) +def lenient_isinstance(o: Any, class_or_tuple: Union[Type[Any], Tuple[Type[Any], ...]]) -> bool: + try: + return isinstance(o, class_or_tuple) + except TypeError: + return False + + def lenient_issubclass(cls: Any, class_or_tuple: Union[Type[Any], Tuple[Type[Any], ...]]) -> bool: try: return isinstance(cls, type) and issubclass(cls, class_or_tuple)
pydantic/pydantic
c532e8324e0a68fcecb239b02d66b55df7d9c684
diff --git a/tests/test_types.py b/tests/test_types.py --- a/tests/test_types.py +++ b/tests/test_types.py @@ -27,7 +27,7 @@ from uuid import UUID import pytest -from typing_extensions import Literal +from typing_extensions import Literal, TypedDict from pydantic import ( UUID1, @@ -3120,6 +3120,22 @@ class Model(BaseModel, smart_union=True): assert Model(x=[1, '2']).x == ['1', '2'] +def test_smart_union_typeddict(): + class Dict1(TypedDict): + foo: str + + class Dict2(TypedDict): + bar: str + + class M(BaseModel): + d: Union[Dict2, Dict1] + + class Config: + smart_union = True + + assert M(d=dict(foo='baz')).d == {'foo': 'baz'} + + @pytest.mark.parametrize( 'value,result', (
`Config.smart_union` doesn't work with `TypedDict` ### Checks * [x] I added a descriptive title to this issue * [x] I have searched (google, github) for similar issues and couldn't find anything * [x] I have read and followed [the docs](https://pydantic-docs.helpmanual.io/) and still think this is a bug <!-- Sorry to sound so draconian, but every second saved replying to issues is time spend improving pydantic :-) --> # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.9.0a1 pydantic compiled: False python version: 3.10.0 (tags/v3.10.0:b494f59, Oct 4 2021, 19:00:18) [MSC v.1929 64 bit (AMD64)] platform: Windows-10-10.0.22000-SP0 optional deps. installed: ['typing-extensions'] ``` <!-- or if you're using pydantic prior to v1.3, manually include: OS, python version and pydantic version --> <!-- Please read the [docs](https://pydantic-docs.helpmanual.io/) and search through issues to confirm your bug hasn't already been reported. --> <!-- Where possible please include a self-contained code snippet describing your bug: --> ```py class Dict1(TypedDict): foo: str class Dict2(TypedDict): bar: str class M(BaseModel): d: Union[Dict2, Dict1] class Config: smart_union = True M(d=dict(foo='baz')) # raises TypeError: isinstance() arg 2 must be a type, a tuple of types, or a union ```
0.0
c532e8324e0a68fcecb239b02d66b55df7d9c684
[ "tests/test_types.py::test_smart_union_typeddict" ]
[ "tests/test_types.py::test_constrained_bytes_good", "tests/test_types.py::test_constrained_bytes_default", "tests/test_types.py::test_constrained_bytes_too_long", "tests/test_types.py::test_constrained_bytes_lower_enabled", "tests/test_types.py::test_constrained_bytes_lower_disabled", "tests/test_types.py::test_constrained_bytes_strict_true", "tests/test_types.py::test_constrained_bytes_strict_false", "tests/test_types.py::test_constrained_bytes_strict_default", "tests/test_types.py::test_constrained_list_good", "tests/test_types.py::test_constrained_list_default", "tests/test_types.py::test_constrained_list_too_long", "tests/test_types.py::test_constrained_list_too_short", "tests/test_types.py::test_constrained_list_not_unique_hashable_items", "tests/test_types.py::test_constrained_list_not_unique_unhashable_items", "tests/test_types.py::test_constrained_list_optional", "tests/test_types.py::test_constrained_list_constraints", "tests/test_types.py::test_constrained_list_item_type_fails", "tests/test_types.py::test_conlist", "tests/test_types.py::test_conlist_wrong_type_default", "tests/test_types.py::test_constrained_set_good", "tests/test_types.py::test_constrained_set_default", "tests/test_types.py::test_constrained_set_default_invalid", "tests/test_types.py::test_constrained_set_too_long", "tests/test_types.py::test_constrained_set_too_short", "tests/test_types.py::test_constrained_set_optional", "tests/test_types.py::test_constrained_set_constraints", "tests/test_types.py::test_constrained_set_item_type_fails", "tests/test_types.py::test_conset", "tests/test_types.py::test_conset_not_required", "tests/test_types.py::test_confrozenset", "tests/test_types.py::test_confrozenset_not_required", "tests/test_types.py::test_constrained_frozenset_optional", "tests/test_types.py::test_constrained_str_good", "tests/test_types.py::test_constrained_str_default", "tests/test_types.py::test_constrained_str_too_long", "tests/test_types.py::test_constrained_str_lower_enabled", "tests/test_types.py::test_constrained_str_lower_disabled", "tests/test_types.py::test_constrained_str_max_length_0", "tests/test_types.py::test_module_import", "tests/test_types.py::test_pyobject_none", "tests/test_types.py::test_pyobject_callable", "tests/test_types.py::test_default_validators[bool_check-True-True0]", "tests/test_types.py::test_default_validators[bool_check-1-True0]", "tests/test_types.py::test_default_validators[bool_check-y-True]", "tests/test_types.py::test_default_validators[bool_check-Y-True]", "tests/test_types.py::test_default_validators[bool_check-yes-True]", "tests/test_types.py::test_default_validators[bool_check-Yes-True]", "tests/test_types.py::test_default_validators[bool_check-YES-True]", "tests/test_types.py::test_default_validators[bool_check-true-True]", "tests/test_types.py::test_default_validators[bool_check-True-True1]", "tests/test_types.py::test_default_validators[bool_check-TRUE-True0]", "tests/test_types.py::test_default_validators[bool_check-on-True]", "tests/test_types.py::test_default_validators[bool_check-On-True]", "tests/test_types.py::test_default_validators[bool_check-ON-True]", "tests/test_types.py::test_default_validators[bool_check-1-True1]", "tests/test_types.py::test_default_validators[bool_check-t-True]", "tests/test_types.py::test_default_validators[bool_check-T-True]", "tests/test_types.py::test_default_validators[bool_check-TRUE-True1]", "tests/test_types.py::test_default_validators[bool_check-False-False0]", "tests/test_types.py::test_default_validators[bool_check-0-False0]", "tests/test_types.py::test_default_validators[bool_check-n-False]", "tests/test_types.py::test_default_validators[bool_check-N-False]", "tests/test_types.py::test_default_validators[bool_check-no-False]", "tests/test_types.py::test_default_validators[bool_check-No-False]", "tests/test_types.py::test_default_validators[bool_check-NO-False]", "tests/test_types.py::test_default_validators[bool_check-false-False]", "tests/test_types.py::test_default_validators[bool_check-False-False1]", "tests/test_types.py::test_default_validators[bool_check-FALSE-False0]", "tests/test_types.py::test_default_validators[bool_check-off-False]", "tests/test_types.py::test_default_validators[bool_check-Off-False]", "tests/test_types.py::test_default_validators[bool_check-OFF-False]", "tests/test_types.py::test_default_validators[bool_check-0-False1]", "tests/test_types.py::test_default_validators[bool_check-f-False]", "tests/test_types.py::test_default_validators[bool_check-F-False]", "tests/test_types.py::test_default_validators[bool_check-FALSE-False1]", "tests/test_types.py::test_default_validators[bool_check-None-ValidationError]", "tests/test_types.py::test_default_validators[bool_check--ValidationError]", "tests/test_types.py::test_default_validators[bool_check-value36-ValidationError]", "tests/test_types.py::test_default_validators[bool_check-value37-ValidationError]", "tests/test_types.py::test_default_validators[bool_check-value38-ValidationError]", "tests/test_types.py::test_default_validators[bool_check-value39-ValidationError]", "tests/test_types.py::test_default_validators[bool_check-2-ValidationError0]", "tests/test_types.py::test_default_validators[bool_check-2-ValidationError1]", "tests/test_types.py::test_default_validators[bool_check-2-ValidationError2]", "tests/test_types.py::test_default_validators[bool_check-\\x81-ValidationError]", "tests/test_types.py::test_default_validators[bool_check-value44-ValidationError]", "tests/test_types.py::test_default_validators[str_check-s-s0]", "tests/test_types.py::test_default_validators[str_check-", "tests/test_types.py::test_default_validators[str_check-s-s1]", "tests/test_types.py::test_default_validators[str_check-1-1]", "tests/test_types.py::test_default_validators[str_check-xxxxxxxxxxx-ValidationError0]", "tests/test_types.py::test_default_validators[str_check-xxxxxxxxxxx-ValidationError1]", "tests/test_types.py::test_default_validators[bytes_check-s-s0]", "tests/test_types.py::test_default_validators[bytes_check-", "tests/test_types.py::test_default_validators[bytes_check-s-s1]", "tests/test_types.py::test_default_validators[bytes_check-1-1]", "tests/test_types.py::test_default_validators[bytes_check-value57-xx]", "tests/test_types.py::test_default_validators[bytes_check-True-True]", "tests/test_types.py::test_default_validators[bytes_check-False-False]", "tests/test_types.py::test_default_validators[bytes_check-value60-ValidationError]", "tests/test_types.py::test_default_validators[bytes_check-xxxxxxxxxxx-ValidationError0]", "tests/test_types.py::test_default_validators[bytes_check-xxxxxxxxxxx-ValidationError1]", "tests/test_types.py::test_default_validators[int_check-1-10]", "tests/test_types.py::test_default_validators[int_check-1.9-1]", "tests/test_types.py::test_default_validators[int_check-1-11]", "tests/test_types.py::test_default_validators[int_check-1.9-ValidationError]", "tests/test_types.py::test_default_validators[int_check-1-12]", "tests/test_types.py::test_default_validators[int_check-12-120]", "tests/test_types.py::test_default_validators[int_check-12-121]", "tests/test_types.py::test_default_validators[int_check-12-122]", "tests/test_types.py::test_default_validators[float_check-1-1.00]", "tests/test_types.py::test_default_validators[float_check-1.0-1.00]", "tests/test_types.py::test_default_validators[float_check-1.0-1.01]", "tests/test_types.py::test_default_validators[float_check-1-1.01]", "tests/test_types.py::test_default_validators[float_check-1.0-1.02]", "tests/test_types.py::test_default_validators[float_check-1-1.02]", "tests/test_types.py::test_default_validators[uuid_check-ebcdab58-6eb8-46fb-a190-d07a33e9eac8-result77]", "tests/test_types.py::test_default_validators[uuid_check-value78-result78]", "tests/test_types.py::test_default_validators[uuid_check-ebcdab58-6eb8-46fb-a190-d07a33e9eac8-result79]", "tests/test_types.py::test_default_validators[uuid_check-\\x124Vx\\x124Vx\\x124Vx\\x124Vx-result80]", "tests/test_types.py::test_default_validators[uuid_check-ebcdab58-6eb8-46fb-a190--ValidationError]", "tests/test_types.py::test_default_validators[uuid_check-123-ValidationError]", "tests/test_types.py::test_default_validators[decimal_check-42.24-result83]", "tests/test_types.py::test_default_validators[decimal_check-42.24-result84]", "tests/test_types.py::test_default_validators[decimal_check-42.24-result85]", "tests/test_types.py::test_default_validators[decimal_check-", "tests/test_types.py::test_default_validators[decimal_check-value87-result87]", "tests/test_types.py::test_default_validators[decimal_check-not", "tests/test_types.py::test_default_validators[decimal_check-NaN-ValidationError]", "tests/test_types.py::test_string_too_long", "tests/test_types.py::test_string_too_short", "tests/test_types.py::test_datetime_successful", "tests/test_types.py::test_datetime_errors", "tests/test_types.py::test_enum_successful", "tests/test_types.py::test_enum_fails", "tests/test_types.py::test_int_enum_successful_for_str_int", "tests/test_types.py::test_enum_type", "tests/test_types.py::test_int_enum_type", "tests/test_types.py::test_string_success", "tests/test_types.py::test_string_fails", "tests/test_types.py::test_dict", "tests/test_types.py::test_list_success[value0-result0]", "tests/test_types.py::test_list_success[value1-result1]", "tests/test_types.py::test_list_success[value2-result2]", "tests/test_types.py::test_list_success[<genexpr>-result3]", "tests/test_types.py::test_list_success[value4-result4]", "tests/test_types.py::test_list_fails[1230]", "tests/test_types.py::test_list_fails[1231]", "tests/test_types.py::test_ordered_dict", "tests/test_types.py::test_tuple_success[value0-result0]", "tests/test_types.py::test_tuple_success[value1-result1]", "tests/test_types.py::test_tuple_success[value2-result2]", "tests/test_types.py::test_tuple_success[<genexpr>-result3]", "tests/test_types.py::test_tuple_success[value4-result4]", "tests/test_types.py::test_tuple_fails[1230]", "tests/test_types.py::test_tuple_fails[1231]", "tests/test_types.py::test_tuple_variable_len_success[value0-int-result0]", "tests/test_types.py::test_tuple_variable_len_success[value1-int-result1]", "tests/test_types.py::test_tuple_variable_len_success[<genexpr>-int-result2]", "tests/test_types.py::test_tuple_variable_len_success[value3-str-result3]", "tests/test_types.py::test_tuple_variable_len_fails[value0-str-exc0]", "tests/test_types.py::test_tuple_variable_len_fails[value1-str-exc1]", "tests/test_types.py::test_set_success[value0-result0]", "tests/test_types.py::test_set_success[value1-result1]", "tests/test_types.py::test_set_success[value2-result2]", "tests/test_types.py::test_set_success[value3-result3]", "tests/test_types.py::test_set_fails[1230]", "tests/test_types.py::test_set_fails[1231]", "tests/test_types.py::test_list_type_fails", "tests/test_types.py::test_set_type_fails", "tests/test_types.py::test_sequence_success[int-value0-result0]", "tests/test_types.py::test_sequence_success[int-value1-result1]", "tests/test_types.py::test_sequence_success[int-value2-result2]", "tests/test_types.py::test_sequence_success[float-value3-result3]", "tests/test_types.py::test_sequence_success[cls4-value4-result4]", "tests/test_types.py::test_sequence_success[cls5-value5-result5]", "tests/test_types.py::test_sequence_generator_success[int-<genexpr>-result0]", "tests/test_types.py::test_sequence_generator_success[float-<genexpr>-result1]", "tests/test_types.py::test_sequence_generator_success[str-<genexpr>-result2]", "tests/test_types.py::test_infinite_iterable", "tests/test_types.py::test_invalid_iterable", "tests/test_types.py::test_infinite_iterable_validate_first", "tests/test_types.py::test_sequence_generator_fails[int-<genexpr>-errors0]", "tests/test_types.py::test_sequence_generator_fails[float-<genexpr>-errors1]", "tests/test_types.py::test_sequence_fails[int-value0-errors0]", "tests/test_types.py::test_sequence_fails[int-value1-errors1]", "tests/test_types.py::test_sequence_fails[float-value2-errors2]", "tests/test_types.py::test_sequence_fails[float-value3-errors3]", "tests/test_types.py::test_sequence_fails[float-value4-errors4]", "tests/test_types.py::test_sequence_fails[cls5-value5-errors5]", "tests/test_types.py::test_sequence_fails[cls6-value6-errors6]", "tests/test_types.py::test_sequence_fails[cls7-value7-errors7]", "tests/test_types.py::test_int_validation", "tests/test_types.py::test_float_validation", "tests/test_types.py::test_strict_bytes", "tests/test_types.py::test_strict_bytes_subclass", "tests/test_types.py::test_strict_str", "tests/test_types.py::test_strict_str_subclass", "tests/test_types.py::test_strict_bool", "tests/test_types.py::test_strict_int", "tests/test_types.py::test_strict_int_subclass", "tests/test_types.py::test_strict_float", "tests/test_types.py::test_strict_float_subclass", "tests/test_types.py::test_bool_unhashable_fails", "tests/test_types.py::test_uuid_error", "tests/test_types.py::test_uuid_validation", "tests/test_types.py::test_anystr_strip_whitespace_enabled", "tests/test_types.py::test_anystr_strip_whitespace_disabled", "tests/test_types.py::test_anystr_lower_enabled", "tests/test_types.py::test_anystr_lower_disabled", "tests/test_types.py::test_decimal_validation[type_args0-value0-result0]", "tests/test_types.py::test_decimal_validation[type_args1-value1-result1]", "tests/test_types.py::test_decimal_validation[type_args2-value2-result2]", "tests/test_types.py::test_decimal_validation[type_args3-value3-result3]", "tests/test_types.py::test_decimal_validation[type_args4-value4-result4]", "tests/test_types.py::test_decimal_validation[type_args5-value5-result5]", "tests/test_types.py::test_decimal_validation[type_args6-value6-result6]", "tests/test_types.py::test_decimal_validation[type_args7-value7-result7]", "tests/test_types.py::test_decimal_validation[type_args8-value8-result8]", "tests/test_types.py::test_decimal_validation[type_args9-value9-result9]", "tests/test_types.py::test_decimal_validation[type_args10-value10-result10]", "tests/test_types.py::test_decimal_validation[type_args11-value11-result11]", "tests/test_types.py::test_decimal_validation[type_args12-value12-result12]", "tests/test_types.py::test_decimal_validation[type_args13-value13-result13]", "tests/test_types.py::test_decimal_validation[type_args14-value14-result14]", "tests/test_types.py::test_decimal_validation[type_args15-value15-result15]", "tests/test_types.py::test_decimal_validation[type_args16-value16-result16]", "tests/test_types.py::test_decimal_validation[type_args17-value17-result17]", "tests/test_types.py::test_decimal_validation[type_args18-value18-result18]", "tests/test_types.py::test_decimal_validation[type_args19-value19-result19]", "tests/test_types.py::test_decimal_validation[type_args20-value20-result20]", "tests/test_types.py::test_decimal_validation[type_args21-NaN-result21]", "tests/test_types.py::test_decimal_validation[type_args22--NaN-result22]", "tests/test_types.py::test_decimal_validation[type_args23-+NaN-result23]", "tests/test_types.py::test_decimal_validation[type_args24-sNaN-result24]", "tests/test_types.py::test_decimal_validation[type_args25--sNaN-result25]", "tests/test_types.py::test_decimal_validation[type_args26-+sNaN-result26]", "tests/test_types.py::test_decimal_validation[type_args27-Inf-result27]", "tests/test_types.py::test_decimal_validation[type_args28--Inf-result28]", "tests/test_types.py::test_decimal_validation[type_args29-+Inf-result29]", "tests/test_types.py::test_decimal_validation[type_args30-Infinity-result30]", "tests/test_types.py::test_decimal_validation[type_args31--Infinity-result31]", "tests/test_types.py::test_decimal_validation[type_args32--Infinity-result32]", "tests/test_types.py::test_decimal_validation[type_args33-value33-result33]", "tests/test_types.py::test_decimal_validation[type_args34-value34-result34]", "tests/test_types.py::test_decimal_validation[type_args35-value35-result35]", "tests/test_types.py::test_decimal_validation[type_args36-value36-result36]", "tests/test_types.py::test_decimal_validation[type_args37-value37-result37]", "tests/test_types.py::test_decimal_validation[type_args38-value38-result38]", "tests/test_types.py::test_decimal_validation[type_args39-value39-result39]", "tests/test_types.py::test_decimal_validation[type_args40-value40-result40]", "tests/test_types.py::test_decimal_validation[type_args41-value41-result41]", "tests/test_types.py::test_decimal_validation[type_args42-value42-result42]", "tests/test_types.py::test_decimal_validation[type_args43-value43-result43]", "tests/test_types.py::test_decimal_validation[type_args44-value44-result44]", "tests/test_types.py::test_decimal_validation[type_args45-value45-result45]", "tests/test_types.py::test_path_validation_success[/test/path-result0]", "tests/test_types.py::test_path_validation_success[value1-result1]", "tests/test_types.py::test_path_validation_fails", "tests/test_types.py::test_file_path_validation_success[tests/test_types.py-result0]", "tests/test_types.py::test_file_path_validation_success[value1-result1]", "tests/test_types.py::test_file_path_validation_fails[nonexistentfile-errors0]", "tests/test_types.py::test_file_path_validation_fails[value1-errors1]", "tests/test_types.py::test_file_path_validation_fails[tests-errors2]", "tests/test_types.py::test_file_path_validation_fails[value3-errors3]", "tests/test_types.py::test_directory_path_validation_success[tests-result0]", "tests/test_types.py::test_directory_path_validation_success[value1-result1]", "tests/test_types.py::test_directory_path_validation_fails[nonexistentdirectory-errors0]", "tests/test_types.py::test_directory_path_validation_fails[value1-errors1]", "tests/test_types.py::test_directory_path_validation_fails[tests/test_types.py-errors2]", "tests/test_types.py::test_directory_path_validation_fails[value3-errors3]", "tests/test_types.py::test_number_gt", "tests/test_types.py::test_number_ge", "tests/test_types.py::test_number_lt", "tests/test_types.py::test_number_le", "tests/test_types.py::test_number_multiple_of_int_valid[10]", "tests/test_types.py::test_number_multiple_of_int_valid[100]", "tests/test_types.py::test_number_multiple_of_int_valid[20]", "tests/test_types.py::test_number_multiple_of_int_invalid[1337]", "tests/test_types.py::test_number_multiple_of_int_invalid[23]", "tests/test_types.py::test_number_multiple_of_int_invalid[6]", "tests/test_types.py::test_number_multiple_of_int_invalid[14]", "tests/test_types.py::test_number_multiple_of_float_valid[0.2]", "tests/test_types.py::test_number_multiple_of_float_valid[0.3]", "tests/test_types.py::test_number_multiple_of_float_valid[0.4]", "tests/test_types.py::test_number_multiple_of_float_valid[0.5]", "tests/test_types.py::test_number_multiple_of_float_valid[1]", "tests/test_types.py::test_number_multiple_of_float_invalid[0.07]", "tests/test_types.py::test_number_multiple_of_float_invalid[1.27]", "tests/test_types.py::test_number_multiple_of_float_invalid[1.003]", "tests/test_types.py::test_bounds_config_exceptions[conint]", "tests/test_types.py::test_bounds_config_exceptions[confloat]", "tests/test_types.py::test_bounds_config_exceptions[condecimal]", "tests/test_types.py::test_new_type_success", "tests/test_types.py::test_new_type_fails", "tests/test_types.py::test_valid_simple_json", "tests/test_types.py::test_invalid_simple_json", "tests/test_types.py::test_valid_simple_json_bytes", "tests/test_types.py::test_valid_detailed_json", "tests/test_types.py::test_invalid_detailed_json_value_error", "tests/test_types.py::test_valid_detailed_json_bytes", "tests/test_types.py::test_invalid_detailed_json_type_error", "tests/test_types.py::test_json_not_str", "tests/test_types.py::test_json_pre_validator", "tests/test_types.py::test_json_optional_simple", "tests/test_types.py::test_json_optional_complex", "tests/test_types.py::test_json_explicitly_required", "tests/test_types.py::test_json_no_default", "tests/test_types.py::test_pattern", "tests/test_types.py::test_pattern_error", "tests/test_types.py::test_secretstr", "tests/test_types.py::test_secretstr_equality", "tests/test_types.py::test_secretstr_idempotent", "tests/test_types.py::test_secretstr_error", "tests/test_types.py::test_secretstr_min_max_length", "tests/test_types.py::test_secretbytes", "tests/test_types.py::test_secretbytes_equality", "tests/test_types.py::test_secretbytes_idempotent", "tests/test_types.py::test_secretbytes_error", "tests/test_types.py::test_secretbytes_min_max_length", "tests/test_types.py::test_secrets_schema[no-constrains-SecretStr]", "tests/test_types.py::test_secrets_schema[no-constrains-SecretBytes]", "tests/test_types.py::test_secrets_schema[min-constraint-SecretStr]", "tests/test_types.py::test_secrets_schema[min-constraint-SecretBytes]", "tests/test_types.py::test_secrets_schema[max-constraint-SecretStr]", "tests/test_types.py::test_secrets_schema[max-constraint-SecretBytes]", "tests/test_types.py::test_secrets_schema[min-max-constraints-SecretStr]", "tests/test_types.py::test_secrets_schema[min-max-constraints-SecretBytes]", "tests/test_types.py::test_generic_without_params", "tests/test_types.py::test_generic_without_params_error", "tests/test_types.py::test_literal_single", "tests/test_types.py::test_literal_multiple", "tests/test_types.py::test_unsupported_field_type", "tests/test_types.py::test_frozenset_field", "tests/test_types.py::test_frozenset_field_conversion[value0-result0]", "tests/test_types.py::test_frozenset_field_conversion[value1-result1]", "tests/test_types.py::test_frozenset_field_conversion[value2-result2]", "tests/test_types.py::test_frozenset_field_conversion[value3-result3]", "tests/test_types.py::test_frozenset_field_not_convertible", "tests/test_types.py::test_bytesize_conversions[1-1-1.0B-1.0B]", "tests/test_types.py::test_bytesize_conversions[1.0-1-1.0B-1.0B]", "tests/test_types.py::test_bytesize_conversions[1b-1-1.0B-1.0B]", "tests/test_types.py::test_bytesize_conversions[1.5", "tests/test_types.py::test_bytesize_conversions[5.1kib-5222-5.1KiB-5.2KB]", "tests/test_types.py::test_bytesize_conversions[6.2EiB-7148113328562451456-6.2EiB-7.1EB]", "tests/test_types.py::test_bytesize_to", "tests/test_types.py::test_bytesize_raises", "tests/test_types.py::test_deque_success", "tests/test_types.py::test_deque_generic_success[int-value0-result0]", "tests/test_types.py::test_deque_generic_success[int-value1-result1]", "tests/test_types.py::test_deque_generic_success[int-value2-result2]", "tests/test_types.py::test_deque_generic_success[float-value3-result3]", "tests/test_types.py::test_deque_generic_success[cls4-value4-result4]", "tests/test_types.py::test_deque_generic_success[cls5-value5-result5]", "tests/test_types.py::test_deque_generic_success[str-value6-result6]", "tests/test_types.py::test_deque_generic_success[int-value7-result7]", "tests/test_types.py::test_deque_fails[int-value0-errors0]", "tests/test_types.py::test_deque_fails[int-value1-errors1]", "tests/test_types.py::test_deque_fails[float-value2-errors2]", "tests/test_types.py::test_deque_fails[float-value3-errors3]", "tests/test_types.py::test_deque_fails[float-value4-errors4]", "tests/test_types.py::test_deque_fails[cls5-value5-errors5]", "tests/test_types.py::test_deque_fails[cls6-value6-errors6]", "tests/test_types.py::test_deque_fails[cls7-value7-errors7]", "tests/test_types.py::test_deque_model", "tests/test_types.py::test_deque_json", "tests/test_types.py::test_none[None]", "tests/test_types.py::test_none[NoneType0]", "tests/test_types.py::test_none[NoneType1]", "tests/test_types.py::test_none[value_type3]", "tests/test_types.py::test_default_union_types", "tests/test_types.py::test_smart_union_types", "tests/test_types.py::test_default_union_class", "tests/test_types.py::test_smart_union_class", "tests/test_types.py::test_default_union_subclass", "tests/test_types.py::test_smart_union_subclass", "tests/test_types.py::test_default_union_compound_types", "tests/test_types.py::test_smart_union_compound_types", "tests/test_types.py::test_smart_union_compouned_types_edge_case", "tests/test_types.py::test_past_date_validation_success[1996-01-22-result0]", "tests/test_types.py::test_past_date_validation_success[value1-result1]", "tests/test_types.py::test_past_date_validation_fails[value0]", "tests/test_types.py::test_past_date_validation_fails[value1]", "tests/test_types.py::test_past_date_validation_fails[value2]", "tests/test_types.py::test_past_date_validation_fails[value3]", "tests/test_types.py::test_past_date_validation_fails[2064-06-01]", "tests/test_types.py::test_future_date_validation_success[value0-result0]", "tests/test_types.py::test_future_date_validation_success[value1-result1]", "tests/test_types.py::test_future_date_validation_success[2064-06-01-result2]", "tests/test_types.py::test_future_date_validation_fails[value0]", "tests/test_types.py::test_future_date_validation_fails[value1]", "tests/test_types.py::test_future_date_validation_fails[value2]", "tests/test_types.py::test_future_date_validation_fails[value3]", "tests/test_types.py::test_future_date_validation_fails[1996-01-22]" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-12-19 17:52:20+00:00
mit
4,845
pydantic__pydantic-3547
diff --git a/docs/examples/schema_ad_hoc.py b/docs/examples/schema_ad_hoc.py --- a/docs/examples/schema_ad_hoc.py +++ b/docs/examples/schema_ad_hoc.py @@ -2,7 +2,7 @@ from typing_extensions import Annotated -from pydantic import BaseModel, Field, schema_json +from pydantic import BaseModel, Field, schema_json_of class Cat(BaseModel): @@ -17,4 +17,4 @@ class Dog(BaseModel): Pet = Annotated[Union[Cat, Dog], Field(discriminator='pet_type')] -print(schema_json(Pet, title='The Pet Schema', indent=2)) +print(schema_json_of(Pet, title='The Pet Schema', indent=2)) diff --git a/pydantic/__init__.py b/pydantic/__init__.py --- a/pydantic/__init__.py +++ b/pydantic/__init__.py @@ -67,8 +67,8 @@ 'parse_file_as', 'parse_obj_as', 'parse_raw_as', - 'schema', - 'schema_json', + 'schema_of', + 'schema_json_of', # types 'NoneStr', 'NoneBytes', diff --git a/pydantic/tools.py b/pydantic/tools.py --- a/pydantic/tools.py +++ b/pydantic/tools.py @@ -7,7 +7,7 @@ from .types import StrBytes from .typing import display_as_type -__all__ = ('parse_file_as', 'parse_obj_as', 'parse_raw_as', 'schema', 'schema_json') +__all__ = ('parse_file_as', 'parse_obj_as', 'parse_raw_as', 'schema_of', 'schema_json_of') NameFactory = Union[str, Callable[[Type[Any]], str]] @@ -82,11 +82,11 @@ def parse_raw_as( return parse_obj_as(type_, obj, type_name=type_name) -def schema(type_: Any, *, title: Optional[NameFactory] = None, **schema_kwargs: Any) -> 'DictStrAny': +def schema_of(type_: Any, *, title: Optional[NameFactory] = None, **schema_kwargs: Any) -> 'DictStrAny': """Generate a JSON schema (as dict) for the passed model or dynamically generated one""" return _get_parsing_type(type_, type_name=title).schema(**schema_kwargs) -def schema_json(type_: Any, *, title: Optional[NameFactory] = None, **schema_json_kwargs: Any) -> str: +def schema_json_of(type_: Any, *, title: Optional[NameFactory] = None, **schema_json_kwargs: Any) -> str: """Generate a JSON schema (as JSON) for the passed model or dynamically generated one""" return _get_parsing_type(type_, type_name=title).schema_json(**schema_json_kwargs)
pydantic/pydantic
c532e8324e0a68fcecb239b02d66b55df7d9c684
I think this issue has the following root cause: * The `pydantic/main.py` file defines a function called `schema` * The `pydantic/__init__.py` file does the import `from .main import *` As such the following import `import pydantic.schema` imports the function `schema` and not the package `schema` which also exists in the `pydantic` package. Illustration: ``` (env) [arnaud@laptop]/tmp% pip install pydantic==1.8.2 ... Successfully installed pydantic-1.8.2 (env) [arnaud@laptop]/tmp% python >>> import pydantic.schema >>> print(pydantic.schema) <module 'pydantic.schema' from '/tmp/env/lib64/python3.6/site-packages/pydantic/schema.cpython-36m-x86_64-linux-gnu.so'> (env) [arnaud@laptop]/tmp% pip install -U --pre pydantic ... Successfully installed pydantic-1.9.0a1 (env) [arnaud@laptop]/tmp% python >>> import pydantic.schema >>> print(pydantic.schema) <cyfunction schema at 0x7fccff445d50> ```
diff --git a/tests/test_tools.py b/tests/test_tools.py --- a/tests/test_tools.py +++ b/tests/test_tools.py @@ -5,7 +5,7 @@ from pydantic import BaseModel, ValidationError from pydantic.dataclasses import dataclass -from pydantic.tools import parse_file_as, parse_obj_as, parse_raw_as, schema, schema_json +from pydantic.tools import parse_file_as, parse_obj_as, parse_raw_as, schema_json_of, schema_of @pytest.mark.parametrize('obj,type_,parsed', [('1', int, 1), (['1'], List[int], [1])]) @@ -101,11 +101,11 @@ class Item(BaseModel): def test_schema(): - assert schema(Union[int, str], title='IntOrStr') == { + assert schema_of(Union[int, str], title='IntOrStr') == { 'title': 'IntOrStr', 'anyOf': [{'type': 'integer'}, {'type': 'string'}], } - assert schema_json(Union[int, str], title='IntOrStr', indent=2) == ( + assert schema_json_of(Union[int, str], title='IntOrStr', indent=2) == ( '{\n' ' "title": "IntOrStr",\n' ' "anyOf": [\n'
1.9.0a1 breaks workaround for `field_type_schema` and nullable release 1.9.0a1 breaks this work around completely: ```python .../inmanta/data/model.py", line 34, in <module> old_field_type_schema = pydantic.schema.field_type_schema AttributeError: 'cython_function_or_method' object has no attribute 'field_type_schema' ``` _Originally posted by @wouterdb in https://github.com/samuelcolvin/pydantic/issues/1270#issuecomment-997700804_
0.0
c532e8324e0a68fcecb239b02d66b55df7d9c684
[ "tests/test_tools.py::test_parse_obj[1-int-1]", "tests/test_tools.py::test_parse_obj[obj1-type_1-parsed1]", "tests/test_tools.py::test_parse_obj_as_model", "tests/test_tools.py::test_parse_obj_preserves_subclasses", "tests/test_tools.py::test_parse_obj_fails", "tests/test_tools.py::test_parsing_model_naming", "tests/test_tools.py::test_parse_as_dataclass", "tests/test_tools.py::test_parse_mapping_as", "tests/test_tools.py::test_parse_file_as", "tests/test_tools.py::test_parse_file_as_json_loads", "tests/test_tools.py::test_raw_as", "tests/test_tools.py::test_schema" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-12-20 09:55:02+00:00
mit
4,846
pydantic__pydantic-3551
diff --git a/pydantic/fields.py b/pydantic/fields.py --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -732,6 +732,10 @@ def prepare_discriminated_union_sub_fields(self) -> None: Note that this process can be aborted if a `ForwardRef` is encountered """ assert self.discriminator_key is not None + + if self.type_.__class__ is DeferredType: + return + assert self.sub_fields is not None sub_fields_mapping: Dict[str, 'ModelField'] = {} all_aliases: Set[str] = set()
pydantic/pydantic
c532e8324e0a68fcecb239b02d66b55df7d9c684
diff --git a/tests/test_discrimated_union.py b/tests/test_discrimated_union.py --- a/tests/test_discrimated_union.py +++ b/tests/test_discrimated_union.py @@ -1,12 +1,14 @@ import re +import sys from enum import Enum -from typing import Union +from typing import Generic, TypeVar, Union import pytest from typing_extensions import Annotated, Literal from pydantic import BaseModel, Field, ValidationError from pydantic.errors import ConfigError +from pydantic.generics import GenericModel def test_discriminated_union_only_union(): @@ -361,3 +363,36 @@ class Model(BaseModel): n: int assert isinstance(Model(**{'pet': {'pet_type': 'dog', 'name': 'Milou'}, 'n': 5}).pet, Dog) + + [email protected](sys.version_info < (3, 7), reason='generics only supported for python 3.7 and above') +def test_generic(): + T = TypeVar('T') + + class Success(GenericModel, Generic[T]): + type: Literal['Success'] = 'Success' + data: T + + class Failure(BaseModel): + type: Literal['Failure'] = 'Failure' + error_message: str + + class Container(GenericModel, Generic[T]): + result: Union[Success[T], Failure] = Field(discriminator='type') + + with pytest.raises(ValidationError, match="Discriminator 'type' is missing in value"): + Container[str].parse_obj({'result': {}}) + + with pytest.raises( + ValidationError, + match=re.escape("No match for discriminator 'type' and value 'Other' (allowed values: 'Success', 'Failure')"), + ): + Container[str].parse_obj({'result': {'type': 'Other'}}) + + with pytest.raises( + ValidationError, match=re.escape('Container[str]\nresult -> Success[str] -> data\n field required') + ): + Container[str].parse_obj({'result': {'type': 'Success'}}) + + # coercion is done properly + assert Container[str].parse_obj({'result': {'type': 'Success', 'data': 1}}).result.data == '1'
Field with discriminator on generic causes `AssertionError`. (1.9.0a1) # Bug When defining a Generic, with a `Field` that has descriminator, filling in the type variable of the generic class fails with an ``AssertionError``. Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.9.0a1 pydantic compiled: True install path: /home/jonathan/.pyenv/versions/3.9.5/envs/lazy-maestro/lib/python3.9/site-packages/pydantic python version: 3.9.5 (default, Jun 3 2021, 16:26:08) [GCC 9.3.0] platform: Linux-5.4.0-91-generic-x86_64-with-glibc2.31 optional deps. installed: ['dotenv', 'typing-extensions'] ``` ```py from typing import Generic, TypeVar, Union from pydantic import Field from pydantic.generics import BaseModel, GenericModel from typing_extensions import Literal _T = TypeVar("_T") class Success(GenericModel, Generic[_T]): type: Literal["Success"] = "Success" data: _T class Failure(BaseModel): type: Literal["Failure"] = "Failure" error_message: str class Container(GenericModel, Generic[_T]): result: Union[Success[_T], Failure] = Field(discriminator="type") # It's the following expresison that raises the traceback below: Container[str] ``` The error: ``` Traceback (most recent call last): File "/tmp/test.py", line 25, in <module> Container[str] File "/home/jonathan/.pyenv/versions/lazy-maestro/lib/python3.9/site-packages/pydantic/generics.py", line 95, in __class_getitem__ create_model( File "pydantic/main.py", line 959, in pydantic.main.create_model File "pydantic/main.py", line 291, in pydantic.main.ModelMetaclass.__new__ File "pydantic/main.py", line 762, in pydantic.main.BaseModel.__try_update_forward_refs__ File "pydantic/typing.py", line 477, in pydantic.typing.update_model_forward_refs literal (or one of several literals): File "pydantic/typing.py", line 456, in pydantic.typing.update_field_forward_refs parameters = tuple(_type_check(p, msg) for p in parameters) File "pydantic/fields.py", line 735, in pydantic.fields.ModelField.prepare_discriminated_union_sub_fields AssertionError ```
0.0
c532e8324e0a68fcecb239b02d66b55df7d9c684
[ "tests/test_discrimated_union.py::test_generic" ]
[ "tests/test_discrimated_union.py::test_discriminated_union_only_union", "tests/test_discrimated_union.py::test_discriminated_union_invalid_type", "tests/test_discrimated_union.py::test_discriminated_union_defined_discriminator", "tests/test_discrimated_union.py::test_discriminated_union_literal_discriminator", "tests/test_discrimated_union.py::test_discriminated_union_root_same_discriminator", "tests/test_discrimated_union.py::test_discriminated_union_validation", "tests/test_discrimated_union.py::test_discriminated_annotated_union", "tests/test_discrimated_union.py::test_discriminated_union_basemodel_instance_value", "tests/test_discrimated_union.py::test_discriminated_union_int", "tests/test_discrimated_union.py::test_discriminated_union_enum", "tests/test_discrimated_union.py::test_alias_different", "tests/test_discrimated_union.py::test_alias_same", "tests/test_discrimated_union.py::test_nested" ]
{ "failed_lite_validators": [ "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2021-12-20 17:17:45+00:00
mit
4,847
pydantic__pydantic-3594
diff --git a/pydantic/class_validators.py b/pydantic/class_validators.py --- a/pydantic/class_validators.py +++ b/pydantic/class_validators.py @@ -9,6 +9,9 @@ from .typing import AnyCallable from .utils import ROOT_KEY, in_ipython +if TYPE_CHECKING: + from .typing import AnyClassMethod + class Validator: __slots__ = 'func', 'pre', 'each_item', 'always', 'check_fields', 'skip_on_failure' @@ -54,7 +57,7 @@ def validator( check_fields: bool = True, whole: bool = None, allow_reuse: bool = False, -) -> Callable[[AnyCallable], classmethod]: # type: ignore[type-arg] +) -> Callable[[AnyCallable], 'AnyClassMethod']: """ Decorate methods on the class indicating that they should be used to validate fields :param fields: which field(s) the method should be called on @@ -81,7 +84,7 @@ def validator( assert each_item is False, '"each_item" and "whole" conflict, remove "whole"' each_item = not whole - def dec(f: AnyCallable) -> classmethod: # type: ignore[type-arg] + def dec(f: AnyCallable) -> 'AnyClassMethod': f_cls = _prepare_validator(f, allow_reuse) setattr( f_cls, @@ -97,20 +100,20 @@ def dec(f: AnyCallable) -> classmethod: # type: ignore[type-arg] @overload -def root_validator(_func: AnyCallable) -> classmethod: # type: ignore[type-arg] +def root_validator(_func: AnyCallable) -> 'AnyClassMethod': ... @overload def root_validator( *, pre: bool = False, allow_reuse: bool = False, skip_on_failure: bool = False -) -> Callable[[AnyCallable], classmethod]: # type: ignore[type-arg] +) -> Callable[[AnyCallable], 'AnyClassMethod']: ... def root_validator( _func: Optional[AnyCallable] = None, *, pre: bool = False, allow_reuse: bool = False, skip_on_failure: bool = False -) -> Union[classmethod, Callable[[AnyCallable], classmethod]]: # type: ignore[type-arg] +) -> Union['AnyClassMethod', Callable[[AnyCallable], 'AnyClassMethod']]: """ Decorate methods on a model indicating that they should be used to validate (and perhaps modify) data either before or after standard model parsing/validation is performed. @@ -122,7 +125,7 @@ def root_validator( ) return f_cls - def dec(f: AnyCallable) -> classmethod: # type: ignore[type-arg] + def dec(f: AnyCallable) -> 'AnyClassMethod': f_cls = _prepare_validator(f, allow_reuse) setattr( f_cls, ROOT_VALIDATOR_CONFIG_KEY, Validator(func=f_cls.__func__, pre=pre, skip_on_failure=skip_on_failure) @@ -132,7 +135,7 @@ def dec(f: AnyCallable) -> classmethod: # type: ignore[type-arg] return dec -def _prepare_validator(function: AnyCallable, allow_reuse: bool) -> classmethod: # type: ignore[type-arg] +def _prepare_validator(function: AnyCallable, allow_reuse: bool) -> 'AnyClassMethod': """ Avoid validators with duplicated names since without this, validators can be overwritten silently which generally isn't the intended behaviour, don't run in ipython (see #312) or if allow_reuse is False. @@ -325,7 +328,7 @@ def _generic_validator_basic(validator: AnyCallable, sig: 'Signature', args: Set return lambda cls, v, values, field, config: validator(v, values=values, field=field, config=config) -def gather_all_validators(type_: 'ModelOrDc') -> Dict[str, classmethod]: # type: ignore[type-arg] +def gather_all_validators(type_: 'ModelOrDc') -> Dict[str, 'AnyClassMethod']: all_attributes = ChainMap(*[cls.__dict__ for cls in type_.__mro__]) return { k: v diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -66,6 +66,7 @@ from .types import ModelOrDc from .typing import ( AbstractSetIntStr, + AnyClassMethod, CallableGenerator, DictAny, DictStrAny, @@ -890,7 +891,7 @@ def create_model( __config__: Optional[Type[BaseConfig]] = None, __base__: None = None, __module__: str = __name__, - __validators__: Dict[str, classmethod] = None, # type: ignore[type-arg] + __validators__: Dict[str, 'AnyClassMethod'] = None, **field_definitions: Any, ) -> Type['BaseModel']: ... @@ -903,7 +904,7 @@ def create_model( __config__: Optional[Type[BaseConfig]] = None, __base__: Union[Type['Model'], Tuple[Type['Model'], ...]], __module__: str = __name__, - __validators__: Dict[str, classmethod] = None, # type: ignore[type-arg] + __validators__: Dict[str, 'AnyClassMethod'] = None, **field_definitions: Any, ) -> Type['Model']: ... @@ -915,7 +916,7 @@ def create_model( __config__: Optional[Type[BaseConfig]] = None, __base__: Union[None, Type['Model'], Tuple[Type['Model'], ...]] = None, __module__: str = __name__, - __validators__: Dict[str, classmethod] = None, # type: ignore[type-arg] + __validators__: Dict[str, 'AnyClassMethod'] = None, **field_definitions: Any, ) -> Type['Model']: """ diff --git a/pydantic/mypy.py b/pydantic/mypy.py --- a/pydantic/mypy.py +++ b/pydantic/mypy.py @@ -1,20 +1,6 @@ from configparser import ConfigParser from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Type as TypingType, Union -from pydantic.utils import is_valid_field - -try: - import toml -except ImportError: # pragma: no cover - # future-proofing for upcoming `mypy` releases which will switch dependencies - try: - import tomli as toml # type: ignore - except ImportError: - import warnings - - warnings.warn('No TOML parser installed, cannot read configuration from `pyproject.toml`.') - toml = None # type: ignore - from mypy.errorcodes import ErrorCode from mypy.nodes import ( ARG_NAMED, @@ -60,13 +46,21 @@ Type, TypeOfAny, TypeType, - TypeVarLikeType, TypeVarType, UnionType, get_proper_type, ) from mypy.typevars import fill_typevars from mypy.util import get_unique_redefinition_name +from mypy.version import __version__ as mypy_version + +from pydantic.utils import is_valid_field + +try: + from mypy.types import TypeVarDef # type: ignore[attr-defined] +except ImportError: # pragma: no cover + # Backward-compatible with TypeVarDef from Mypy 0.910. + from mypy.types import TypeVarType as TypeVarDef CONFIGFILE_KEY = 'pydantic-mypy' METADATA_KEY = 'pydantic-mypy-metadata' @@ -74,6 +68,7 @@ BASESETTINGS_FULLNAME = 'pydantic.env_settings.BaseSettings' FIELD_FULLNAME = 'pydantic.fields.Field' DATACLASS_FULLNAME = 'pydantic.dataclasses.dataclass' +BUILTINS_NAME = 'builtins' if float(mypy_version) >= 0.930 else '__builtins__' def plugin(version: str) -> 'TypingType[Plugin]': @@ -125,9 +120,9 @@ def __init__(self, options: Options) -> None: if options.config_file is None: # pragma: no cover return - if toml and options.config_file.endswith('.toml'): - with open(options.config_file, 'r') as rf: - config = toml.load(rf).get('tool', {}).get('pydantic-mypy', {}) + toml_config = parse_toml(options.config_file) + if toml_config is not None: + config = toml_config.get('tool', {}).get('pydantic-mypy', {}) for key in self.__slots__: setting = config.get(key, False) if not isinstance(setting, bool): @@ -348,26 +343,32 @@ def add_construct_method(self, fields: List['PydanticModelField']) -> None: and does not treat settings fields as optional. """ ctx = self._ctx - set_str = ctx.api.named_type('builtins.set', [ctx.api.named_type('builtins.str')]) + set_str = ctx.api.named_type(f'{BUILTINS_NAME}.set', [ctx.api.named_type(f'{BUILTINS_NAME}.str')]) optional_set_str = UnionType([set_str, NoneType()]) fields_set_argument = Argument(Var('_fields_set', optional_set_str), optional_set_str, None, ARG_OPT) construct_arguments = self.get_field_arguments(fields, typed=True, force_all_optional=False, use_alias=False) construct_arguments = [fields_set_argument] + construct_arguments - obj_type = ctx.api.named_type('builtins.object') + obj_type = ctx.api.named_type(f'{BUILTINS_NAME}.object') self_tvar_name = '_PydanticBaseModel' # Make sure it does not conflict with other names in the class tvar_fullname = ctx.cls.fullname + '.' + self_tvar_name - self_type = TypeVarType(self_tvar_name, tvar_fullname, -1, [], obj_type) + tvd = TypeVarDef(self_tvar_name, tvar_fullname, -1, [], obj_type) self_tvar_expr = TypeVarExpr(self_tvar_name, tvar_fullname, [], obj_type) ctx.cls.info.names[self_tvar_name] = SymbolTableNode(MDEF, self_tvar_expr) + # Backward-compatible with TypeVarDef from Mypy 0.910. + if isinstance(tvd, TypeVarType): + self_type = tvd + else: + self_type = TypeVarType(tvd) # type: ignore[call-arg] + add_method( ctx, 'construct', construct_arguments, return_type=self_type, self_type=self_type, - tvar_like_type=self_type, + tvar_def=tvd, is_classmethod=True, ) @@ -619,7 +620,7 @@ def add_method( args: List[Argument], return_type: Type, self_type: Optional[Type] = None, - tvar_like_type: Optional[TypeVarLikeType] = None, + tvar_def: Optional[TypeVarDef] = None, is_classmethod: bool = False, is_new: bool = False, # is_staticmethod: bool = False, @@ -654,10 +655,10 @@ def add_method( arg_names.append(get_name(arg.variable)) arg_kinds.append(arg.kind) - function_type = ctx.api.named_type('builtins.function') + function_type = ctx.api.named_type(f'{BUILTINS_NAME}.function') signature = CallableType(arg_types, arg_kinds, arg_names, return_type, function_type) - if tvar_like_type: - signature.variables = [tvar_like_type] + if tvar_def: + signature.variables = [tvar_def] func = FuncDef(name, args, Block([PassStmt()])) func.info = info @@ -714,3 +715,25 @@ def get_name(x: Union[FuncBase, SymbolNode]) -> str: if callable(fn): # pragma: no cover return fn() return fn + + +def parse_toml(config_file: str) -> Optional[Dict[str, Any]]: + if not config_file.endswith('.toml'): + return None + + read_mode = 'rb' + try: + import tomli as toml_ + except ImportError: + # older versions of mypy have toml as a dependency, not tomli + read_mode = 'r' + try: + import toml as toml_ # type: ignore[no-redef] + except ImportError: # pragma: no cover + import warnings + + warnings.warn('No TOML parser installed, cannot read configuration from `pyproject.toml`.') + return None + + with open(config_file, read_mode) as rf: + return toml_.load(rf) # type: ignore[arg-type] diff --git a/pydantic/typing.py b/pydantic/typing.py --- a/pydantic/typing.py +++ b/pydantic/typing.py @@ -228,6 +228,7 @@ def is_union(tp: Optional[Type[Any]]) -> bool: MappingIntStrAny = Mapping[IntStr, Any] CallableGenerator = Generator[AnyCallable, None, None] ReprArgs = Sequence[Tuple[Optional[str], Any]] + AnyClassMethod = classmethod[Any] __all__ = ( 'ForwardRef', @@ -258,6 +259,7 @@ def is_union(tp: Optional[Type[Any]]) -> bool: 'DictIntStrAny', 'CallableGenerator', 'ReprArgs', + 'AnyClassMethod', 'CallableGenerator', 'WithArgsTypes', 'get_args', diff --git a/pydantic/utils.py b/pydantic/utils.py --- a/pydantic/utils.py +++ b/pydantic/utils.py @@ -574,7 +574,8 @@ def _coerce_items(items: Union['AbstractSetIntStr', 'MappingIntStrAny']) -> 'Map elif isinstance(items, AbstractSet): items = dict.fromkeys(items, ...) else: - raise TypeError(f'Unexpected type of exclude value {items.__class__}') # type: ignore[attr-defined] + class_name = getattr(items, '__class__', '???') + raise TypeError(f'Unexpected type of exclude value {class_name}') return items @classmethod
pydantic/pydantic
8ef492b85fddbfbeadde49e07163580c13d432d5
diff --git a/tests/mypy/test_mypy.py b/tests/mypy/test_mypy.py --- a/tests/mypy/test_mypy.py +++ b/tests/mypy/test_mypy.py @@ -7,8 +7,10 @@ try: from mypy import api as mypy_api + from mypy.version import __version__ as mypy_version except ImportError: mypy_api = None # type: ignore + mypy_version = '0' try: import dotenv @@ -72,6 +74,15 @@ def test_mypy_results(config_filename: str, python_filename: str, output_filenam raise RuntimeError(f'wrote actual output to {output_path} since file did not exist') expected_out = Path(output_path).read_text() if output_path else '' + + # fix for compatibility between mypy versions: (this can be dropped once we drop support for mypy<0.930) + if actual_out and float(mypy_version) < 0.930: + actual_out = actual_out.lower() + expected_out = expected_out.lower() + actual_out = actual_out.replace('variant:', 'variants:') + actual_out = re.sub(r'^(\d+: note: {4}).*', r'\1...', actual_out, flags=re.M) + expected_out = re.sub(r'^(\d+: note: {4}).*', r'\1...', expected_out, flags=re.M) + assert actual_out == expected_out, actual_out diff --git a/tests/requirements-linting.txt b/tests/requirements-linting.txt --- a/tests/requirements-linting.txt +++ b/tests/requirements-linting.txt @@ -8,4 +8,3 @@ pre-commit==2.16.0 pycodestyle==2.8.0 pyflakes==2.4.0 twine==3.7.1 -types-toml==0.10.1
Error in mypy plugin reading config from pyproject.toml with mypy >= 0.920 ### Checks * [x] I added a descriptive title to this issue * [x] I have searched (google, github) for similar issues and couldn't find anything * [x] I have read and followed [the docs](https://pydantic-docs.helpmanual.io/) and still think this is a bug <!-- Sorry to sound so draconian, but every second saved replying to issues is time spend improving pydantic :-) --> # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.9.0a2 pydantic compiled: True install path: /Users/paul/.cache/pre-commit/repo8u79aah5/py_env-python3.9/lib/python3.9/site-packages/pydantic python version: 3.9.6 (default, Aug 18 2021, 18:03:48) [Clang 11.0.3 (clang-1103.0.32.62)] platform: macOS-10.16-x86_64-i386-64bit optional deps. installed: ['typing-extensions'] ``` <!-- or if you're using pydantic prior to v1.3, manually include: OS, python version and pydantic version --> <!-- Please read the [docs](https://pydantic-docs.helpmanual.io/) and search through issues to confirm your bug hasn't already been reported. --> <!-- Where possible please include a self-contained code snippet describing your bug: --> I'm testing out the new `pyproject.toml` config support in alpha. I tried to set the config in my `pyproject.toml` exactly like in the docs: https://pydantic-docs.helpmanual.io/mypy_plugin/#configuring-the-plugin . However, this doesn't seem to work with `mypy` `0.930`, when I run it I get the folllowing traceback: ``` Error constructing plugin instance of PydanticPlugin Traceback (most recent call last): File "/Users/paul/.cache/pre-commit/repo8u79aah5/py_env-python3.9/bin/mypy", line 8, in <module> sys.exit(console_entry()) File "/Users/paul/.cache/pre-commit/repo8u79aah5/py_env-python3.9/lib/python3.9/site-packages/mypy/__main__.py", line 12, in console_entry main(None, sys.stdout, sys.stderr) File "mypy/main.py", line 96, in main File "mypy/main.py", line 173, in run_build File "mypy/build.py", line 180, in build File "mypy/build.py", line 231, in _build File "mypy/build.py", line 478, in load_plugins File "mypy/build.py", line 456, in load_plugins_from_config File "pydantic/mypy.py", line 91, in pydantic.mypy.PydanticPlugin.__init__ File "pydantic/mypy.py", line 129, in pydantic.mypy.PydanticPluginConfig.__init__ File "pydantic/mypy.py", line 130, in pydantic.mypy.PydanticPluginConfig.__init__ File "/Users/paul/.cache/pre-commit/repo8u79aah5/py_env-python3.9/lib/python3.9/site-packages/tomli/_parser.py", line 56, in load s = __fp.read().decode() AttributeError: 'str' object has no attribute 'decode' ``` The issue is here: https://github.com/samuelcolvin/pydantic/blob/ef4678999f94625819ebad61b44ea264479aeb0a/pydantic/mypy.py#L129 Newer `mypy` versions (`>=0.920`) use `tomli` for parsing, and `tomli`'s version of `load` expects the file handle in binary mode explaining the error. Related: https://github.com/samuelcolvin/pydantic/issues/2895 https://github.com/samuelcolvin/pydantic/pull/2908
0.0
8ef492b85fddbfbeadde49e07163580c13d432d5
[ "tests/mypy/test_mypy.py::test_mypy_results[pyproject-plugin.toml-plugin_success.py-None]", "tests/mypy/test_mypy.py::test_mypy_results[pyproject-plugin.toml-plugin_fail.py-plugin-fail.txt]", "tests/mypy/test_mypy.py::test_mypy_results[pyproject-plugin-strict.toml-plugin_success.py-plugin-success-strict.txt]", "tests/mypy/test_mypy.py::test_mypy_results[pyproject-plugin-strict.toml-plugin_fail.py-plugin-fail-strict.txt]", "tests/mypy/test_mypy.py::test_bad_toml_config" ]
[ "tests/mypy/test_mypy.py::test_mypy_results[mypy-plugin.ini-plugin_success.py-None]", "tests/mypy/test_mypy.py::test_mypy_results[mypy-plugin.ini-plugin_fail.py-plugin-fail.txt]", "tests/mypy/test_mypy.py::test_mypy_results[mypy-plugin-strict.ini-plugin_success.py-plugin-success-strict.txt]", "tests/mypy/test_mypy.py::test_mypy_results[mypy-plugin-strict.ini-plugin_fail.py-plugin-fail-strict.txt]", "tests/mypy/test_mypy.py::test_mypy_results[mypy-default.ini-success.py-None]", "tests/mypy/test_mypy.py::test_mypy_results[mypy-default.ini-fail1.py-fail1.txt]", "tests/mypy/test_mypy.py::test_mypy_results[mypy-default.ini-fail2.py-fail2.txt]", "tests/mypy/test_mypy.py::test_mypy_results[mypy-default.ini-fail3.py-fail3.txt]", "tests/mypy/test_mypy.py::test_mypy_results[mypy-default.ini-fail4.py-fail4.txt]", "tests/mypy/test_mypy.py::test_mypy_results[mypy-default.ini-plugin_success.py-plugin_success.txt]", "tests/mypy/test_mypy.py::test_mypy_results[pyproject-default.toml-success.py-None]", "tests/mypy/test_mypy.py::test_mypy_results[pyproject-default.toml-fail1.py-fail1.txt]", "tests/mypy/test_mypy.py::test_mypy_results[pyproject-default.toml-fail2.py-fail2.txt]", "tests/mypy/test_mypy.py::test_mypy_results[pyproject-default.toml-fail3.py-fail3.txt]", "tests/mypy/test_mypy.py::test_mypy_results[pyproject-default.toml-fail4.py-fail4.txt]", "tests/mypy/test_mypy.py::test_success_cases_run[plugin_success]", "tests/mypy/test_mypy.py::test_success_cases_run[success]", "tests/mypy/test_mypy.py::test_explicit_reexports" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-12-29 17:16:11+00:00
mit
4,848
pydantic__pydantic-3639
diff --git a/pydantic/fields.py b/pydantic/fields.py --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -600,7 +600,7 @@ def _type_analysis(self) -> None: # noqa: C901 (ignore complexity) return if self.discriminator_key is not None and not is_union(origin): - raise TypeError('`discriminator` can only be used with `Union` type') + raise TypeError('`discriminator` can only be used with `Union` type with more than one variant') # add extra check for `collections.abc.Hashable` for python 3.10+ where origin is not `None` if origin is None or origin is CollectionsHashable:
pydantic/pydantic
6f46a5a1460728868f860840e3f6186aa40403d8
Hi @tommilligan The thing is we can't do anything about it because python changes `Union[A]` into `A` at interpretation time. ```py from typing import Union class A: ... assert Union[A] is A ``` So at runtime, pydantic has no way to know `A` was supposed to be a `Union` Ah, that makes sense. I was about to start poking to see if the simplification was internal to `pydantic` or not, but if it's at a higher layer I'll give it up as a lost cause. Would you accept a PR noting this as an edge case in the documentation/error message? I suppose the workaround is to add a dummy second type into the union, or just to remove the discriminator until it is required. For documentation forward compatibility, we were using [openapi-schema-pydantic](https://github.com/kuimono/openapi-schema-pydantic), which now collides with the `discriminator` Field property nicely. But that's not your problem! I'll file a bug over there now. Documentation PRs are always welcome :)
diff --git a/tests/test_discrimated_union.py b/tests/test_discrimated_union.py --- a/tests/test_discrimated_union.py +++ b/tests/test_discrimated_union.py @@ -11,12 +11,23 @@ def test_discriminated_union_only_union(): - with pytest.raises(TypeError, match='`discriminator` can only be used with `Union` type'): + with pytest.raises( + TypeError, match='`discriminator` can only be used with `Union` type with more than one variant' + ): class Model(BaseModel): x: str = Field(..., discriminator='qwe') +def test_discriminated_union_single_variant(): + with pytest.raises( + TypeError, match='`discriminator` can only be used with `Union` type with more than one variant' + ): + + class Model(BaseModel): + x: Union[str] = Field(..., discriminator='qwe') + + def test_discriminated_union_invalid_type(): with pytest.raises(TypeError, match="Type 'str' is not a valid `BaseModel` or `dataclass`"):
Discriminated unions raise TypeError for unions of a single type ### Checks * [x] I added a descriptive title to this issue * [x] I have searched (google, github) for similar issues and couldn't find anything * [x] I have read and followed [the docs](https://pydantic-docs.helpmanual.io/) and still think this is a bug <!-- Sorry to sound so draconian, but every second saved replying to issues is time spend improving pydantic :-) --> # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.9.0 pydantic compiled: False install path: /home/tom/reinfer/env/lib/python3.8/site-packages/pydantic python version: 3.8.10 (default, Nov 26 2021, 20:14:08) [GCC 9.3.0] platform: Linux-5.11.0-44-generic-x86_64-with-glibc2.29 optional deps. installed: ['dotenv', 'typing-extensions'] ``` When a `Union` with only a single variant it tagged with a field as a discriminated union, a type error is thrown on defining the class. The below is a minimally reproducible example: ```py # repro.py from typing import Literal, Union from pydantic import BaseModel, Field class DataAModel(BaseModel): kind: Literal["a"] class RequestModel(BaseModel): data: Union[DataAModel] = Field(..., discriminator="kind") ``` produces ```bash $ python repro.py Traceback (most recent call last): File "repro.py", line 10, in <module> class RequestModel(BaseModel): File "/home/tom/r/env/lib/python3.8/site-packages/pydantic/main.py", line 204, in __new__ fields[ann_name] = ModelField.infer( File "/home/tom/r/env/lib/python3.8/site-packages/pydantic/fields.py", line 488, in infer return cls( File "/home/tom/r/env/lib/python3.8/site-packages/pydantic/fields.py", line 419, in __init__ self.prepare() File "/home/tom/r/env/lib/python3.8/site-packages/pydantic/fields.py", line 534, in prepare self._type_analysis() File "/home/tom/r/env/lib/python3.8/site-packages/pydantic/fields.py", line 605, in _type_analysis raise TypeError('`discriminator` can only be used with `Union` type') TypeError: `discriminator` can only be used with `Union` type ``` The following code snippet works as intended. The only difference is I have introduced a second type in the discriminated union field. Note that simply repeating the existing type (such as `Union[DataAModel, DataAModel]`) still fails: ```py from typing import Literal, Union from pydantic import BaseModel, Field class DataAModel(BaseModel): kind: Literal["a"] class DataBModel(BaseModel): kind: Literal["b"] class RequestModel(BaseModel): data: Union[DataAModel, DataBModel] = Field(..., discriminator="kind") ``` --- After some poking, it looks like within `_type_analysis`, `self.discriminator_key` is set on the model `DataAModel`, rather than the parent field, `Union[DataAModel]`. I'm guessing there is a simplification step somewhere where singleton unions are simplified to their child type, which is no longer accurate? Happy to submit a PR if you can point me further in the right approach.
0.0
6f46a5a1460728868f860840e3f6186aa40403d8
[ "tests/test_discrimated_union.py::test_discriminated_union_only_union", "tests/test_discrimated_union.py::test_discriminated_union_single_variant" ]
[ "tests/test_discrimated_union.py::test_discriminated_union_invalid_type", "tests/test_discrimated_union.py::test_discriminated_union_defined_discriminator", "tests/test_discrimated_union.py::test_discriminated_union_literal_discriminator", "tests/test_discrimated_union.py::test_discriminated_union_root_same_discriminator", "tests/test_discrimated_union.py::test_discriminated_union_validation", "tests/test_discrimated_union.py::test_discriminated_annotated_union", "tests/test_discrimated_union.py::test_discriminated_union_basemodel_instance_value", "tests/test_discrimated_union.py::test_discriminated_union_int", "tests/test_discrimated_union.py::test_discriminated_union_enum", "tests/test_discrimated_union.py::test_alias_different", "tests/test_discrimated_union.py::test_alias_same", "tests/test_discrimated_union.py::test_nested", "tests/test_discrimated_union.py::test_generic" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2022-01-07 16:37:49+00:00
mit
4,849
pydantic__pydantic-3642
diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -666,7 +666,7 @@ def __get_validators__(cls) -> 'CallableGenerator': def validate(cls: Type['Model'], value: Any) -> 'Model': if isinstance(value, cls): if cls.__config__.copy_on_model_validation: - return value._copy_and_set_values(value.__dict__, value.__fields_set__, deep=False) + return value._copy_and_set_values(value.__dict__, value.__fields_set__, deep=True) else: return value
pydantic/pydantic
02eb182db08f373d96a35ec525ec4f86497b3b11
diff --git a/tests/test_main.py b/tests/test_main.py --- a/tests/test_main.py +++ b/tests/test_main.py @@ -1561,12 +1561,28 @@ class Config: assert t.user is not my_user assert t.user.hobbies == ['scuba diving'] - assert t.user.hobbies is my_user.hobbies # `Config.copy_on_model_validation` only does a shallow copy + assert t.user.hobbies is not my_user.hobbies # `Config.copy_on_model_validation` does a deep copy assert t.user._priv == 13 assert t.user.password.get_secret_value() == 'hashedpassword' assert t.dict() == {'id': '1234567890', 'user': {'id': 42, 'hobbies': ['scuba diving']}} +def test_validation_deep_copy(): + """By default, Config.copy_on_model_validation should do a deep copy""" + + class A(BaseModel): + name: str + + class B(BaseModel): + list_a: List[A] + + a = A(name='a') + b = B(list_a=[a]) + assert b.list_a == [A(name='a')] + a.name = 'b' + assert b.list_a == [A(name='a')] + + @pytest.mark.parametrize( 'kinds', [
copy_on_model_validation config doesn't copy List field anymore in v1.9.0 ### Checks * [x] I added a descriptive title to this issue * [x] I have searched (google, github) for similar issues and couldn't find anything * [x] I have read and followed [the docs](https://pydantic-docs.helpmanual.io/) and still think this is a bug <!-- Sorry to sound so draconian, but every second saved replying to issues is time spend improving pydantic :-) --> # Bug The output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"` when I use v1.9.0a1, ``` pydantic version: 1.9.0a1 pydantic compiled: True install path: <*my-project-dir*>/venv/lib/python3.9/site-packages/pydantic python version: 3.9.9 (main, Nov 16 2021, 03:05:18) [GCC 7.5.0] platform: Linux-5.4.0-91-generic-x86_64-with-glibc2.27 optional deps. installed: ['typing-extensions'] ``` The output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"` when I use v1.9.0, ``` pydantic version: 1.9.0 pydantic compiled: True install path: <*my-project-dir*>/venv/lib/python3.9/site-packages/pydantic python version: 3.9.9 (main, Nov 16 2021, 03:05:18) [GCC 7.5.0] platform: Linux-5.4.0-91-generic-x86_64-with-glibc2.27 optional deps. installed: ['typing-extensions'] ``` <!-- or if you're using pydantic prior to v1.3, manually include: OS, python version and pydantic version --> <!-- Please read the [docs](https://pydantic-docs.helpmanual.io/) and search through issues to confirm your bug hasn't already been reported. --> <!-- Where possible please include a self-contained code snippet describing your bug: --> Looks like there is accidental behaviour change from v1.9.0a1 to v1.9.0 regarding the `copy_on_model_validation` config. ```py from pydantic import BaseModel from typing import List class A(BaseModel): name: str class Config: copy_on_model_validation = True # Default behaviour class B(BaseModel): list_a: List[A] a = A(name="a") b = B(list_a=[a]) print(a) print(b) a.name = "b" # make a change to variable a's field print(a) print(b) ``` The output using v1.9.0a1, ``` A(name='a') B(list_a=[A(name='a')]) A(name='b') B(list_a=[A(name='a')]) ``` The output using v1.9.0 changed to, ``` A(name='a') B(list_a=[A(name='a')]) A(name='b') B(list_a=[A(name='b')]) ```
0.0
02eb182db08f373d96a35ec525ec4f86497b3b11
[ "tests/test_main.py::test_model_exclude_copy_on_model_validation", "tests/test_main.py::test_validation_deep_copy" ]
[ "tests/test_main.py::test_success", "tests/test_main.py::test_ultra_simple_missing", "tests/test_main.py::test_ultra_simple_failed", "tests/test_main.py::test_ultra_simple_repr", "tests/test_main.py::test_default_factory_field", "tests/test_main.py::test_default_factory_no_type_field", "tests/test_main.py::test_comparing", "tests/test_main.py::test_nullable_strings_success", "tests/test_main.py::test_nullable_strings_fails", "tests/test_main.py::test_recursion", "tests/test_main.py::test_recursion_fails", "tests/test_main.py::test_not_required", "tests/test_main.py::test_infer_type", "tests/test_main.py::test_allow_extra", "tests/test_main.py::test_allow_extra_repr", "tests/test_main.py::test_forbidden_extra_success", "tests/test_main.py::test_forbidden_extra_fails", "tests/test_main.py::test_disallow_mutation", "tests/test_main.py::test_extra_allowed", "tests/test_main.py::test_extra_ignored", "tests/test_main.py::test_set_attr", "tests/test_main.py::test_set_attr_invalid", "tests/test_main.py::test_any", "tests/test_main.py::test_alias", "tests/test_main.py::test_population_by_field_name", "tests/test_main.py::test_field_order", "tests/test_main.py::test_required", "tests/test_main.py::test_mutability", "tests/test_main.py::test_immutability[False-False]", "tests/test_main.py::test_immutability[False-True]", "tests/test_main.py::test_immutability[True-True]", "tests/test_main.py::test_not_frozen_are_not_hashable", "tests/test_main.py::test_with_declared_hash", "tests/test_main.py::test_frozen_with_hashable_fields_are_hashable", "tests/test_main.py::test_frozen_with_unhashable_fields_are_not_hashable", "tests/test_main.py::test_hash_function_give_different_result_for_different_object", "tests/test_main.py::test_const_validates", "tests/test_main.py::test_const_uses_default", "tests/test_main.py::test_const_validates_after_type_validators", "tests/test_main.py::test_const_with_wrong_value", "tests/test_main.py::test_const_with_validator", "tests/test_main.py::test_const_list", "tests/test_main.py::test_const_list_with_wrong_value", "tests/test_main.py::test_const_validation_json_serializable", "tests/test_main.py::test_validating_assignment_pass", "tests/test_main.py::test_validating_assignment_fail", "tests/test_main.py::test_validating_assignment_pre_root_validator_fail", "tests/test_main.py::test_validating_assignment_post_root_validator_fail", "tests/test_main.py::test_root_validator_many_values_change", "tests/test_main.py::test_enum_values", "tests/test_main.py::test_literal_enum_values", "tests/test_main.py::test_enum_raw", "tests/test_main.py::test_set_tuple_values", "tests/test_main.py::test_default_copy", "tests/test_main.py::test_arbitrary_type_allowed_validation_success", "tests/test_main.py::test_arbitrary_type_allowed_validation_fails", "tests/test_main.py::test_arbitrary_types_not_allowed", "tests/test_main.py::test_type_type_validation_success", "tests/test_main.py::test_type_type_subclass_validation_success", "tests/test_main.py::test_type_type_validation_fails_for_instance", "tests/test_main.py::test_type_type_validation_fails_for_basic_type", "tests/test_main.py::test_bare_type_type_validation_success", "tests/test_main.py::test_bare_type_type_validation_fails", "tests/test_main.py::test_annotation_field_name_shadows_attribute", "tests/test_main.py::test_value_field_name_shadows_attribute", "tests/test_main.py::test_class_var", "tests/test_main.py::test_fields_set", "tests/test_main.py::test_exclude_unset_dict", "tests/test_main.py::test_exclude_unset_recursive", "tests/test_main.py::test_dict_exclude_unset_populated_by_alias", "tests/test_main.py::test_dict_exclude_unset_populated_by_alias_with_extra", "tests/test_main.py::test_exclude_defaults", "tests/test_main.py::test_dir_fields", "tests/test_main.py::test_dict_with_extra_keys", "tests/test_main.py::test_root", "tests/test_main.py::test_root_list", "tests/test_main.py::test_root_nested", "tests/test_main.py::test_encode_nested_root", "tests/test_main.py::test_root_failed", "tests/test_main.py::test_root_undefined_failed", "tests/test_main.py::test_parse_root_as_mapping", "tests/test_main.py::test_parse_obj_non_mapping_root", "tests/test_main.py::test_parse_obj_nested_root", "tests/test_main.py::test_untouched_types", "tests/test_main.py::test_custom_types_fail_without_keep_untouched", "tests/test_main.py::test_model_iteration", "tests/test_main.py::test_model_export_nested_list[excluding", "tests/test_main.py::test_model_export_nested_list[should", "tests/test_main.py::test_model_export_nested_list[using", "tests/test_main.py::test_model_export_dict_exclusion[excluding", "tests/test_main.py::test_model_export_dict_exclusion[using", "tests/test_main.py::test_model_export_dict_exclusion[exclude", "tests/test_main.py::test_model_exclude_config_field_merging", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[None-expected0-kinds0]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[None-expected0-kinds1]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[None-expected0-kinds2]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[None-expected0-kinds3]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[None-expected0-kinds4]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[None-expected0-kinds5]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[None-expected0-kinds6]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude1-expected1-kinds0]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude1-expected1-kinds1]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude1-expected1-kinds2]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude1-expected1-kinds3]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude1-expected1-kinds4]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude1-expected1-kinds5]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude1-expected1-kinds6]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude2-expected2-kinds0]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude2-expected2-kinds1]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude2-expected2-kinds2]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude2-expected2-kinds3]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude2-expected2-kinds4]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude2-expected2-kinds5]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude2-expected2-kinds6]", "tests/test_main.py::test_model_export_exclusion_inheritance", "tests/test_main.py::test_model_export_with_true_instead_of_ellipsis", "tests/test_main.py::test_model_export_inclusion", "tests/test_main.py::test_model_export_inclusion_inheritance", "tests/test_main.py::test_custom_init_subclass_params", "tests/test_main.py::test_update_forward_refs_does_not_modify_module_dict", "tests/test_main.py::test_two_defaults", "tests/test_main.py::test_default_factory", "tests/test_main.py::test_default_factory_called_once", "tests/test_main.py::test_default_factory_called_once_2", "tests/test_main.py::test_default_factory_validate_children", "tests/test_main.py::test_default_factory_parse", "tests/test_main.py::test_none_min_max_items", "tests/test_main.py::test_reuse_same_field", "tests/test_main.py::test_base_config_type_hinting", "tests/test_main.py::test_allow_mutation_field", "tests/test_main.py::test_repr_field", "tests/test_main.py::test_inherited_model_field_copy", "tests/test_main.py::test_inherited_model_field_untouched", "tests/test_main.py::test_mapping_retains_type_subclass", "tests/test_main.py::test_mapping_retains_type_defaultdict", "tests/test_main.py::test_mapping_retains_type_fallback_error", "tests/test_main.py::test_typing_coercion_dict", "tests/test_main.py::test_typing_non_coercion_of_dict_subclasses", "tests/test_main.py::test_typing_coercion_defaultdict", "tests/test_main.py::test_typing_coercion_counter", "tests/test_main.py::test_typing_counter_value_validation", "tests/test_main.py::test_class_kwargs_config", "tests/test_main.py::test_class_kwargs_config_json_encoders", "tests/test_main.py::test_class_kwargs_config_and_attr_conflict", "tests/test_main.py::test_class_kwargs_custom_config" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2022-01-09 12:00:51+00:00
mit
4,850
pydantic__pydantic-3646
diff --git a/pydantic/color.py b/pydantic/color.py --- a/pydantic/color.py +++ b/pydantic/color.py @@ -198,6 +198,9 @@ def __str__(self) -> str: def __repr_args__(self) -> 'ReprArgs': return [(None, self.as_named(fallback=True))] + [('rgb', self.as_rgb_tuple())] # type: ignore + def __eq__(self, other: Any) -> bool: + return isinstance(other, Color) and self.as_rgb_tuple() == other.as_rgb_tuple() + def parse_tuple(value: Tuple[Any, ...]) -> RGBA: """
pydantic/pydantic
a69136d2096e327ed48954a298c775dceb1551d1
This is not a bug. It's a feature request. We don't currently implement special equals methods. PR welcome.
diff --git a/tests/test_color.py b/tests/test_color.py --- a/tests/test_color.py +++ b/tests/test_color.py @@ -184,3 +184,12 @@ def test_str_repr(): assert repr(Color('red')) == "Color('red', rgb=(255, 0, 0))" assert str(Color((1, 2, 3))) == '#010203' assert repr(Color((1, 2, 3))) == "Color('#010203', rgb=(1, 2, 3))" + + +def test_eq(): + assert Color('red') == Color('red') + assert Color('red') != Color('blue') + assert Color('red') != 'red' + + assert Color('red') == Color((255, 0, 0)) + assert Color('red') != Color((0, 0, 255))
Color comparison is always false # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.9.0 pydantic compiled: True install path: /home/xxxxxxx/xxxxxxx/xxxxxxx/venv310/lib/python3.10/site-packages/pydantic python version: 3.10.1 (main, Dec 21 2021, 17:46:38) [GCC 9.3.0] platform: Linux-5.11.0-44-generic-x86_64-with-glibc2.31 optional deps. installed: ['dotenv', 'typing-extensions'] ``` <!-- or if you're using pydantic prior to v1.3, manually include: OS, python version and pydantic version --> <!-- Please read the [docs](https://pydantic-docs.helpmanual.io/) and search through issues to confirm your bug hasn't already been reported. --> <!-- Where possible please include a self-contained code snippet describing your bug: --> How to reproduce: ```py >>> from pydantic.color import Color >>> Color("red") == Color("red") False ``` As a consequence, when using Color fields, the comparison of equal models is always false.
0.0
a69136d2096e327ed48954a298c775dceb1551d1
[ "tests/test_color.py::test_eq" ]
[ "tests/test_color.py::test_color_success[aliceblue-as_tuple0]", "tests/test_color.py::test_color_success[Antiquewhite-as_tuple1]", "tests/test_color.py::test_color_success[#000000-as_tuple2]", "tests/test_color.py::test_color_success[#DAB-as_tuple3]", "tests/test_color.py::test_color_success[#dab-as_tuple4]", "tests/test_color.py::test_color_success[#000-as_tuple5]", "tests/test_color.py::test_color_success[0x797979-as_tuple6]", "tests/test_color.py::test_color_success[0x777-as_tuple7]", "tests/test_color.py::test_color_success[0x777777-as_tuple8]", "tests/test_color.py::test_color_success[0x777777cc-as_tuple9]", "tests/test_color.py::test_color_success[777-as_tuple10]", "tests/test_color.py::test_color_success[777c-as_tuple11]", "tests/test_color.py::test_color_success[", "tests/test_color.py::test_color_success[777", "tests/test_color.py::test_color_success[raw_color15-as_tuple15]", "tests/test_color.py::test_color_success[raw_color16-as_tuple16]", "tests/test_color.py::test_color_success[raw_color17-as_tuple17]", "tests/test_color.py::test_color_success[raw_color18-as_tuple18]", "tests/test_color.py::test_color_success[rgb(0,", "tests/test_color.py::test_color_success[rgba(0,", "tests/test_color.py::test_color_success[rgba(00,0,128,0.6", "tests/test_color.py::test_color_success[hsl(270,", "tests/test_color.py::test_color_success[hsl(180,", "tests/test_color.py::test_color_success[hsl(630,", "tests/test_color.py::test_color_success[hsl(270deg,", "tests/test_color.py::test_color_success[hsl(.75turn,", "tests/test_color.py::test_color_success[hsl(-.25turn,", "tests/test_color.py::test_color_success[hsl(-0.25turn,", "tests/test_color.py::test_color_success[hsl(4.71238rad,", "tests/test_color.py::test_color_success[hsl(10.9955rad,", "tests/test_color.py::test_color_success[hsl(270.00deg,", "tests/test_color.py::test_color_fail[nosuchname]", "tests/test_color.py::test_color_fail[chucknorris]", "tests/test_color.py::test_color_fail[#0000000]", "tests/test_color.py::test_color_fail[x000]", "tests/test_color.py::test_color_fail[color4]", "tests/test_color.py::test_color_fail[color5]", "tests/test_color.py::test_color_fail[color6]", "tests/test_color.py::test_color_fail[color7]", "tests/test_color.py::test_color_fail[color8]", "tests/test_color.py::test_color_fail[color9]", "tests/test_color.py::test_color_fail[color10]", "tests/test_color.py::test_color_fail[color11]", "tests/test_color.py::test_color_fail[color12]", "tests/test_color.py::test_color_fail[color13]", "tests/test_color.py::test_color_fail[rgb(0,", "tests/test_color.py::test_color_fail[rgba(0,", "tests/test_color.py::test_color_fail[hsl(180,", "tests/test_color.py::test_color_fail[color19]", "tests/test_color.py::test_color_fail[object]", "tests/test_color.py::test_color_fail[color21]", "tests/test_color.py::test_model_validation", "tests/test_color.py::test_as_rgb", "tests/test_color.py::test_as_rgb_tuple", "tests/test_color.py::test_as_hsl", "tests/test_color.py::test_as_hsl_tuple", "tests/test_color.py::test_as_hex", "tests/test_color.py::test_as_named", "tests/test_color.py::test_str_repr" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2022-01-09 18:56:15+00:00
mit
4,851
pydantic__pydantic-3681
diff --git a/pydantic/fields.py b/pydantic/fields.py --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -35,6 +35,7 @@ Callable, ForwardRef, NoArgAnyCallable, + convert_generics, display_as_type, get_args, get_origin, @@ -396,7 +397,7 @@ def __init__( self.name: str = name self.has_alias: bool = bool(alias) self.alias: str = alias or name - self.type_: Any = type_ + self.type_: Any = convert_generics(type_) self.outer_type_: Any = type_ self.class_validators = class_validators or {} self.default: Any = default diff --git a/pydantic/typing.py b/pydantic/typing.py --- a/pydantic/typing.py +++ b/pydantic/typing.py @@ -38,6 +38,12 @@ # python < 3.9 does not have GenericAlias (list[int], tuple[str, ...] and so on) TypingGenericAlias = () +try: + from types import UnionType as TypesUnionType # type: ignore +except ImportError: + # python < 3.10 does not have UnionType (str | int, byte | bool and so on) + TypesUnionType = () + if sys.version_info < (3, 9): @@ -145,6 +151,63 @@ 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, 9): + + def convert_generics(tp: Type[Any]) -> Type[Any]: + """Python 3.9 and older only supports generics from `typing` module. + They convert strings to ForwardRef automatically. + + Examples:: + typing.List['Hero'] == typing.List[ForwardRef('Hero')] + """ + return tp + +else: + from typing import _UnionGenericAlias # type: ignore + + from typing_extensions import _AnnotatedAlias + + def convert_generics(tp: Type[Any]) -> Type[Any]: + """ + Recursively searches for `str` type hints and replaces them with ForwardRef. + + Examples:: + convert_generics(list['Hero']) == list[ForwardRef('Hero')] + convert_generics(dict['Hero', 'Team']) == dict[ForwardRef('Hero'), ForwardRef('Team')] + convert_generics(typing.Dict['Hero', 'Team']) == typing.Dict[ForwardRef('Hero'), ForwardRef('Team')] + convert_generics(list[str | 'Hero'] | int) == list[str | ForwardRef('Hero')] | int + """ + origin = get_origin(tp) + if not origin or not hasattr(tp, '__args__'): + return tp + + args = get_args(tp) + + # typing.Annotated needs special treatment + if origin is Annotated: + return _AnnotatedAlias(convert_generics(args[0]), args[1:]) + + # recursively replace `str` instances inside of `GenericAlias` with `ForwardRef(arg)` + converted = tuple( + ForwardRef(arg) if isinstance(arg, str) and isinstance(tp, TypingGenericAlias) else convert_generics(arg) + for arg in args + ) + + if converted == args: + return tp + elif isinstance(tp, TypingGenericAlias): + return TypingGenericAlias(origin, converted) + elif isinstance(tp, TypesUnionType): + # recreate types.UnionType (PEP604, Python >= 3.10) + return _UnionGenericAlias(origin, converted) + else: + try: + setattr(tp, '__args__', converted) + except AttributeError: + pass + return tp + + if sys.version_info < (3, 10): def is_union(tp: Optional[Type[Any]]) -> bool:
pydantic/pydantic
f4197103815fba6546b4a3a7e5cccdd8b5a8f3be
It seems there are two problems, the first one is what you mentioned in the issue, which aparently can be solved by using the legacy types in Typing. I believe that is problematic since PEP 585 was supposed to make list and List equal(at least from my understanding). ``` from typing import TypedDict, List from pydantic import BaseModel class A(TypedDict): a: List['A'] class B(BaseModel): a: A ``` The problem with this code now becomes a maximum recursion depth. But that's a completly different problem. ``` ... File "/home/luccas/Projetos/pydantic/pydantic/typing.py", line 355, in is_literal_type return Literal is not None and get_origin(type_) is Literal File "/home/luccas/Projetos/pydantic/pydantic/typing.py", line 124, in get_origin return _typing_get_origin(tp) or getattr(tp, '__origin__', None) File "/usr/lib/python3.9/typing.py", line 1510, in get_origin if isinstance(tp, (_BaseGenericAlias, GenericAlias)): RecursionError: maximum recursion depth exceeded in __instancecheck__ ``` This for example works ``` from typing import TypedDict, List from pydantic import BaseModel class A(TypedDict): foo: int bar: str class B(BaseModel): a: List['A'] ``` Output of python -c "import pydantic.utils; print(pydantic.utils.version_info())": ``` pydantic version: 1.8.2 pydantic compiled: False install path: /home/luccas/Projetos/pydantic/pydantic python version: 3.9.7 (default, Aug 31 2021, 13:28:12) [GCC 11.1.0] platform: Linux-5.4.148-1-MANJARO-x86_64-with-glibc2.33 optional deps. installed: ['devtools', 'dotenv', 'email-validator', 'typing-extensions'] ```
diff --git a/tests/test_forward_ref.py b/tests/test_forward_ref.py --- a/tests/test_forward_ref.py +++ b/tests/test_forward_ref.py @@ -672,6 +672,48 @@ class Config: assert m.json(models_as_dict=False) == '{"name": "anne", "friends": ["User(ben)", "User(charlie)"]}' +skip_pep585 = pytest.mark.skipif( + sys.version_info < (3, 9), reason='PEP585 generics only supported for python 3.9 and above' +) + + +@skip_pep585 +def test_pep585_self_referencing_generics(): + class SelfReferencing(BaseModel): + names: list['SelfReferencing'] # noqa: F821 + + SelfReferencing.update_forward_refs() # will raise an exception if the forward ref isn't resolvable + # test the class + assert SelfReferencing.__fields__['names'].type_ is SelfReferencing + # NOTE: outer_type_ is not converted + assert SelfReferencing.__fields__['names'].outer_type_ == list['SelfReferencing'] + # test that object creation works + obj = SelfReferencing(names=[SelfReferencing(names=[])]) + assert obj.names == [SelfReferencing(names=[])] + + +@skip_pep585 +def test_pep585_recursive_generics(create_module): + @create_module + def module(): + from pydantic import BaseModel + + class Team(BaseModel): + name: str + heroes: list['Hero'] # noqa: F821 + + class Hero(BaseModel): + name: str + teams: list[Team] + + Team.update_forward_refs() + + assert module.Team.__fields__['heroes'].type_ is module.Hero + assert module.Hero.__fields__['teams'].type_ is module.Team + + module.Hero(name='Ivan', teams=[module.Team(name='TheBest', heroes=[])]) + + @pytest.mark.skipif(sys.version_info < (3, 9), reason='needs 3.9 or newer') def test_class_var_forward_ref(create_module): # see #3679 diff --git a/tests/test_typing.py b/tests/test_typing.py --- a/tests/test_typing.py +++ b/tests/test_typing.py @@ -1,9 +1,12 @@ +import sys from collections import namedtuple -from typing import Callable as TypingCallable, NamedTuple +from typing import Any, Callable as TypingCallable, Dict, ForwardRef, List, NamedTuple, NewType, Union # noqa: F401 import pytest +from typing_extensions import Annotated # noqa: F401 -from pydantic.typing import Literal, is_namedtuple, is_none_type, is_typeddict +from pydantic import Field # noqa: F401 +from pydantic.typing import Literal, convert_generics, is_namedtuple, is_none_type, is_typeddict try: from typing import TypedDict as typing_TypedDict @@ -66,3 +69,58 @@ def test_is_none_type(): # `collections.abc.Callable` (even with python >= 3.9) as they behave # differently assert is_none_type(TypingCallable) is False + + +class Hero: + pass + + +class Team: + pass + + [email protected](sys.version_info < (3, 9), reason='PEP585 generics only supported for python 3.9 and above.') [email protected]( + ['type_', 'expectations'], + [ + ('int', 'int'), + ('Union[list["Hero"], int]', 'Union[list[ForwardRef("Hero")], int]'), + ('list["Hero"]', 'list[ForwardRef("Hero")]'), + ('dict["Hero", "Team"]', 'dict[ForwardRef("Hero"), ForwardRef("Team")]'), + ('dict["Hero", list["Team"]]', 'dict[ForwardRef("Hero"), list[ForwardRef("Team")]]'), + ('dict["Hero", List["Team"]]', 'dict[ForwardRef("Hero"), List[ForwardRef("Team")]]'), + ('Dict["Hero", list["Team"]]', 'Dict[ForwardRef("Hero"), list[ForwardRef("Team")]]'), + ( + 'Annotated[list["Hero"], Field(min_length=2)]', + 'Annotated[list[ForwardRef("Hero")], Field(min_length=2)]', + ), + ], +) +def test_convert_generics(type_, expectations): + assert str(convert_generics(eval(type_))) == str(eval(expectations)) + + [email protected](sys.version_info < (3, 10), reason='NewType class was added in python 3.10.') +def test_convert_generics_unsettable_args(): + class User(NewType): + + __origin__ = type(list[str]) + __args__ = (list['Hero'],) + + def __init__(self, name: str, tp: type) -> None: + super().__init__(name, tp) + + def __setattr__(self, __name: str, __value: Any) -> None: + if __name == '__args__': + raise AttributeError # will be thrown during the generics conversion + return super().__setattr__(__name, __value) + + # tests that convert_generics will not throw an exception even if __args__ isn't settable + assert convert_generics(User('MyUser', str)).__args__ == (list['Hero'],) + + [email protected](sys.version_info < (3, 10), reason='PEP604 unions only supported for python 3.10 and above.') +def test_convert_generics_pep604(): + assert ( + convert_generics(dict['Hero', list['Team']] | int) == dict[ForwardRef('Hero'), list[ForwardRef('Team')]] | int + )
Recursive list of TypedDicts doesn't work # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.8 pydantic compiled: True install path: /usr/local/lib/python3.9/dist-packages/pydantic python version: 3.9.6 (default, Jul 3 2021, 17:50:42) [GCC 7.5.0] platform: Linux-5.4.0-66-generic-x86_64-with-glibc2.27 optional deps. installed: ['typing-extensions'] ``` ```py from typing import TypedDict from pydantic import BaseModel class A(TypedDict): a: list['A'] class B(BaseModel): a: A ``` Result: "RuntimeError: error checking inheritance of 'A' (type: str)" Adding `from __future__ import annotations` doesn't help
0.0
f4197103815fba6546b4a3a7e5cccdd8b5a8f3be
[ "tests/test_forward_ref.py::test_postponed_annotations", "tests/test_forward_ref.py::test_postponed_annotations_optional", "tests/test_forward_ref.py::test_postponed_annotations_auto_update_forward_refs", "tests/test_forward_ref.py::test_forward_ref_auto_update_no_model", "tests/test_forward_ref.py::test_forward_ref_one_of_fields_not_defined", "tests/test_forward_ref.py::test_basic_forward_ref", "tests/test_forward_ref.py::test_self_forward_ref_module", "tests/test_forward_ref.py::test_self_forward_ref_collection", "tests/test_forward_ref.py::test_self_forward_ref_local", "tests/test_forward_ref.py::test_missing_update_forward_refs", "tests/test_forward_ref.py::test_forward_ref_dataclass", "tests/test_forward_ref.py::test_forward_ref_dataclass_with_future_annotations", "tests/test_forward_ref.py::test_forward_ref_sub_types", "tests/test_forward_ref.py::test_forward_ref_nested_sub_types", "tests/test_forward_ref.py::test_self_reference_json_schema", "tests/test_forward_ref.py::test_self_reference_json_schema_with_future_annotations", "tests/test_forward_ref.py::test_circular_reference_json_schema", "tests/test_forward_ref.py::test_circular_reference_json_schema_with_future_annotations", "tests/test_forward_ref.py::test_forward_ref_with_field", "tests/test_forward_ref.py::test_forward_ref_optional", "tests/test_forward_ref.py::test_forward_ref_with_create_model", "tests/test_forward_ref.py::test_resolve_forward_ref_dataclass", "tests/test_forward_ref.py::test_nested_forward_ref", "tests/test_forward_ref.py::test_discriminated_union_forward_ref", "tests/test_forward_ref.py::test_class_var_as_string", "tests/test_forward_ref.py::test_json_encoder_str", "tests/test_forward_ref.py::test_json_encoder_forward_ref", "tests/test_typing.py::test_is_namedtuple", "tests/test_typing.py::test_is_typeddict_typing[TypedDict0]", "tests/test_typing.py::test_is_typeddict_typing[TypedDict1]", "tests/test_typing.py::test_is_none_type" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-01-17 01:41:47+00:00
mit
4,852
pydantic__pydantic-3819
diff --git a/pydantic/schema.py b/pydantic/schema.py --- a/pydantic/schema.py +++ b/pydantic/schema.py @@ -419,10 +419,13 @@ def get_flat_models_from_field(field: ModelField, known_models: TypeModelSet) -> # Handle dataclass-based models if is_builtin_dataclass(field.type_): field.type_ = dataclass(field.type_) + was_dataclass = True + else: + was_dataclass = False field_type = field.type_ if lenient_issubclass(getattr(field_type, '__pydantic_model__', None), BaseModel): field_type = field_type.__pydantic_model__ - if field.sub_fields and not lenient_issubclass(field_type, BaseModel): + if field.sub_fields and (not lenient_issubclass(field_type, BaseModel) or was_dataclass): flat_models |= get_flat_models_from_fields(field.sub_fields, known_models=known_models) elif lenient_issubclass(field_type, BaseModel) and field_type not in known_models: flat_models |= get_flat_models_from_model(field_type, known_models=known_models)
pydantic/pydantic
9d631a3429a66f30742c1a52c94ac18ec6ba848d
diff --git a/tests/test_schema.py b/tests/test_schema.py --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -2884,3 +2884,34 @@ class Model(BaseModel): }, }, } + + +def test_nested_python_dataclasses(): + """ + Test schema generation for nested python dataclasses + """ + + from dataclasses import dataclass as python_dataclass + + @python_dataclass + class ChildModel: + name: str + + @python_dataclass + class NestedModel: + child: List[ChildModel] + + assert model_schema(dataclass(NestedModel)) == { + 'title': 'NestedModel', + 'type': 'object', + 'properties': {'child': {'title': 'Child', 'type': 'array', 'items': {'$ref': '#/definitions/ChildModel'}}}, + 'required': ['child'], + 'definitions': { + 'ChildModel': { + 'title': 'ChildModel', + 'type': 'object', + 'properties': {'name': {'title': 'Name', 'type': 'string'}}, + 'required': ['name'], + } + }, + }
list of python dataclass broken after upgrade to 1.9.0 ### Checks * [x] I added a descriptive title to this issue * [x] I have searched (google, github) for similar issues and couldn't find anything * [x] I have read and followed [the docs](https://pydantic-docs.helpmanual.io/) and still think this is a bug <!-- Sorry to sound so draconian, but every second saved replying to issues is time spend improving pydantic :-) --> # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.9.0 pydantic compiled: True install path: my_directory/venv/lib/python3.8/site-packages/pydantic python version: 3.8.6 (default, Sep 6 2021, 17:04:40) [GCC 10.3.0] platform: Linux-5.13.0-28-generic-x86_64-with-glibc2.33 optional deps. installed: ['typing-extensions'] ``` <!-- or if you're using pydantic prior to v1.3, manually include: OS, python version and pydantic version --> <!-- Please read the [docs](https://pydantic-docs.helpmanual.io/) and search through issues to confirm your bug hasn't already been reported. --> <!-- Where possible please include a self-contained code snippet describing your bug: --> The following snippet works as expected with version 1.8.2 but errors with version 1.9.0 ```py from dataclasses import dataclass from typing import List import pydantic @dataclass() class A: a: int = 5 @dataclass() class B_and_As: list_of_as: List[A] b: str = 'b' def get_schema(json_cls: dataclass): as_pydantic = pydantic.dataclasses.dataclass(json_cls) schema = as_pydantic.__pydantic_model__.schema() print(schema) get_schema(B_and_As) ``` error: ``` schema = as_pydantic.__pydantic_model__.schema() File "pydantic/main.py", line 647, in pydantic.main.BaseModel.schema File "pydantic/schema.py", line 185, in pydantic.schema.model_schema File "pydantic/schema.py", line 617, in pydantic.schema.model_process_schema File "pydantic/schema.py", line 658, in pydantic.schema.model_type_schema File "pydantic/schema.py", line 258, in pydantic.schema.field_schema File "pydantic/schema.py", line 498, in pydantic.schema.field_type_schema File "pydantic/schema.py", line 848, in pydantic.schema.field_singleton_schema File "pydantic/schema.py", line 736, in pydantic.schema.field_singleton_sub_fields_schema File "pydantic/schema.py", line 563, in pydantic.schema.field_type_schema File "pydantic/schema.py", line 947, in pydantic.schema.field_singleton_schema ValueError: Value not declarable with JSON Schema, field: name='_list_of_as' type=A required=True ``` on 1.8.2 it's prints as expected: ``` {'title': 'B_and_As', 'type': 'object', 'properties': {'list_of_as': {'title': 'List Of As', 'type': 'array', 'items': {'$ref': '#/definitions/A'}}, 'b': {'title': 'B', 'default': 'b', 'type': 'string'}}, 'required': ['list_of_as'], 'definitions': {'A': {'title': 'A', 'type': 'object', 'properties': {'a': {'title': 'A', 'default': 5, 'type': 'integer'}}}}} ``` Btw: * `get_schema(A)` works in both versions * [Discussed on stackoverflow](https://stackoverflow.com/questions/71048746/how-can-i-generate-json-schema-for-list-of-dataclass-with-pydantic)
0.0
9d631a3429a66f30742c1a52c94ac18ec6ba848d
[ "tests/test_schema.py::test_nested_python_dataclasses" ]
[ "tests/test_schema.py::test_key", "tests/test_schema.py::test_by_alias", "tests/test_schema.py::test_ref_template", "tests/test_schema.py::test_by_alias_generator", "tests/test_schema.py::test_sub_model", "tests/test_schema.py::test_schema_class", "tests/test_schema.py::test_schema_repr", "tests/test_schema.py::test_schema_class_by_alias", "tests/test_schema.py::test_choices", "tests/test_schema.py::test_enum_modify_schema", "tests/test_schema.py::test_enum_schema_custom_field", "tests/test_schema.py::test_enum_and_model_have_same_behaviour", "tests/test_schema.py::test_enum_includes_extra_without_other_params", "tests/test_schema.py::test_list_enum_schema_extras", "tests/test_schema.py::test_json_schema", "tests/test_schema.py::test_list_sub_model", "tests/test_schema.py::test_optional", "tests/test_schema.py::test_any", "tests/test_schema.py::test_set", "tests/test_schema.py::test_const_str", "tests/test_schema.py::test_const_false", "tests/test_schema.py::test_tuple[tuple-extra_props0]", "tests/test_schema.py::test_tuple[field_type1-extra_props1]", "tests/test_schema.py::test_tuple[field_type2-extra_props2]", "tests/test_schema.py::test_tuple[field_type3-extra_props3]", "tests/test_schema.py::test_deque", "tests/test_schema.py::test_bool", "tests/test_schema.py::test_strict_bool", "tests/test_schema.py::test_dict", "tests/test_schema.py::test_list", "tests/test_schema.py::test_list_union_dict[field_type0-expected_schema0]", "tests/test_schema.py::test_list_union_dict[field_type1-expected_schema1]", "tests/test_schema.py::test_list_union_dict[field_type2-expected_schema2]", "tests/test_schema.py::test_list_union_dict[field_type3-expected_schema3]", "tests/test_schema.py::test_list_union_dict[field_type4-expected_schema4]", "tests/test_schema.py::test_date_types[datetime-expected_schema0]", "tests/test_schema.py::test_date_types[date-expected_schema1]", "tests/test_schema.py::test_date_types[time-expected_schema2]", "tests/test_schema.py::test_date_types[timedelta-expected_schema3]", "tests/test_schema.py::test_str_basic_types[field_type0-expected_schema0]", "tests/test_schema.py::test_str_basic_types[field_type1-expected_schema1]", "tests/test_schema.py::test_str_basic_types[field_type2-expected_schema2]", "tests/test_schema.py::test_str_basic_types[field_type3-expected_schema3]", "tests/test_schema.py::test_str_constrained_types[StrictStr-expected_schema0]", "tests/test_schema.py::test_str_constrained_types[ConstrainedStr-expected_schema1]", "tests/test_schema.py::test_str_constrained_types[ConstrainedStrValue-expected_schema2]", "tests/test_schema.py::test_special_str_types[AnyUrl-expected_schema0]", "tests/test_schema.py::test_special_str_types[UrlValue-expected_schema1]", "tests/test_schema.py::test_email_str_types[EmailStr-email]", "tests/test_schema.py::test_email_str_types[NameEmail-name-email]", "tests/test_schema.py::test_secret_types[SecretBytes-string]", "tests/test_schema.py::test_secret_types[SecretStr-string]", "tests/test_schema.py::test_special_int_types[ConstrainedInt-expected_schema0]", "tests/test_schema.py::test_special_int_types[ConstrainedIntValue-expected_schema1]", "tests/test_schema.py::test_special_int_types[ConstrainedIntValue-expected_schema2]", "tests/test_schema.py::test_special_int_types[ConstrainedIntValue-expected_schema3]", "tests/test_schema.py::test_special_int_types[PositiveInt-expected_schema4]", "tests/test_schema.py::test_special_int_types[NegativeInt-expected_schema5]", "tests/test_schema.py::test_special_int_types[NonNegativeInt-expected_schema6]", "tests/test_schema.py::test_special_int_types[NonPositiveInt-expected_schema7]", "tests/test_schema.py::test_special_float_types[ConstrainedFloat-expected_schema0]", "tests/test_schema.py::test_special_float_types[ConstrainedFloatValue-expected_schema1]", "tests/test_schema.py::test_special_float_types[ConstrainedFloatValue-expected_schema2]", "tests/test_schema.py::test_special_float_types[ConstrainedFloatValue-expected_schema3]", "tests/test_schema.py::test_special_float_types[PositiveFloat-expected_schema4]", "tests/test_schema.py::test_special_float_types[NegativeFloat-expected_schema5]", "tests/test_schema.py::test_special_float_types[NonNegativeFloat-expected_schema6]", "tests/test_schema.py::test_special_float_types[NonPositiveFloat-expected_schema7]", "tests/test_schema.py::test_special_float_types[ConstrainedDecimal-expected_schema8]", "tests/test_schema.py::test_special_float_types[ConstrainedDecimalValue-expected_schema9]", "tests/test_schema.py::test_special_float_types[ConstrainedDecimalValue-expected_schema10]", "tests/test_schema.py::test_special_float_types[ConstrainedDecimalValue-expected_schema11]", "tests/test_schema.py::test_uuid_types[UUID-uuid]", "tests/test_schema.py::test_uuid_types[UUID1-uuid1]", "tests/test_schema.py::test_uuid_types[UUID3-uuid3]", "tests/test_schema.py::test_uuid_types[UUID4-uuid4]", "tests/test_schema.py::test_uuid_types[UUID5-uuid5]", "tests/test_schema.py::test_path_types[FilePath-file-path]", "tests/test_schema.py::test_path_types[DirectoryPath-directory-path]", "tests/test_schema.py::test_path_types[Path-path]", "tests/test_schema.py::test_json_type", "tests/test_schema.py::test_ipv4address_type", "tests/test_schema.py::test_ipv6address_type", "tests/test_schema.py::test_ipvanyaddress_type", "tests/test_schema.py::test_ipv4interface_type", "tests/test_schema.py::test_ipv6interface_type", "tests/test_schema.py::test_ipvanyinterface_type", "tests/test_schema.py::test_ipv4network_type", "tests/test_schema.py::test_ipv6network_type", "tests/test_schema.py::test_ipvanynetwork_type", "tests/test_schema.py::test_callable_type[type_0-default_value0]", "tests/test_schema.py::test_callable_type[type_1-<lambda>]", "tests/test_schema.py::test_callable_type[type_2-default_value2]", "tests/test_schema.py::test_callable_type[type_3-<lambda>]", "tests/test_schema.py::test_error_non_supported_types", "tests/test_schema.py::test_flat_models_unique_models", "tests/test_schema.py::test_flat_models_with_submodels", "tests/test_schema.py::test_flat_models_with_submodels_from_sequence", "tests/test_schema.py::test_model_name_maps", "tests/test_schema.py::test_schema_overrides", "tests/test_schema.py::test_schema_overrides_w_union", "tests/test_schema.py::test_schema_from_models", "tests/test_schema.py::test_schema_with_refs[#/components/schemas/-None]", "tests/test_schema.py::test_schema_with_refs[None-#/components/schemas/{model}]", "tests/test_schema.py::test_schema_with_refs[#/components/schemas/-#/{model}/schemas/]", "tests/test_schema.py::test_schema_with_custom_ref_template", "tests/test_schema.py::test_schema_ref_template_key_error", "tests/test_schema.py::test_schema_no_definitions", "tests/test_schema.py::test_list_default", "tests/test_schema.py::test_enum_str_default", "tests/test_schema.py::test_enum_int_default", "tests/test_schema.py::test_dict_default", "tests/test_schema.py::test_constraints_schema[kwargs0-str-expected_extra0]", "tests/test_schema.py::test_constraints_schema[kwargs1-ConstrainedStrValue-expected_extra1]", "tests/test_schema.py::test_constraints_schema[kwargs2-str-expected_extra2]", "tests/test_schema.py::test_constraints_schema[kwargs3-bytes-expected_extra3]", "tests/test_schema.py::test_constraints_schema[kwargs4-str-expected_extra4]", "tests/test_schema.py::test_constraints_schema[kwargs5-int-expected_extra5]", "tests/test_schema.py::test_constraints_schema[kwargs6-int-expected_extra6]", "tests/test_schema.py::test_constraints_schema[kwargs7-int-expected_extra7]", "tests/test_schema.py::test_constraints_schema[kwargs8-int-expected_extra8]", "tests/test_schema.py::test_constraints_schema[kwargs9-int-expected_extra9]", "tests/test_schema.py::test_constraints_schema[kwargs10-float-expected_extra10]", "tests/test_schema.py::test_constraints_schema[kwargs11-float-expected_extra11]", "tests/test_schema.py::test_constraints_schema[kwargs12-float-expected_extra12]", "tests/test_schema.py::test_constraints_schema[kwargs13-float-expected_extra13]", "tests/test_schema.py::test_constraints_schema[kwargs14-float-expected_extra14]", "tests/test_schema.py::test_constraints_schema[kwargs15-float-expected_extra15]", "tests/test_schema.py::test_constraints_schema[kwargs16-float-expected_extra16]", "tests/test_schema.py::test_constraints_schema[kwargs17-float-expected_extra17]", "tests/test_schema.py::test_constraints_schema[kwargs18-float-expected_extra18]", "tests/test_schema.py::test_constraints_schema[kwargs19-Decimal-expected_extra19]", "tests/test_schema.py::test_constraints_schema[kwargs20-Decimal-expected_extra20]", "tests/test_schema.py::test_constraints_schema[kwargs21-Decimal-expected_extra21]", "tests/test_schema.py::test_constraints_schema[kwargs22-Decimal-expected_extra22]", "tests/test_schema.py::test_constraints_schema[kwargs23-Decimal-expected_extra23]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs0-int]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs1-float]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs2-Decimal]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs3-bool]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs4-int]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs5-str]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs6-bytes]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs7-str]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs8-bool]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs9-type_9]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs10-type_10]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs11-ConstrainedListValue]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs12-ConstrainedSetValue]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs13-ConstrainedFrozenSetValue]", "tests/test_schema.py::test_constraints_schema_validation[kwargs0-str-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs1-str-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs2-bytes-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs3-str-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs4-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs5-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs6-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs7-int-2]", "tests/test_schema.py::test_constraints_schema_validation[kwargs8-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs9-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs10-int-5]", "tests/test_schema.py::test_constraints_schema_validation[kwargs11-float-3.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs12-float-2.1]", "tests/test_schema.py::test_constraints_schema_validation[kwargs13-float-3.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs14-float-4.9]", "tests/test_schema.py::test_constraints_schema_validation[kwargs15-float-3.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs16-float-2.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs17-float-3.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs18-float-5.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs19-float-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs20-float-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs21-Decimal-value21]", "tests/test_schema.py::test_constraints_schema_validation[kwargs22-Decimal-value22]", "tests/test_schema.py::test_constraints_schema_validation[kwargs23-Decimal-value23]", "tests/test_schema.py::test_constraints_schema_validation[kwargs24-Decimal-value24]", "tests/test_schema.py::test_constraints_schema_validation[kwargs25-Decimal-value25]", "tests/test_schema.py::test_constraints_schema_validation[kwargs26-Decimal-value26]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs0-str-foobar]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs1-str-f]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs2-str-bar]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs3-int-2]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs4-int-5]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs5-int-1]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs6-int-6]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs7-float-2.0]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs8-float-5.0]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs9-float-1.9]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs10-float-5.1]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs11-Decimal-value11]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs12-Decimal-value12]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs13-Decimal-value13]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs14-Decimal-value14]", "tests/test_schema.py::test_schema_kwargs", "tests/test_schema.py::test_schema_dict_constr", "tests/test_schema.py::test_bytes_constrained_types[ConstrainedBytes-expected_schema0]", "tests/test_schema.py::test_bytes_constrained_types[ConstrainedBytesValue-expected_schema1]", "tests/test_schema.py::test_optional_dict", "tests/test_schema.py::test_optional_validator", "tests/test_schema.py::test_field_with_validator", "tests/test_schema.py::test_unparameterized_schema_generation", "tests/test_schema.py::test_known_model_optimization", "tests/test_schema.py::test_root", "tests/test_schema.py::test_root_list", "tests/test_schema.py::test_root_nested_model", "tests/test_schema.py::test_new_type_schema", "tests/test_schema.py::test_literal_schema", "tests/test_schema.py::test_literal_enum", "tests/test_schema.py::test_color_type", "tests/test_schema.py::test_model_with_schema_extra", "tests/test_schema.py::test_model_with_schema_extra_callable", "tests/test_schema.py::test_model_with_schema_extra_callable_no_model_class", "tests/test_schema.py::test_model_with_schema_extra_callable_classmethod", "tests/test_schema.py::test_model_with_schema_extra_callable_instance_method", "tests/test_schema.py::test_model_with_extra_forbidden", "tests/test_schema.py::test_enforced_constraints[int-kwargs0-field_schema0]", "tests/test_schema.py::test_enforced_constraints[annotation1-kwargs1-field_schema1]", "tests/test_schema.py::test_enforced_constraints[annotation2-kwargs2-field_schema2]", "tests/test_schema.py::test_enforced_constraints[annotation3-kwargs3-field_schema3]", "tests/test_schema.py::test_enforced_constraints[annotation4-kwargs4-field_schema4]", "tests/test_schema.py::test_enforced_constraints[annotation5-kwargs5-field_schema5]", "tests/test_schema.py::test_enforced_constraints[annotation6-kwargs6-field_schema6]", "tests/test_schema.py::test_enforced_constraints[annotation7-kwargs7-field_schema7]", "tests/test_schema.py::test_real_vs_phony_constraints", "tests/test_schema.py::test_subfield_field_info", "tests/test_schema.py::test_dataclass", "tests/test_schema.py::test_schema_attributes", "tests/test_schema.py::test_model_process_schema_enum", "tests/test_schema.py::test_path_modify_schema", "tests/test_schema.py::test_frozen_set", "tests/test_schema.py::test_iterable", "tests/test_schema.py::test_new_type", "tests/test_schema.py::test_multiple_models_with_same_name", "tests/test_schema.py::test_multiple_enums_with_same_name", "tests/test_schema.py::test_schema_for_generic_field", "tests/test_schema.py::test_namedtuple_default", "tests/test_schema.py::test_advanced_generic_schema", "tests/test_schema.py::test_nested_generic", "tests/test_schema.py::test_nested_generic_model", "tests/test_schema.py::test_complex_nested_generic", "tests/test_schema.py::test_schema_with_field_parameter", "tests/test_schema.py::test_discriminated_union", "tests/test_schema.py::test_discriminated_annotated_union", "tests/test_schema.py::test_alias_same" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2022-02-15 09:07:02+00:00
mit
4,853
pydantic__pydantic-3847
diff --git a/pydantic/fields.py b/pydantic/fields.py --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -1086,7 +1086,7 @@ def _validate_discriminated_union( except TypeError: try: # BaseModel or dataclass - discriminator_value = getattr(v, self.discriminator_alias) + discriminator_value = getattr(v, self.discriminator_key) except (AttributeError, TypeError): return v, ErrorWrapper(MissingDiscriminator(discriminator_key=self.discriminator_key), loc)
pydantic/pydantic
8846ec4685e749b93907081450f592060eeb99b1
diff --git a/tests/test_discrimated_union.py b/tests/test_discrimated_union.py --- a/tests/test_discrimated_union.py +++ b/tests/test_discrimated_union.py @@ -267,6 +267,24 @@ class Top(BaseModel): assert isinstance(t, Top) +def test_discriminated_union_basemodel_instance_value_with_alias(): + class A(BaseModel): + literal: Literal['a'] = Field(alias='lit') + + class B(BaseModel): + literal: Literal['b'] = Field(alias='lit') + + class Config: + allow_population_by_field_name = True + + class Top(BaseModel): + sub: Union[A, B] = Field(..., discriminator='literal') + + assert Top(sub=A(lit='a')).sub.literal == 'a' + assert Top(sub=B(lit='b')).sub.literal == 'b' + assert Top(sub=B(literal='b')).sub.literal == 'b' + + def test_discriminated_union_int(): class A(BaseModel): l: Literal[1]
Discriminator field on BaseModel instances are incorrectly accessed by alias in validation ### Checks * [x] I added a descriptive title to this issue * [x] I have searched (google, github) for similar issues and couldn't find anything * [x] I have read and followed [the docs](https://pydantic-docs.helpmanual.io/) and still think this is a bug # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` $ python -c "import pydantic.utils; print(pydantic.utils.version_info())" pydantic version: 1.9.0 pydantic compiled: True install path: ./venv/lib/python3.10/site-packages/pydantic python version: 3.10.2 (main, Jan 17 2022, 00:00:00) [GCC 11.2.1 20211203 (Red Hat 11.2.1-7)] platform: Linux-5.16.9-200.fc35.x86_64-x86_64-with-glibc2.34 optional deps. installed: ['typing-extensions'] ``` When validating a discriminated union where the union value has been passed as a Pydantic model instance, it appears that the `_validate_discriminated_union` function is trying to access the value of the discriminator field via its alias. Since the alias does not exist on the model as an attribute, the validation fails. I believe this is the result of a tiny mistake when setting up the `_validate_discriminated_union` function and that whenever a `BaseModel` or dataclass is detected then we should use the discriminator key and not the alias to access the discriminator value. ```py from typing import Literal, Union from pydantic import BaseModel, Field class A(BaseModel): literal: Literal['a'] = Field(alias='lit') class B(BaseModel): literal: Literal['b'] = Field(alias='lit') class Config: allow_population_by_field_name = True class Top(BaseModel): sub: Union[A, B] = Field(..., discriminator='literal') Top(sub=A(lit='a')) # pydantic.error_wrappers.ValidationError: 1 validation error for Top # sub # Discriminator 'literal' is missing in value (type=value_error.discriminated_union.missing_discriminator; discriminator_key=literal) Top(sub=B(lit='b')) # pydantic.error_wrappers.ValidationError: 1 validation error for Top # sub # Discriminator 'literal' is missing in value (type=value_error.discriminated_union.missing_discriminator; discriminator_key=literal) Top(sub=B(literal='b')) # pydantic.error_wrappers.ValidationError: 1 validation error for Top # sub # Discriminator 'literal' is missing in value (type=value_error.discriminated_union.missing_discriminator; discriminator_key=literal) ```
0.0
8846ec4685e749b93907081450f592060eeb99b1
[ "tests/test_discrimated_union.py::test_discriminated_union_basemodel_instance_value_with_alias" ]
[ "tests/test_discrimated_union.py::test_discriminated_union_only_union", "tests/test_discrimated_union.py::test_discriminated_union_single_variant", "tests/test_discrimated_union.py::test_discriminated_union_invalid_type", "tests/test_discrimated_union.py::test_discriminated_union_defined_discriminator", "tests/test_discrimated_union.py::test_discriminated_union_literal_discriminator", "tests/test_discrimated_union.py::test_discriminated_union_root_same_discriminator", "tests/test_discrimated_union.py::test_discriminated_union_validation", "tests/test_discrimated_union.py::test_discriminated_annotated_union", "tests/test_discrimated_union.py::test_discriminated_union_basemodel_instance_value", "tests/test_discrimated_union.py::test_discriminated_union_int", "tests/test_discrimated_union.py::test_discriminated_union_enum", "tests/test_discrimated_union.py::test_alias_different", "tests/test_discrimated_union.py::test_alias_same", "tests/test_discrimated_union.py::test_nested", "tests/test_discrimated_union.py::test_generic" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2022-02-22 10:02:25+00:00
mit
4,854
pydantic__pydantic-3907
diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -53,6 +53,7 @@ update_model_forward_refs, ) from .utils import ( + DUNDER_ATTRIBUTES, ROOT_KEY, ClassAttribute, GetterDict, @@ -350,7 +351,7 @@ def __init__(__pydantic_self__, **data: Any) -> None: @no_type_check def __setattr__(self, name, value): # noqa: C901 (ignore complexity) - if name in self.__private_attributes__: + if name in self.__private_attributes__ or name in DUNDER_ATTRIBUTES: return object_setattr(self, name, value) if self.__config__.extra is not Extra.allow and name not in self.__fields__: @@ -891,7 +892,9 @@ def __eq__(self, other: Any) -> bool: def __repr_args__(self) -> 'ReprArgs': return [ - (k, v) for k, v in self.__dict__.items() if k not in self.__fields__ or self.__fields__[k].field_info.repr + (k, v) + for k, v in self.__dict__.items() + if k not in DUNDER_ATTRIBUTES and (k not in self.__fields__ or self.__fields__[k].field_info.repr) ] diff --git a/pydantic/utils.py b/pydantic/utils.py --- a/pydantic/utils.py +++ b/pydantic/utils.py @@ -76,6 +76,7 @@ 'ROOT_KEY', 'get_unique_discriminator_alias', 'get_discriminator_alias_and_values', + 'DUNDER_ATTRIBUTES', 'LimitedDict', ) @@ -680,15 +681,19 @@ def is_valid_field(name: str) -> bool: return ROOT_KEY == name +DUNDER_ATTRIBUTES = { + '__annotations__', + '__classcell__', + '__doc__', + '__module__', + '__orig_bases__', + '__orig_class__', + '__qualname__', +} + + def is_valid_private_name(name: str) -> bool: - return not is_valid_field(name) and name not in { - '__annotations__', - '__classcell__', - '__doc__', - '__module__', - '__orig_bases__', - '__qualname__', - } + return not is_valid_field(name) and name not in DUNDER_ATTRIBUTES _EMPTY = object()
pydantic/pydantic
cd439a4e8d38e082d3ca7bdbdd53ebb9e7d49680
I just hit something throwing the same error. Pydantic version 1.8.2 (because 1.9.0 doesn't work for other reasons). I'm getting a similar error while using generics ``` T = TypeVar('T', bound=BaseModel) class Paginated(Generic[T], BaseModel): total: int total_pages: int page: int per_page: int items: List[T] ``` and I'm doing something like this when it throws the error ``` Paginated[PydenticModelSchema]( total=qs._pagination.total_results, total_pages=qs._pagination.num_pages, page=qs._pagination.page_number, per_page=qs._pagination.page_size, items=qs.results, ) ``` but it works if I remove the generic type and just use `List[Any]` ``` class Paginated(BaseModel): total: int total_pages: int page: int per_page: int items: List[Any] ``` Is it because of the same bug? I couldn't find anything related to this online @iodsfx3d you should use `GenericModel` like explained in the doc ```py from pydantic.generics import GenericModel ... T = TypeVar('T', bound=BaseModel) class Paginated(GenericModel, Generic[T]): total: T Paginated[str](total='qwe') ``` @adriangb Yep indeed! `Annotated` seems to add a dunder attribute which can't be set because of our custom `__setattr__`. I'll make a quick fix
diff --git a/tests/test_main.py b/tests/test_main.py --- a/tests/test_main.py +++ b/tests/test_main.py @@ -19,6 +19,7 @@ from uuid import UUID, uuid4 import pytest +from typing_extensions import Annotated from pydantic import ( BaseConfig, @@ -2174,6 +2175,19 @@ class Model(BaseModel): } +def test_annotated_class(): + class PydanticModel(BaseModel): + foo: str = '123' + + PydanticAlias = Annotated[PydanticModel, 'bar baz'] + + pa = PydanticAlias() + assert isinstance(pa, PydanticModel) + pa.__doc__ = 'qwe' + assert repr(pa) == "PydanticModel(foo='123')" + assert pa.__doc__ == 'qwe' + + @pytest.mark.parametrize( 'ann', [Final, Final[int]],
bug: cannot instantiate PEP 593 type alias ```python from dataclasses import dataclass from typing import Annotated from pydantic import BaseModel @dataclass class DataclassModel: foo: str = "123" DataclassAlias = Annotated[DataclassModel, "bar baz"] DataclassAlias() # works class PydanticModel(BaseModel): foo: str = "123" PydanticAlias = Annotated[PydanticModel, "bar baz"] PydanticAlias() # error # File ".../typing.py", line 680, in __call__ # result.__orig_class__ = self # File "pydantic/main.py", line 347, in pydantic.main.BaseModel.__setattr__ # ValueError: "PydanticModel" object has no field "__orig_class__" ```
0.0
cd439a4e8d38e082d3ca7bdbdd53ebb9e7d49680
[ "tests/test_main.py::test_annotated_class" ]
[ "tests/test_main.py::test_success", "tests/test_main.py::test_ultra_simple_missing", "tests/test_main.py::test_ultra_simple_failed", "tests/test_main.py::test_ultra_simple_repr", "tests/test_main.py::test_default_factory_field", "tests/test_main.py::test_default_factory_no_type_field", "tests/test_main.py::test_comparing", "tests/test_main.py::test_nullable_strings_success", "tests/test_main.py::test_nullable_strings_fails", "tests/test_main.py::test_recursion", "tests/test_main.py::test_recursion_fails", "tests/test_main.py::test_not_required", "tests/test_main.py::test_infer_type", "tests/test_main.py::test_allow_extra", "tests/test_main.py::test_allow_extra_repr", "tests/test_main.py::test_forbidden_extra_success", "tests/test_main.py::test_forbidden_extra_fails", "tests/test_main.py::test_disallow_mutation", "tests/test_main.py::test_extra_allowed", "tests/test_main.py::test_extra_ignored", "tests/test_main.py::test_set_attr", "tests/test_main.py::test_set_attr_invalid", "tests/test_main.py::test_any", "tests/test_main.py::test_alias", "tests/test_main.py::test_population_by_field_name", "tests/test_main.py::test_field_order", "tests/test_main.py::test_required", "tests/test_main.py::test_mutability", "tests/test_main.py::test_immutability[False-False]", "tests/test_main.py::test_immutability[False-True]", "tests/test_main.py::test_immutability[True-True]", "tests/test_main.py::test_not_frozen_are_not_hashable", "tests/test_main.py::test_with_declared_hash", "tests/test_main.py::test_frozen_with_hashable_fields_are_hashable", "tests/test_main.py::test_frozen_with_unhashable_fields_are_not_hashable", "tests/test_main.py::test_hash_function_give_different_result_for_different_object", "tests/test_main.py::test_const_validates", "tests/test_main.py::test_const_uses_default", "tests/test_main.py::test_const_validates_after_type_validators", "tests/test_main.py::test_const_with_wrong_value", "tests/test_main.py::test_const_with_validator", "tests/test_main.py::test_const_list", "tests/test_main.py::test_const_list_with_wrong_value", "tests/test_main.py::test_const_validation_json_serializable", "tests/test_main.py::test_validating_assignment_pass", "tests/test_main.py::test_validating_assignment_fail", "tests/test_main.py::test_validating_assignment_pre_root_validator_fail", "tests/test_main.py::test_validating_assignment_post_root_validator_fail", "tests/test_main.py::test_root_validator_many_values_change", "tests/test_main.py::test_enum_values", "tests/test_main.py::test_literal_enum_values", "tests/test_main.py::test_enum_raw", "tests/test_main.py::test_set_tuple_values", "tests/test_main.py::test_default_copy", "tests/test_main.py::test_arbitrary_type_allowed_validation_success", "tests/test_main.py::test_arbitrary_type_allowed_validation_fails", "tests/test_main.py::test_arbitrary_types_not_allowed", "tests/test_main.py::test_type_type_validation_success", "tests/test_main.py::test_type_type_subclass_validation_success", "tests/test_main.py::test_type_type_validation_fails_for_instance", "tests/test_main.py::test_type_type_validation_fails_for_basic_type", "tests/test_main.py::test_bare_type_type_validation_success", "tests/test_main.py::test_bare_type_type_validation_fails", "tests/test_main.py::test_annotation_field_name_shadows_attribute", "tests/test_main.py::test_value_field_name_shadows_attribute", "tests/test_main.py::test_class_var", "tests/test_main.py::test_fields_set", "tests/test_main.py::test_exclude_unset_dict", "tests/test_main.py::test_exclude_unset_recursive", "tests/test_main.py::test_dict_exclude_unset_populated_by_alias", "tests/test_main.py::test_dict_exclude_unset_populated_by_alias_with_extra", "tests/test_main.py::test_exclude_defaults", "tests/test_main.py::test_dir_fields", "tests/test_main.py::test_dict_with_extra_keys", "tests/test_main.py::test_root", "tests/test_main.py::test_root_list", "tests/test_main.py::test_root_nested", "tests/test_main.py::test_encode_nested_root", "tests/test_main.py::test_root_failed", "tests/test_main.py::test_root_undefined_failed", "tests/test_main.py::test_parse_root_as_mapping", "tests/test_main.py::test_parse_obj_non_mapping_root", "tests/test_main.py::test_parse_obj_nested_root", "tests/test_main.py::test_untouched_types", "tests/test_main.py::test_custom_types_fail_without_keep_untouched", "tests/test_main.py::test_model_iteration", "tests/test_main.py::test_model_export_nested_list[excluding", "tests/test_main.py::test_model_export_nested_list[should", "tests/test_main.py::test_model_export_nested_list[using", "tests/test_main.py::test_model_export_dict_exclusion[excluding", "tests/test_main.py::test_model_export_dict_exclusion[using", "tests/test_main.py::test_model_export_dict_exclusion[exclude", "tests/test_main.py::test_model_exclude_config_field_merging", "tests/test_main.py::test_model_exclude_copy_on_model_validation", "tests/test_main.py::test_validation_deep_copy", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[None-expected0-kinds0]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[None-expected0-kinds1]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[None-expected0-kinds2]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[None-expected0-kinds3]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[None-expected0-kinds4]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[None-expected0-kinds5]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[None-expected0-kinds6]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude1-expected1-kinds0]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude1-expected1-kinds1]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude1-expected1-kinds2]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude1-expected1-kinds3]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude1-expected1-kinds4]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude1-expected1-kinds5]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude1-expected1-kinds6]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude2-expected2-kinds0]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude2-expected2-kinds1]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude2-expected2-kinds2]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude2-expected2-kinds3]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude2-expected2-kinds4]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude2-expected2-kinds5]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude2-expected2-kinds6]", "tests/test_main.py::test_model_export_exclusion_inheritance", "tests/test_main.py::test_model_export_with_true_instead_of_ellipsis", "tests/test_main.py::test_model_export_inclusion", "tests/test_main.py::test_model_export_inclusion_inheritance", "tests/test_main.py::test_custom_init_subclass_params", "tests/test_main.py::test_update_forward_refs_does_not_modify_module_dict", "tests/test_main.py::test_two_defaults", "tests/test_main.py::test_default_factory", "tests/test_main.py::test_default_factory_called_once", "tests/test_main.py::test_default_factory_called_once_2", "tests/test_main.py::test_default_factory_validate_children", "tests/test_main.py::test_default_factory_parse", "tests/test_main.py::test_none_min_max_items", "tests/test_main.py::test_reuse_same_field", "tests/test_main.py::test_base_config_type_hinting", "tests/test_main.py::test_allow_mutation_field", "tests/test_main.py::test_repr_field", "tests/test_main.py::test_inherited_model_field_copy", "tests/test_main.py::test_inherited_model_field_untouched", "tests/test_main.py::test_mapping_retains_type_subclass", "tests/test_main.py::test_mapping_retains_type_defaultdict", "tests/test_main.py::test_mapping_retains_type_fallback_error", "tests/test_main.py::test_typing_coercion_dict", "tests/test_main.py::test_typing_non_coercion_of_dict_subclasses", "tests/test_main.py::test_typing_coercion_defaultdict", "tests/test_main.py::test_typing_coercion_counter", "tests/test_main.py::test_typing_counter_value_validation", "tests/test_main.py::test_class_kwargs_config", "tests/test_main.py::test_class_kwargs_config_json_encoders", "tests/test_main.py::test_class_kwargs_config_and_attr_conflict", "tests/test_main.py::test_class_kwargs_custom_config", "tests/test_main.py::test_final_field_decl_withou_default_val[none-no-arg]", "tests/test_main.py::test_final_field_decl_withou_default_val[none-with-arg]", "tests/test_main.py::test_final_field_decl_withou_default_val[field-no-arg]", "tests/test_main.py::test_final_field_decl_withou_default_val[field-with-arg]", "tests/test_main.py::test_final_field_decl_with_default_val[no-arg]", "tests/test_main.py::test_final_field_decl_with_default_val[with-arg]", "tests/test_main.py::test_final_field_reassignment", "tests/test_main.py::test_field_by_default_is_not_final" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-03-17 01:25:10+00:00
mit
4,855
pydantic__pydantic-3909
diff --git a/pydantic/json.py b/pydantic/json.py --- a/pydantic/json.py +++ b/pydantic/json.py @@ -105,8 +105,8 @@ def custom_pydantic_encoder(type_encoders: Dict[Any, Callable[[Type[Any]], Any]] def timedelta_isoformat(td: datetime.timedelta) -> str: """ - ISO 8601 encoding for timedeltas. + ISO 8601 encoding for Python timedelta object. """ minutes, seconds = divmod(td.seconds, 60) hours, minutes = divmod(minutes, 60) - return f'P{td.days}DT{hours:d}H{minutes:d}M{seconds:d}.{td.microseconds:06d}S' + return f'{"-" if td.days < 0 else ""}P{abs(td.days)}DT{hours:d}H{minutes:d}M{seconds:d}.{td.microseconds:06d}S'
pydantic/pydantic
39d30c24df78df3d7e1756575f8cac7ba1869e6a
diff --git a/tests/test_json.py b/tests/test_json.py --- a/tests/test_json.py +++ b/tests/test_json.py @@ -46,6 +46,7 @@ class MyEnum(Enum): (datetime.datetime(2032, 1, 1), '"2032-01-01T00:00:00"'), (datetime.time(12, 34, 56), '"12:34:56"'), (datetime.timedelta(days=12, seconds=34, microseconds=56), '1036834.000056'), + (datetime.timedelta(seconds=-1), '-1.0'), ({1, 2, 3}, '[1, 2, 3]'), (frozenset([1, 2, 3]), '[1, 2, 3]'), ((v for v in range(4)), '[0, 1, 2, 3]'), @@ -142,6 +143,8 @@ class Foo: [ (datetime.timedelta(days=12, seconds=34, microseconds=56), 'P12DT0H0M34.000056S'), (datetime.timedelta(days=1001, hours=1, minutes=2, seconds=3, microseconds=654_321), 'P1001DT1H2M3.654321S'), + (datetime.timedelta(seconds=-1), '-P1DT23H59M59.000000S'), + (datetime.timedelta(), 'P0DT0H0M0.000000S'), ], ) def test_iso_timedelta(input, output):
timedelta_isoformat does not produce correct string in some cases ### Checks * [x] I added a descriptive title to this issue * [x] I have searched (google, github) for similar issues and couldn't find anything * [x] I have read and followed [the docs](https://pydantic-docs.helpmanual.io/) and still think this is a bug <!-- Sorry to sound so draconian, but every second saved replying to issues is time spend improving pydantic :-) --> # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.9.0 pydantic compiled: True install path: C:\Program Files\Python310\Lib\site-packages\pydantic python version: 3.10.2 (tags/v3.10.2:a58ebcc, Jan 17 2022, 14:12:15) [MSC v.1929 64 bit (AMD64)] platform: Windows-10-10.0.19044-SP0 optional deps. installed: ['dotenv', 'typing-extensions'] ``` # Code Demonstration bug ```py from pydantic.json import timedelta_isoformat from datetime import datetime timedelta = (datetime.fromisoformat("2022-03-15 08:00:57.152735+00:00") - datetime.fromisoformat("2022-03-15 08:00:57.264000+00:00")) incorrect_iso_string = timedelta_isoformat(timedelta) # this produce "P-1DT23H59M59.888735S" and that is incorrect according to documentation ([±]P[DD]DT[HH]H[MM]M[SS]S) ... ``` i have verified this on two diferent computers with two diferents setups (conda/regular python so it should not be problem of my enviroment) timedelta_isoformat does not produce correct string in some cases ### Checks * [x] I added a descriptive title to this issue * [x] I have searched (google, github) for similar issues and couldn't find anything * [x] I have read and followed [the docs](https://pydantic-docs.helpmanual.io/) and still think this is a bug <!-- Sorry to sound so draconian, but every second saved replying to issues is time spend improving pydantic :-) --> # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.9.0 pydantic compiled: True install path: C:\Program Files\Python310\Lib\site-packages\pydantic python version: 3.10.2 (tags/v3.10.2:a58ebcc, Jan 17 2022, 14:12:15) [MSC v.1929 64 bit (AMD64)] platform: Windows-10-10.0.19044-SP0 optional deps. installed: ['dotenv', 'typing-extensions'] ``` # Code Demonstration bug ```py from pydantic.json import timedelta_isoformat from datetime import datetime timedelta = (datetime.fromisoformat("2022-03-15 08:00:57.152735+00:00") - datetime.fromisoformat("2022-03-15 08:00:57.264000+00:00")) incorrect_iso_string = timedelta_isoformat(timedelta) # this produce "P-1DT23H59M59.888735S" and that is incorrect according to documentation ([±]P[DD]DT[HH]H[MM]M[SS]S) ... ``` i have verified this on two diferent computers with two diferents setups (conda/regular python so it should not be problem of my enviroment)
0.0
39d30c24df78df3d7e1756575f8cac7ba1869e6a
[ "tests/test_json.py::test_iso_timedelta[input2--P1DT23H59M59.000000S]" ]
[ "tests/test_json.py::test_encoding[input0-\"ebcdab58-6eb8-46fb-a190-d07a33e9eac8\"]", "tests/test_json.py::test_encoding[input1-\"192.168.0.1\"]", "tests/test_json.py::test_encoding[input2-\"black\"]", "tests/test_json.py::test_encoding[input3-\"#010c7b\"]", "tests/test_json.py::test_encoding[input4-\"**********\"]", "tests/test_json.py::test_encoding[input5-\"\"]", "tests/test_json.py::test_encoding[input6-\"**********\"]", "tests/test_json.py::test_encoding[input7-\"\"]", "tests/test_json.py::test_encoding[input8-\"foo", "tests/test_json.py::test_encoding[input9-\"::1:0:1\"]", "tests/test_json.py::test_encoding[input10-\"192.168.0.0/24\"]", "tests/test_json.py::test_encoding[input11-\"2001:db00::/120\"]", "tests/test_json.py::test_encoding[input12-\"192.168.0.0/24\"]", "tests/test_json.py::test_encoding[input13-\"2001:db00::/120\"]", "tests/test_json.py::test_encoding[input14-\"2032-01-01T01:01:00\"]", "tests/test_json.py::test_encoding[input15-\"2032-01-01T01:01:00+00:00\"]", "tests/test_json.py::test_encoding[input16-\"2032-01-01T00:00:00\"]", "tests/test_json.py::test_encoding[input17-\"12:34:56\"]", "tests/test_json.py::test_encoding[input18-1036834.000056]", "tests/test_json.py::test_encoding[input19--1.0]", "tests/test_json.py::test_encoding[input20-[1,", "tests/test_json.py::test_encoding[input21-[1,", "tests/test_json.py::test_encoding[<genexpr>-[0,", "tests/test_json.py::test_encoding[this", "tests/test_json.py::test_encoding[input24-12.34]", "tests/test_json.py::test_encoding[input25-{\"a\":", "tests/test_json.py::test_encoding[MyEnum.foo-\"bar\"]", "tests/test_json.py::test_encoding[^regex$-\"^regex$\"]", "tests/test_json.py::test_path_encoding", "tests/test_json.py::test_model_encoding", "tests/test_json.py::test_subclass_encoding", "tests/test_json.py::test_subclass_custom_encoding", "tests/test_json.py::test_invalid_model", "tests/test_json.py::test_iso_timedelta[input0-P12DT0H0M34.000056S]", "tests/test_json.py::test_iso_timedelta[input1-P1001DT1H2M3.654321S]", "tests/test_json.py::test_iso_timedelta[input3-P0DT0H0M0.000000S]", "tests/test_json.py::test_custom_encoder", "tests/test_json.py::test_custom_iso_timedelta", "tests/test_json.py::test_con_decimal_encode", "tests/test_json.py::test_json_encoder_simple_inheritance", "tests/test_json.py::test_json_encoder_inheritance_override", "tests/test_json.py::test_custom_encoder_arg", "tests/test_json.py::test_encode_dataclass", "tests/test_json.py::test_encode_pydantic_dataclass", "tests/test_json.py::test_encode_custom_root", "tests/test_json.py::test_custom_decode_encode", "tests/test_json.py::test_json_nested_encode_models", "tests/test_json.py::test_custom_encode_fallback_basemodel", "tests/test_json.py::test_custom_encode_error", "tests/test_json.py::test_recursive" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2022-03-17 06:20:43+00:00
mit
4,856
pydantic__pydantic-3935
diff --git a/pydantic/fields.py b/pydantic/fields.py --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -199,7 +199,8 @@ def update_from_config(self, from_config: Dict[str, Any]) -> None: current_value = getattr(self, attr_name) except AttributeError: # attr_name is not an attribute of FieldInfo, it should therefore be added to extra - self.extra[attr_name] = value + # (except if extra already has this value!) + self.extra.setdefault(attr_name, value) else: if current_value is self.__field_constraints__.get(attr_name, None): setattr(self, attr_name, value)
pydantic/pydantic
eadfdbdbde3d4d8363b69196bbe4dded956982c3
You wrote `Config.field` for model B instead of `Config.fields` hence the difference. Now you're right the output is not the expected one. I'll open a fix shortly
diff --git a/tests/test_schema.py b/tests/test_schema.py --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -3001,3 +3001,27 @@ class Model(BaseModel): }, }, } + + +def test_extra_inheritance(): + class A(BaseModel): + root: Optional[str] + + class Config: + fields = { + 'root': {'description': 'root path of data', 'level': 1}, + } + + class Model(A): + root: str = Field('asa', description='image height', level=3) + + m = Model() + assert m.schema()['properties'] == { + 'root': { + 'title': 'Root', + 'type': 'string', + 'description': 'image height', + 'default': 'asa', + 'level': 3, + } + }
sub-model cannot always re-write field infos from the same BaseModel. ### Checks * [-] I added a descriptive title to this issue * [-] I have searched (google, github) for similar issues and couldn't find anything * [-] I have read and followed [the docs](https://pydantic-docs.helpmanual.io/) and still think this is a bug # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.9.0 pydantic compiled: True install path: /home/zuobinhua/anaconda3/lib/python3.7/site-packages/pydantic python version: 3.7.6 (default, Jan 8 2020, 19:59:22) [GCC 7.3.0] platform: Linux-4.15.0-159-generic-x86_64-with-debian-buster-sid optional deps. installed: ['email-validator', 'typing-extensions'] ``` When creating two sub models(A, B) from Pydantic BaseModel, with fields infos defined in Config. Then creating another two sub models(Model1, Model2) from A and B, trying to rewrite the extra keys (we used `level` in the following code) in field info. Only one of the sub models can re-write the extra value correctly. As shown in the following code, `extra` in m2.__fields__["root"].field_info got level=3, but for m1 it still got level=1. ```py from typing import Optional from pydantic import BaseModel from pydantic import Field class A(BaseModel): root: Optional[str] class Config: fields = { "root": {"description": "root path of data", "level": 1}, } class B(BaseModel): root: Optional[str] class Config: field = { "root": {"description": "root path of data", "level": 1}, } class Model1(A): root: str = Field("asa", description="image height", level=3) class Model2(B): root: str = Field("asa", description="image height", level=3) m1 = Model1() print(m1.__fields__["root"].field_info) # default='asa' description='image height' extra={'level': 1} m2 = Model2() print(m2.__fields__["root"].field_info) # default='asa' description='image height' extra={'level': 3} ```
0.0
eadfdbdbde3d4d8363b69196bbe4dded956982c3
[ "tests/test_schema.py::test_extra_inheritance" ]
[ "tests/test_schema.py::test_key", "tests/test_schema.py::test_by_alias", "tests/test_schema.py::test_ref_template", "tests/test_schema.py::test_by_alias_generator", "tests/test_schema.py::test_sub_model", "tests/test_schema.py::test_schema_class", "tests/test_schema.py::test_schema_repr", "tests/test_schema.py::test_schema_class_by_alias", "tests/test_schema.py::test_choices", "tests/test_schema.py::test_enum_modify_schema", "tests/test_schema.py::test_enum_schema_custom_field", "tests/test_schema.py::test_enum_and_model_have_same_behaviour", "tests/test_schema.py::test_enum_includes_extra_without_other_params", "tests/test_schema.py::test_list_enum_schema_extras", "tests/test_schema.py::test_json_schema", "tests/test_schema.py::test_list_sub_model", "tests/test_schema.py::test_optional", "tests/test_schema.py::test_any", "tests/test_schema.py::test_set", "tests/test_schema.py::test_const_str", "tests/test_schema.py::test_const_false", "tests/test_schema.py::test_tuple[tuple-extra_props0]", "tests/test_schema.py::test_tuple[field_type1-extra_props1]", "tests/test_schema.py::test_tuple[field_type2-extra_props2]", "tests/test_schema.py::test_tuple[field_type3-extra_props3]", "tests/test_schema.py::test_deque", "tests/test_schema.py::test_bool", "tests/test_schema.py::test_strict_bool", "tests/test_schema.py::test_dict", "tests/test_schema.py::test_list", "tests/test_schema.py::test_list_union_dict[field_type0-expected_schema0]", "tests/test_schema.py::test_list_union_dict[field_type1-expected_schema1]", "tests/test_schema.py::test_list_union_dict[field_type2-expected_schema2]", "tests/test_schema.py::test_list_union_dict[field_type3-expected_schema3]", "tests/test_schema.py::test_list_union_dict[field_type4-expected_schema4]", "tests/test_schema.py::test_date_types[datetime-expected_schema0]", "tests/test_schema.py::test_date_types[date-expected_schema1]", "tests/test_schema.py::test_date_types[time-expected_schema2]", "tests/test_schema.py::test_date_types[timedelta-expected_schema3]", "tests/test_schema.py::test_str_basic_types[field_type0-expected_schema0]", "tests/test_schema.py::test_str_basic_types[field_type1-expected_schema1]", "tests/test_schema.py::test_str_basic_types[field_type2-expected_schema2]", "tests/test_schema.py::test_str_basic_types[field_type3-expected_schema3]", "tests/test_schema.py::test_str_constrained_types[StrictStr-expected_schema0]", "tests/test_schema.py::test_str_constrained_types[ConstrainedStr-expected_schema1]", "tests/test_schema.py::test_str_constrained_types[ConstrainedStrValue-expected_schema2]", "tests/test_schema.py::test_special_str_types[AnyUrl-expected_schema0]", "tests/test_schema.py::test_special_str_types[UrlValue-expected_schema1]", "tests/test_schema.py::test_email_str_types[EmailStr-email]", "tests/test_schema.py::test_email_str_types[NameEmail-name-email]", "tests/test_schema.py::test_secret_types[SecretBytes-string]", "tests/test_schema.py::test_secret_types[SecretStr-string]", "tests/test_schema.py::test_special_int_types[ConstrainedInt-expected_schema0]", "tests/test_schema.py::test_special_int_types[ConstrainedIntValue-expected_schema1]", "tests/test_schema.py::test_special_int_types[ConstrainedIntValue-expected_schema2]", "tests/test_schema.py::test_special_int_types[ConstrainedIntValue-expected_schema3]", "tests/test_schema.py::test_special_int_types[PositiveInt-expected_schema4]", "tests/test_schema.py::test_special_int_types[NegativeInt-expected_schema5]", "tests/test_schema.py::test_special_int_types[NonNegativeInt-expected_schema6]", "tests/test_schema.py::test_special_int_types[NonPositiveInt-expected_schema7]", "tests/test_schema.py::test_special_float_types[ConstrainedFloat-expected_schema0]", "tests/test_schema.py::test_special_float_types[ConstrainedFloatValue-expected_schema1]", "tests/test_schema.py::test_special_float_types[ConstrainedFloatValue-expected_schema2]", "tests/test_schema.py::test_special_float_types[ConstrainedFloatValue-expected_schema3]", "tests/test_schema.py::test_special_float_types[PositiveFloat-expected_schema4]", "tests/test_schema.py::test_special_float_types[NegativeFloat-expected_schema5]", "tests/test_schema.py::test_special_float_types[NonNegativeFloat-expected_schema6]", "tests/test_schema.py::test_special_float_types[NonPositiveFloat-expected_schema7]", "tests/test_schema.py::test_special_float_types[ConstrainedDecimal-expected_schema8]", "tests/test_schema.py::test_special_float_types[ConstrainedDecimalValue-expected_schema9]", "tests/test_schema.py::test_special_float_types[ConstrainedDecimalValue-expected_schema10]", "tests/test_schema.py::test_special_float_types[ConstrainedDecimalValue-expected_schema11]", "tests/test_schema.py::test_uuid_types[UUID-uuid]", "tests/test_schema.py::test_uuid_types[UUID1-uuid1]", "tests/test_schema.py::test_uuid_types[UUID3-uuid3]", "tests/test_schema.py::test_uuid_types[UUID4-uuid4]", "tests/test_schema.py::test_uuid_types[UUID5-uuid5]", "tests/test_schema.py::test_path_types[FilePath-file-path]", "tests/test_schema.py::test_path_types[DirectoryPath-directory-path]", "tests/test_schema.py::test_path_types[Path-path]", "tests/test_schema.py::test_json_type", "tests/test_schema.py::test_ipv4address_type", "tests/test_schema.py::test_ipv6address_type", "tests/test_schema.py::test_ipvanyaddress_type", "tests/test_schema.py::test_ipv4interface_type", "tests/test_schema.py::test_ipv6interface_type", "tests/test_schema.py::test_ipvanyinterface_type", "tests/test_schema.py::test_ipv4network_type", "tests/test_schema.py::test_ipv6network_type", "tests/test_schema.py::test_ipvanynetwork_type", "tests/test_schema.py::test_callable_type[type_0-default_value0]", "tests/test_schema.py::test_callable_type[type_1-<lambda>]", "tests/test_schema.py::test_callable_type[type_2-default_value2]", "tests/test_schema.py::test_callable_type[type_3-<lambda>]", "tests/test_schema.py::test_error_non_supported_types", "tests/test_schema.py::test_flat_models_unique_models", "tests/test_schema.py::test_flat_models_with_submodels", "tests/test_schema.py::test_flat_models_with_submodels_from_sequence", "tests/test_schema.py::test_model_name_maps", "tests/test_schema.py::test_schema_overrides", "tests/test_schema.py::test_schema_overrides_w_union", "tests/test_schema.py::test_schema_from_models", "tests/test_schema.py::test_schema_with_refs[#/components/schemas/-None]", "tests/test_schema.py::test_schema_with_refs[None-#/components/schemas/{model}]", "tests/test_schema.py::test_schema_with_refs[#/components/schemas/-#/{model}/schemas/]", "tests/test_schema.py::test_schema_with_custom_ref_template", "tests/test_schema.py::test_schema_ref_template_key_error", "tests/test_schema.py::test_schema_no_definitions", "tests/test_schema.py::test_list_default", "tests/test_schema.py::test_enum_str_default", "tests/test_schema.py::test_enum_int_default", "tests/test_schema.py::test_dict_default", "tests/test_schema.py::test_constraints_schema[kwargs0-str-expected_extra0]", "tests/test_schema.py::test_constraints_schema[kwargs1-ConstrainedStrValue-expected_extra1]", "tests/test_schema.py::test_constraints_schema[kwargs2-str-expected_extra2]", "tests/test_schema.py::test_constraints_schema[kwargs3-bytes-expected_extra3]", "tests/test_schema.py::test_constraints_schema[kwargs4-str-expected_extra4]", "tests/test_schema.py::test_constraints_schema[kwargs5-int-expected_extra5]", "tests/test_schema.py::test_constraints_schema[kwargs6-int-expected_extra6]", "tests/test_schema.py::test_constraints_schema[kwargs7-int-expected_extra7]", "tests/test_schema.py::test_constraints_schema[kwargs8-int-expected_extra8]", "tests/test_schema.py::test_constraints_schema[kwargs9-int-expected_extra9]", "tests/test_schema.py::test_constraints_schema[kwargs10-float-expected_extra10]", "tests/test_schema.py::test_constraints_schema[kwargs11-float-expected_extra11]", "tests/test_schema.py::test_constraints_schema[kwargs12-float-expected_extra12]", "tests/test_schema.py::test_constraints_schema[kwargs13-float-expected_extra13]", "tests/test_schema.py::test_constraints_schema[kwargs14-float-expected_extra14]", "tests/test_schema.py::test_constraints_schema[kwargs15-float-expected_extra15]", "tests/test_schema.py::test_constraints_schema[kwargs16-float-expected_extra16]", "tests/test_schema.py::test_constraints_schema[kwargs17-float-expected_extra17]", "tests/test_schema.py::test_constraints_schema[kwargs18-float-expected_extra18]", "tests/test_schema.py::test_constraints_schema[kwargs19-Decimal-expected_extra19]", "tests/test_schema.py::test_constraints_schema[kwargs20-Decimal-expected_extra20]", "tests/test_schema.py::test_constraints_schema[kwargs21-Decimal-expected_extra21]", "tests/test_schema.py::test_constraints_schema[kwargs22-Decimal-expected_extra22]", "tests/test_schema.py::test_constraints_schema[kwargs23-Decimal-expected_extra23]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs0-int]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs1-float]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs2-Decimal]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs3-bool]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs4-int]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs5-str]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs6-bytes]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs7-str]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs8-bool]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs9-type_9]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs10-type_10]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs11-ConstrainedListValue]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs12-ConstrainedSetValue]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs13-ConstrainedFrozenSetValue]", "tests/test_schema.py::test_constraints_schema_validation[kwargs0-str-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs1-str-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs2-bytes-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs3-str-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs4-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs5-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs6-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs7-int-2]", "tests/test_schema.py::test_constraints_schema_validation[kwargs8-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs9-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs10-int-5]", "tests/test_schema.py::test_constraints_schema_validation[kwargs11-float-3.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs12-float-2.1]", "tests/test_schema.py::test_constraints_schema_validation[kwargs13-float-3.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs14-float-4.9]", "tests/test_schema.py::test_constraints_schema_validation[kwargs15-float-3.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs16-float-2.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs17-float-3.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs18-float-5.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs19-float-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs20-float-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs21-Decimal-value21]", "tests/test_schema.py::test_constraints_schema_validation[kwargs22-Decimal-value22]", "tests/test_schema.py::test_constraints_schema_validation[kwargs23-Decimal-value23]", "tests/test_schema.py::test_constraints_schema_validation[kwargs24-Decimal-value24]", "tests/test_schema.py::test_constraints_schema_validation[kwargs25-Decimal-value25]", "tests/test_schema.py::test_constraints_schema_validation[kwargs26-Decimal-value26]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs0-str-foobar]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs1-str-f]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs2-str-bar]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs3-int-2]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs4-int-5]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs5-int-1]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs6-int-6]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs7-float-2.0]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs8-float-5.0]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs9-float-1.9]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs10-float-5.1]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs11-Decimal-value11]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs12-Decimal-value12]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs13-Decimal-value13]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs14-Decimal-value14]", "tests/test_schema.py::test_schema_kwargs", "tests/test_schema.py::test_schema_dict_constr", "tests/test_schema.py::test_bytes_constrained_types[ConstrainedBytes-expected_schema0]", "tests/test_schema.py::test_bytes_constrained_types[ConstrainedBytesValue-expected_schema1]", "tests/test_schema.py::test_optional_dict", "tests/test_schema.py::test_optional_validator", "tests/test_schema.py::test_field_with_validator", "tests/test_schema.py::test_unparameterized_schema_generation", "tests/test_schema.py::test_known_model_optimization", "tests/test_schema.py::test_root", "tests/test_schema.py::test_root_list", "tests/test_schema.py::test_root_nested_model", "tests/test_schema.py::test_new_type_schema", "tests/test_schema.py::test_literal_schema", "tests/test_schema.py::test_literal_enum", "tests/test_schema.py::test_color_type", "tests/test_schema.py::test_model_with_schema_extra", "tests/test_schema.py::test_model_with_schema_extra_callable", "tests/test_schema.py::test_model_with_schema_extra_callable_no_model_class", "tests/test_schema.py::test_model_with_schema_extra_callable_classmethod", "tests/test_schema.py::test_model_with_schema_extra_callable_instance_method", "tests/test_schema.py::test_model_with_extra_forbidden", "tests/test_schema.py::test_enforced_constraints[int-kwargs0-field_schema0]", "tests/test_schema.py::test_enforced_constraints[annotation1-kwargs1-field_schema1]", "tests/test_schema.py::test_enforced_constraints[annotation2-kwargs2-field_schema2]", "tests/test_schema.py::test_enforced_constraints[annotation3-kwargs3-field_schema3]", "tests/test_schema.py::test_enforced_constraints[annotation4-kwargs4-field_schema4]", "tests/test_schema.py::test_enforced_constraints[annotation5-kwargs5-field_schema5]", "tests/test_schema.py::test_enforced_constraints[annotation6-kwargs6-field_schema6]", "tests/test_schema.py::test_enforced_constraints[annotation7-kwargs7-field_schema7]", "tests/test_schema.py::test_real_vs_phony_constraints", "tests/test_schema.py::test_subfield_field_info", "tests/test_schema.py::test_dataclass", "tests/test_schema.py::test_schema_attributes", "tests/test_schema.py::test_model_process_schema_enum", "tests/test_schema.py::test_path_modify_schema", "tests/test_schema.py::test_frozen_set", "tests/test_schema.py::test_iterable", "tests/test_schema.py::test_new_type", "tests/test_schema.py::test_multiple_models_with_same_name", "tests/test_schema.py::test_multiple_enums_with_same_name", "tests/test_schema.py::test_schema_for_generic_field", "tests/test_schema.py::test_namedtuple_default", "tests/test_schema.py::test_advanced_generic_schema", "tests/test_schema.py::test_nested_generic", "tests/test_schema.py::test_nested_generic_model", "tests/test_schema.py::test_complex_nested_generic", "tests/test_schema.py::test_schema_with_field_parameter", "tests/test_schema.py::test_discriminated_union", "tests/test_schema.py::test_discriminated_annotated_union", "tests/test_schema.py::test_alias_same", "tests/test_schema.py::test_nested_python_dataclasses", "tests/test_schema.py::test_discriminated_union_in_list" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2022-03-25 07:43:07+00:00
mit
4,857
pydantic__pydantic-3941
diff --git a/docs/examples/exporting_models_json_nested_encoders.py b/docs/examples/exporting_models_json_nested_encoders.py new file mode 100644 --- /dev/null +++ b/docs/examples/exporting_models_json_nested_encoders.py @@ -0,0 +1,41 @@ +from datetime import datetime, timedelta +from pydantic import BaseModel +from pydantic.json import timedelta_isoformat + + +class CustomChildModel(BaseModel): + dt: datetime + diff: timedelta + + class Config: + json_encoders = { + datetime: lambda v: v.timestamp(), + timedelta: timedelta_isoformat, + } + + +class ParentModel(BaseModel): + diff: timedelta + child: CustomChildModel + + class Config: + json_encoders = { + timedelta: lambda v: v.total_seconds(), + CustomChildModel: lambda _: 'using parent encoder', + } + + +child = CustomChildModel(dt=datetime(2032, 6, 1), diff=timedelta(hours=100)) +parent = ParentModel(diff=timedelta(hours=3), child=child) + +# default encoder uses total_seconds() for diff +print(parent.json()) + +# nested encoder uses isoformat +print(parent.json(use_nested_encoders=True)) + +# turning off models_as_dict only uses the top-level formatter, however + +print(parent.json(models_as_dict=False, use_nested_encoders=True)) + +print(parent.json(models_as_dict=False, use_nested_encoders=False)) diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -434,6 +434,7 @@ def dict( exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, + encode_as_json: bool = False, ) -> 'DictStrAny': """ Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. @@ -455,6 +456,7 @@ def dict( exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, + encode_as_json=encode_as_json, ) ) @@ -470,6 +472,7 @@ def json( exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, + use_nested_encoders: bool = False, **dumps_kwargs: Any, ) -> str: """ @@ -497,6 +500,7 @@ def json( exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, + encode_as_json=use_nested_encoders, ) ) if self.__custom_root_type__: @@ -715,6 +719,7 @@ def _get_value( exclude_unset: bool, exclude_defaults: bool, exclude_none: bool, + encode_as_json: bool = False, ) -> Any: if isinstance(v, BaseModel): @@ -726,6 +731,7 @@ def _get_value( include=include, exclude=exclude, exclude_none=exclude_none, + encode_as_json=encode_as_json, ) if ROOT_KEY in v_dict: return v_dict[ROOT_KEY] @@ -775,6 +781,9 @@ def _get_value( elif isinstance(v, Enum) and getattr(cls.Config, 'use_enum_values', False): return v.value + elif encode_as_json: + return cls.__json_encoder__(v) + else: return v @@ -808,6 +817,7 @@ def _iter( exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, + encode_as_json: bool = False, ) -> 'TupleGenerator': # Merge field set excludes with explicit exclude parameter with explicit overriding field set options. @@ -853,6 +863,7 @@ def _iter( exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, + encode_as_json=encode_as_json, ) yield dict_key, v
pydantic/pydantic
ea870115b71c3c8843f454989d0ccffe3edc0279
Hello @mvanderlee The config depends on the model not the type of the field, even if this one is also a model. So you'll need to duplicate your config or add it in your own custom BaseModel. Duplicating the config is a non-starter for us. So you're saying that there is currently no way to ensure a Model will always be serialized a certain way? Other than manually defining a json encoder and always specifying it on json.dump. Which again, would be a non-started for us. I need to allow Models to be 2-way serializable. You mentioned a custom BaseModel, do you have an example? Sure thing! ```python from datetime import datetime, timedelta from pydantic import BaseModel as PydanticBaseModel from pydantic.json import timedelta_isoformat class BaseModel(PydanticBaseModel): """ All the instances of BaseModel should serialize those types the same way """ class Config: json_encoders = { datetime: lambda v: v.timestamp(), timedelta: timedelta_isoformat, } class WithCustomEncoders(BaseModel): dt: datetime diff: timedelta class ParentWithoutEncoders(BaseModel): child: WithCustomEncoders m = WithCustomEncoders(dt=datetime(2032, 6, 1), diff=timedelta(hours=100)) print(m.json()) # {"dt": 1969653600.0, "diff": "P4DT4H0M0.000000S"} p = ParentWithoutEncoders(child=m) print(p.json()) # {"child": {"dt": 1969653600.0, "diff": "P4DT4H0M0.000000S"}} ``` The magic is possible because `Config` of a subclass inherits from the `Config` of its parent! You can also change default value of `BaseConfig`, which all `Config` classes inherit from ```python from datetime import datetime, timedelta from pydantic import BaseConfig, BaseModel from pydantic.json import timedelta_isoformat # All the instances of BaseModel should serialize those types the same way BaseConfig.json_encoders = { datetime: lambda v: v.timestamp(), timedelta: timedelta_isoformat, } class WithCustomEncoders(BaseModel): dt: datetime diff: timedelta class ParentWithoutEncoders(BaseModel): child: WithCustomEncoders m = WithCustomEncoders(dt=datetime(2032, 6, 1), diff=timedelta(hours=100)) print(m.json()) # {"dt": 1969653600.0, "diff": "P4DT4H0M0.000000S"} p = ParentWithoutEncoders(child=m) print(p.json()) # {"child": {"dt": 1969653600.0, "diff": "P4DT4H0M0.000000S"}} ``` Hope it helps :) Right, but now if I add a datetime field to the parent. Then both would use the same format. I'm looking to be able to define how a particular Model serializes, not all data types within the context. We can validate, and deserialize per model, but not serialize per model as far I can tell. ```python from datetime import datetime, timedelta from pydantic import BaseModel, validator from pydantic.json import timedelta_isoformat class WithCustomEncoders(BaseModel): dt: datetime diff: timedelta @validator('dt', pre=True) def validate_dt(cls, v): try: return datetime.fromtimestamp(v) except Exception as e: raise ValueError('must be a valid timestamp', e) class Config: json_encoders = { datetime: lambda v: v.timestamp(), timedelta: timedelta_isoformat, } class ParentWithoutEncoders(BaseModel): child: WithCustomEncoders p_dt: datetime @validator('p_dt', pre=True) def validate_p_dt(cls, v): try: return datetime.fromisoformat(v) except Exception as e: raise ValueError('must be valid iso string', e) class Config: json_encoders = { datetime: lambda v: v.isoformat() } raw_m = '{"dt": 1969671600.0, "diff": "P4DT4H0M0.000000S"}' raw_p = '{"child": {"dt": 1969671600.0, "diff": "P4DT4H0M0.000000S"}, "p_dt": "2032-06-01T00:00:00"}' m = WithCustomEncoders.parse_raw(raw_m) p = ParentWithoutEncoders.parse_raw(raw_p) print(m.json()) print(p.json()) assert m.json() == raw_m assert p.json() == raw_p # {"dt": 1969671600.0, "diff": "P4DT4H0M0.000000S"} # {"child": {"dt": "2032-06-01T00:00:00", "diff": 360000.0}, "p_dt": "2032-06-01T00:00:00"} # Traceback (most recent call last): # File "<stdin>", line 50, in <module> # AssertionError ``` The only way I currently see is to override the `_iter` function, i.e.: ```python class WithCustomEncoders(BaseModel): dt: datetime diff: timedelta @validator('dt', pre=True) def validate_dt(cls, v): try: return datetime.fromtimestamp(v) except Exception as e: raise ValueError('must be a valid timestamp', e) class Config: json_encoders = { datetime: lambda v: v.timestamp(), timedelta: timedelta_isoformat, } def _iter(self, *args, **kwargs): for key, v in super()._iter(*args, **kwargs): if key == 'dt': yield key, v.timestamp() elif key == 'diff': yield key, timedelta_isoformat(v) else: yield key, v ``` Edit: `_iter(...)` if it should also apply to `dict(...)` otherwise overriding `json(...)` in a similar fashion would work as well if it should only apply to json dumping. I agree with @mvanderlee that it's not clear at first that the parent model that is converting to JSON establishes all the encoders and the nested models are converted using those. This appears to be because the whole object is converted into a dict and then the JSON encoder of the parent model is applied to the dictionary. An alternative might be to recursively call the JSON encoder on any pydantic BaseModel children and incorporate along the way. @mvanderlee if you're interested in a PR, you might look at modifying https://github.com/samuelcolvin/pydantic/blob/13a5c7d676167b415080de5e6e6a74bea095b239/pydantic/main.py#L474-L509 This is likely to be much slower than the single call to JSON encoder, so I'd recommend making it an option or even a new method? Agreed with the other folks here that I can see why the current behavior is implemented the way it is, but there may be use-cases where you might want to serialize different components of the same type differently. Perhaps I hadn't been looking at the right parts of the documentation, but I didn't really understand the `Config` inheritance until I stumbled upon this issue and saw [@PrettyWood's explanation](https://github.com/samuelcolvin/pydantic/issues/2277#issuecomment-764010272). Would it be possible to add some of this discussion to the documentation if it's not already there? In the interim, based on @PrettyWood's example, what I came up with was just to create subclasses of the nested object (maybe this is overkill, would appreciate any suggestions!). Using a similar example: ```python class DatetimeA(datetime.datetime): """Datetime that will be encoded as a string in pydantic Config.""" def __new__(cls, *args, **kwargs): return datetime.datetime.__new__(cls, *args, **kwargs) class DatetimeB(datetime.datetime): """Datetime that will be encoded as a timestamp in pydantic Config.""" def __new__(cls, *args, **kwargs): return datetime.datetime.__new__(cls, *args, **kwargs) class MyBaseModel(BaseModel): class Config: json_encoders = { DatetimeA: lambda v: str(v), DatetimeB: lambda v: v.timestamp() } class TestModel(MyBaseModel): datetime_a: DatetimeA datetime_b: DatetimeB class ParentModel(MyBaseModel): test_model: TestModel test_model = TestModel( datetime_a=DatetimeA(2020, 1, 1), datetime_b=DatetimeB(2015, 1, 1) ) parent_model = ParentModel( test_model=test_model ) print(test_model.json()) print(parent_model.json()) ``` Output: ```python # '{"datetime_a": "2020-01-01 00:00:00", "datetime_b": 1420088400.0}' # '{"test_model": {"datetime_a": "2020-01-01 00:00:00", "datetime_b": 1420088400.0}}' ``` I just ran into this issue... after a while of debugging I realized that my `Config` wasn't respected in nested models. Although for my project it's OK to simply set a "global" encoder, I can see the value in defining how to encode a specific model within that model's Config and having that respected even when that model is nested. This is especially true when a module/library exposes public pydantic models for others to use.
diff --git a/tests/test_json.py b/tests/test_json.py --- a/tests/test_json.py +++ b/tests/test_json.py @@ -372,3 +372,81 @@ class Model(BaseModel): nested: Optional[BaseModel] assert Model(value=None, nested=Model(value=None)).json(exclude_none=True) == '{"nested": {}}' + + +class WithCustomEncoders(BaseModel): + dt: datetime.datetime + diff: datetime.timedelta + + class Config: + json_encoders = { + datetime.datetime: lambda v: v.timestamp(), + datetime.timedelta: timedelta_isoformat, + } + + +ides_of_march = datetime.datetime(44, 3, 15, tzinfo=datetime.timezone.utc) + +child = WithCustomEncoders( + dt=datetime.datetime(2032, 6, 1, tzinfo=datetime.timezone.utc), + diff=datetime.timedelta(hours=100), +) + + +def test_inner_custom_encoding(): + assert child.json() == r'{"dt": 1969660800.0, "diff": "P4DT4H0M0.000000S"}' + + +def test_encoding_in_parent_with_variable_encoders(): + class ParentWithVariableEncoders(BaseModel): + dt: datetime.datetime + child: WithCustomEncoders + + class Config: + json_encoders = { + datetime.datetime: lambda v: v.year, + datetime.timedelta: lambda v: v.total_seconds(), + } + + parent = ParentWithVariableEncoders(child=child, dt=ides_of_march) + + default = r'{"dt": 44, "child": {"dt": 2032, "diff": 360000.0}}' + assert parent.json() == default + # turning off models_as_dict defaults to top-level + assert parent.json(models_as_dict=False, use_nested_encoders=False) == default + assert parent.json(models_as_dict=False, use_nested_encoders=True) == default + + custom = ( + r'{"dt": 44, ' # parent.dt still uses the year to encode + # child uses child.json_encoders to encode + r'"child": {"dt": 1969660800.0, "diff": "P4DT4H0M0.000000S"}}' + ) + assert parent.json(use_nested_encoders=True) == custom + + +def test_encoding_in_parent_with_class_encoders(): + class ParentWithClassEncoders(BaseModel): + dt: datetime.datetime + child: WithCustomEncoders + + class Config: + json_encoders = { + datetime.datetime: lambda v: v.timestamp(), + WithCustomEncoders: lambda v: {'dt': v.dt.year}, + } + + parent = ParentWithClassEncoders(child=child, dt=ides_of_march) + + # when models_as_dict=True, the `WithCustomEncoders` encoder is ignored + default = r'{"dt": -60772291200.0, "child": {"dt": 1969660800.0, "diff": 360000.0}}' + assert parent.json() == default + + custom_child = r'{"dt": -60772291200.0, "child": {"dt": 1969660800.0, "diff": "P4DT4H0M0.000000S"}}' + assert parent.json(use_nested_encoders=True) == custom_child + + # when models_as_dict=False, the parent `WithCustomEncoders` is used + # regardless of whatever json_encoders are in WithCustomEncoders.Config + + custom_parent = r'{"dt": -60772291200.0, "child": {"dt": 2032}}' + assert parent.json(models_as_dict=False, use_nested_encoders=False) == custom_parent + assert parent.json(models_as_dict=False, use_nested_encoders=True) == custom_parent
Json Encoders are ignored in nested structures ### Checks * [x] I added a descriptive title to this issue * [x] I have searched (google, github) for similar issues and couldn't find anything * [x] I have read and followed [the docs](https://pydantic-docs.helpmanual.io/) and still think this is a bug <!-- Sorry to sound so draconian, but every second saved replying to issues is time spend improving pydantic :-) --> # Bug When nesting a model with customer encoders, they are ignored by the parent. ```python from datetime import datetime, timedelta from pydantic import BaseModel from pydantic.json import timedelta_isoformat class WithCustomEncoders(BaseModel): dt: datetime diff: timedelta class Config: json_encoders = { datetime: lambda v: v.timestamp(), timedelta: timedelta_isoformat, } class ParentWithoutEncoders(BaseModel): child: WithCustomEncoders m = WithCustomEncoders(dt=datetime(2032, 6, 1), diff=timedelta(hours=100)) print(m.json()) p = ParentWithoutEncoders(child=m) print(p.json()) #> {"dt": 1969671600.0, "diff": "P4DT4H0M0.000000S"} #> {"child": {"dt": "2032-06-01T00:00:00", "diff": 360000.0}} ``` Expected output: ```python #> {"dt": 1969671600.0, "diff": "P4DT4H0M0.000000S"} #> {"child": {"dt": 1969671600.0, "diff": "P4DT4H0M0.000000S"}} ```
0.0
ea870115b71c3c8843f454989d0ccffe3edc0279
[ "tests/test_json.py::test_encoding_in_parent_with_variable_encoders", "tests/test_json.py::test_encoding_in_parent_with_class_encoders" ]
[ "tests/test_json.py::test_encoding[input0-\"ebcdab58-6eb8-46fb-a190-d07a33e9eac8\"]", "tests/test_json.py::test_encoding[input1-\"192.168.0.1\"]", "tests/test_json.py::test_encoding[input2-\"black\"]", "tests/test_json.py::test_encoding[input3-\"#010c7b\"]", "tests/test_json.py::test_encoding[input4-\"**********\"]", "tests/test_json.py::test_encoding[input5-\"\"]", "tests/test_json.py::test_encoding[input6-\"**********\"]", "tests/test_json.py::test_encoding[input7-\"\"]", "tests/test_json.py::test_encoding[input8-\"foo", "tests/test_json.py::test_encoding[input9-\"::1:0:1\"]", "tests/test_json.py::test_encoding[input10-\"192.168.0.0/24\"]", "tests/test_json.py::test_encoding[input11-\"2001:db00::/120\"]", "tests/test_json.py::test_encoding[input12-\"192.168.0.0/24\"]", "tests/test_json.py::test_encoding[input13-\"2001:db00::/120\"]", "tests/test_json.py::test_encoding[input14-\"2032-01-01T01:01:00\"]", "tests/test_json.py::test_encoding[input15-\"2032-01-01T01:01:00+00:00\"]", "tests/test_json.py::test_encoding[input16-\"2032-01-01T00:00:00\"]", "tests/test_json.py::test_encoding[input17-\"12:34:56\"]", "tests/test_json.py::test_encoding[input18-1036834.000056]", "tests/test_json.py::test_encoding[input19--1.0]", "tests/test_json.py::test_encoding[input20-[1,", "tests/test_json.py::test_encoding[input21-[1,", "tests/test_json.py::test_encoding[<genexpr>-[0,", "tests/test_json.py::test_encoding[this", "tests/test_json.py::test_encoding[input24-12.34]", "tests/test_json.py::test_encoding[input25-{\"a\":", "tests/test_json.py::test_encoding[MyEnum.foo-\"bar\"]", "tests/test_json.py::test_encoding[^regex$-\"^regex$\"]", "tests/test_json.py::test_path_encoding", "tests/test_json.py::test_model_encoding", "tests/test_json.py::test_subclass_encoding", "tests/test_json.py::test_subclass_custom_encoding", "tests/test_json.py::test_invalid_model", "tests/test_json.py::test_iso_timedelta[input0-P12DT0H0M34.000056S]", "tests/test_json.py::test_iso_timedelta[input1-P1001DT1H2M3.654321S]", "tests/test_json.py::test_iso_timedelta[input2--P1DT23H59M59.000000S]", "tests/test_json.py::test_iso_timedelta[input3-P0DT0H0M0.000000S]", "tests/test_json.py::test_custom_encoder", "tests/test_json.py::test_custom_iso_timedelta", "tests/test_json.py::test_con_decimal_encode", "tests/test_json.py::test_json_encoder_simple_inheritance", "tests/test_json.py::test_json_encoder_inheritance_override", "tests/test_json.py::test_custom_encoder_arg", "tests/test_json.py::test_encode_dataclass", "tests/test_json.py::test_encode_pydantic_dataclass", "tests/test_json.py::test_encode_custom_root", "tests/test_json.py::test_custom_decode_encode", "tests/test_json.py::test_json_nested_encode_models", "tests/test_json.py::test_custom_encode_fallback_basemodel", "tests/test_json.py::test_custom_encode_error", "tests/test_json.py::test_recursive", "tests/test_json.py::test_inner_custom_encoding" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-03-26 12:45:36+00:00
mit
4,858
pydantic__pydantic-3946
diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -4,7 +4,7 @@ from enum import Enum from functools import partial from pathlib import Path -from types import FunctionType +from types import FunctionType, prepare_class, resolve_bases from typing import ( TYPE_CHECKING, AbstractSet, @@ -996,8 +996,12 @@ def create_model( namespace.update(fields) if __config__: namespace['Config'] = inherit_config(__config__, BaseConfig) - - return type(__model_name, __base__, namespace, **__cls_kwargs__) + resolved_bases = resolve_bases(__base__) + meta, ns, kwds = prepare_class(__model_name, resolved_bases, kwds=__cls_kwargs__) + if resolved_bases is not __base__: + ns['__orig_bases__'] = __base__ + namespace.update(ns) + return meta(__model_name, resolved_bases, namespace, **kwds) _missing = object()
pydantic/pydantic
4fb872ef3aada7ca9e64b464af9bd5c4f3d232f2
diff --git a/tests/test_create_model.py b/tests/test_create_model.py --- a/tests/test_create_model.py +++ b/tests/test_create_model.py @@ -1,6 +1,9 @@ +from typing import Generic, TypeVar + import pytest from pydantic import BaseModel, Extra, Field, ValidationError, create_model, errors, validator +from pydantic.generics import GenericModel def test_create_model(): @@ -205,3 +208,17 @@ class Config: m2 = create_model('M2', __config__=Config, a=(str, Field(...))) assert m2.schema()['properties'] == {'a': {'title': 'A', 'description': 'descr', 'type': 'string'}} + + +def test_generics_model(): + T = TypeVar('T') + + class TestGenericModel(GenericModel): + pass + + AAModel = create_model( + 'AAModel', __base__=(TestGenericModel, Generic[T]), __cls_kwargs__={'orm_mode': True}, aa=(int, Field(0)) + ) + result = AAModel[int](aa=1) + assert result.aa == 1 + assert result.__config__.orm_mode is True
create_model not support generics model ### Checks * [x] I added a descriptive title to this issue * [x] I have searched (google, github) for similar issues and couldn't find anything * [x] I have read and followed [the docs](https://pydantic-docs.helpmanual.io/) and still think this is a bug # Bug ``` from typing import Generic, TypeVar from pydantic import Field, create_model from pydantic.generics import GenericModel T = TypeVar("T") class TestGenericModel(GenericModel): pass AAModel = create_model("AAModel", __base__=(TestGenericModel, Generic[T]), aa=(int, Field(0))) AAModel[int](aa=1) ``` output ```py Traceback (most recent call last): File "test.py", line 13, in <module> AAModel = create_model("AAModel", __base__=(TestGenericModel, Generic[T]), aa=(int, Field(0))) File "pydantic/main.py", line 972, in pydantic.main.create_model TypeError: type() doesn't support MRO entry resolution; use types.new_class() ```
0.0
4fb872ef3aada7ca9e64b464af9bd5c4f3d232f2
[ "tests/test_create_model.py::test_generics_model" ]
[ "tests/test_create_model.py::test_create_model", "tests/test_create_model.py::test_create_model_usage", "tests/test_create_model.py::test_create_model_pickle", "tests/test_create_model.py::test_invalid_name", "tests/test_create_model.py::test_field_wrong_tuple", "tests/test_create_model.py::test_config_and_base", "tests/test_create_model.py::test_inheritance", "tests/test_create_model.py::test_custom_config", "tests/test_create_model.py::test_custom_config_inherits", "tests/test_create_model.py::test_custom_config_extras", "tests/test_create_model.py::test_inheritance_validators", "tests/test_create_model.py::test_inheritance_validators_always", "tests/test_create_model.py::test_inheritance_validators_all", "tests/test_create_model.py::test_funky_name", "tests/test_create_model.py::test_repeat_base_usage", "tests/test_create_model.py::test_dynamic_and_static", "tests/test_create_model.py::test_config_field_info_create_model" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2022-03-28 14:12:58+00:00
mit
4,859
pydantic__pydantic-3975
diff --git a/pydantic/env_settings.py b/pydantic/env_settings.py --- a/pydantic/env_settings.py +++ b/pydantic/env_settings.py @@ -63,6 +63,7 @@ def _build_values( env_nested_delimiter=( _env_nested_delimiter if _env_nested_delimiter is not None else self.__config__.env_nested_delimiter ), + env_prefix_len=len(self.__config__.env_prefix), ) file_secret_settings = SecretsSettingsSource(secrets_dir=_secrets_dir or self.__config__.secrets_dir) # Provide a hook to set built-in sources priority and add / remove sources @@ -142,14 +143,19 @@ def __repr__(self) -> str: class EnvSettingsSource: - __slots__ = ('env_file', 'env_file_encoding', 'env_nested_delimiter') + __slots__ = ('env_file', 'env_file_encoding', 'env_nested_delimiter', 'env_prefix_len') def __init__( - self, env_file: Optional[StrPath], env_file_encoding: Optional[str], env_nested_delimiter: Optional[str] = None + self, + env_file: Optional[StrPath], + env_file_encoding: Optional[str], + env_nested_delimiter: Optional[str] = None, + env_prefix_len: int = 0, ): self.env_file: Optional[StrPath] = env_file self.env_file_encoding: Optional[str] = env_file_encoding self.env_nested_delimiter: Optional[str] = env_nested_delimiter + self.env_prefix_len: int = env_prefix_len def __call__(self, settings: BaseSettings) -> Dict[str, Any]: # noqa C901 """ @@ -228,7 +234,9 @@ def explode_env_vars(self, field: ModelField, env_vars: Mapping[str, Optional[st for env_name, env_val in env_vars.items(): if not any(env_name.startswith(prefix) for prefix in prefixes): continue - _, *keys, last_key = env_name.split(self.env_nested_delimiter) + # we remove the prefix before splitting in case the prefix has characters in common with the delimiter + env_name_without_prefix = env_name[self.env_prefix_len :] + _, *keys, last_key = env_name_without_prefix.split(self.env_nested_delimiter) env_var = result for key in keys: env_var = env_var.setdefault(key, {})
pydantic/pydantic
8997cc5961139dd2695761a33c06a66adbf1430a
diff --git a/tests/test_settings.py b/tests/test_settings.py --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -134,6 +134,33 @@ class Config: } +def test_nested_env_delimiter_with_prefix(env): + class Subsettings(BaseSettings): + banana: str + + class Settings(BaseSettings): + subsettings: Subsettings + + class Config: + env_nested_delimiter = '_' + env_prefix = 'myprefix_' + + env.set('myprefix_subsettings_banana', 'banana') + s = Settings() + assert s.subsettings.banana == 'banana' + + class Settings(BaseSettings): + subsettings: Subsettings + + class Config: + env_nested_delimiter = '_' + env_prefix = 'myprefix__' + + env.set('myprefix__subsettings_banana', 'banana') + s = Settings() + assert s.subsettings.banana == 'banana' + + def test_nested_env_delimiter_complex_required(env): class Cfg(BaseSettings): v: str = 'default'
Unexpected behaviour if the prefix contains the env_nested_delimiter ### Checks * [x] I added a descriptive title to this issue * [x] I have searched (google, github) for similar issues and couldn't find anything * [x] I have read and followed [the docs](https://pydantic-docs.helpmanual.io/) and still think this is a bug <!-- Sorry to sound so draconian, but every second saved replying to issues is time spend improving pydantic :-) --> # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` $ python -c "import pydantic.utils; print(pydantic.utils.version_info())" pydantic version: 1.9.0 pydantic compiled: True install path: /usr/local/lib/python3.8/site-packages/pydantic python version: 3.8.12 (default, Oct 12 2021, 03:05:25) [GCC 10.2.1 20210110] platform: Linux-5.13.0-28-generic-x86_64-with-glibc2.2.5 optional deps. installed: ['dotenv', 'typing-extensions'] ``` <!-- or if you're using pydantic prior to v1.3, manually include: OS, python version and pydantic version --> <!-- Please read the [docs](https://pydantic-docs.helpmanual.io/) and search through issues to confirm your bug hasn't already been reported. --> <!-- Where possible please include a self-contained code snippet describing your bug: --> ```py import os import pydantic import pytest @pytest.fixture def env(): original_env = os.environ.copy() yield os.environ os.environ.clear() os.environ.update(original_env) def test_env_nested_delimiter_in_prefix(env): """Test pydantic fails to set value where the prefix has the delimiter. Pydantic will break down `settings_sub_value` to `{sub: {value: ...}}` and it will pass it to `settings.sub`, so it will fail to populate `settings.sub.value` and it will try to set `settings.sub.sub`. """ class SubSettings(pydantic.BaseSettings): value: str class Settings(pydantic.BaseSettings): sub: SubSettings class Config: env_prefix = "settings_" env_nested_delimiter = "_" env["settings_sub_value"] = "won't be set" expected_error = ( # settings.sub.value doesn't get set r".*sub -> value.*\n?.*value_error\.missing.*\n?" # Tries to assign settings.sub.sub r".*sub -> sub.*\n?.*value_error\.extra" ) with pytest.raises(pydantic.ValidationError, match=expected_error): Settings() def test_env_nested_delimiter_in_field(env): """Test pydantic fails to set value where the field has the delimiter. Pydantic will break down `with_delimiter_value` to `{delimiter: {value: ...}}` and it will pass it to `settings.with_delimiter`, so it will fail to populate `settings.with_delimiter.value` and it will try to set `settings.with_delimiter.delimiter`. """ class SubSettings(pydantic.BaseSettings): value: str class Settings(pydantic.BaseSettings): with_delimiter: SubSettings class Config: env_nested_delimiter = "_" env["with_delimiter_value"] = "won't be set" expected_error = ( # settings.with_delimiter.value doesn't get set r".*with_delimiter -> value.*\n?.*value_error\.missing.*\n?" # Tries to set settings.with_delimiter.delimiter r".*with_delimiter -> delimiter.*\n?.*value_error\.extra" ) with pytest.raises(pydantic.ValidationError, match=expected_error): Settings() ``` In my opinion this behaviour is wrong. Pydantic should either support this or raise an error that the class is wrongly configured. But the way it behaves right now is confusing since there's no error of wrong class setup, but the fields don't get set as expected from the environment variables. Here's a possible solution on adding support for allowing to have the delimiter in both in the prefix and in the field name: ```py class PrefixFixedEnvSettingsSource(EnvSettingsSource): def explode_env_vars( self, field: ModelField, env_vars: Mapping[str, Optional[str]] ) -> Dict[str, Any]: """ Fix original explode_env_vars which splits the prefix with env_nested_delimiter. This implemetation doesn't split the prefix. """ prefixes = [ f"{env_name}{self.env_nested_delimiter}" for env_name in field.field_info.extra["env_names"] ] result: Dict[str, Any] = {} for env_name, env_val in env_vars.items(): matching_prefixes = [ prefix for prefix in prefixes if env_name.startswith(prefix) ] if not matching_prefixes: continue longest_prefix = max(len(prefix) for prefix in matching_prefixes) *keys, last_key = env_name[longest_prefix:].split(self.env_nested_delimiter) env_var = result for key in keys: env_var = env_var.setdefault(key, {}) env_var[last_key] = env_val return result ``` Unexpected behaviour if the prefix contains the env_nested_delimiter ### Checks * [x] I added a descriptive title to this issue * [x] I have searched (google, github) for similar issues and couldn't find anything * [x] I have read and followed [the docs](https://pydantic-docs.helpmanual.io/) and still think this is a bug <!-- Sorry to sound so draconian, but every second saved replying to issues is time spend improving pydantic :-) --> # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` $ python -c "import pydantic.utils; print(pydantic.utils.version_info())" pydantic version: 1.9.0 pydantic compiled: True install path: /usr/local/lib/python3.8/site-packages/pydantic python version: 3.8.12 (default, Oct 12 2021, 03:05:25) [GCC 10.2.1 20210110] platform: Linux-5.13.0-28-generic-x86_64-with-glibc2.2.5 optional deps. installed: ['dotenv', 'typing-extensions'] ``` <!-- or if you're using pydantic prior to v1.3, manually include: OS, python version and pydantic version --> <!-- Please read the [docs](https://pydantic-docs.helpmanual.io/) and search through issues to confirm your bug hasn't already been reported. --> <!-- Where possible please include a self-contained code snippet describing your bug: --> ```py import os import pydantic import pytest @pytest.fixture def env(): original_env = os.environ.copy() yield os.environ os.environ.clear() os.environ.update(original_env) def test_env_nested_delimiter_in_prefix(env): """Test pydantic fails to set value where the prefix has the delimiter. Pydantic will break down `settings_sub_value` to `{sub: {value: ...}}` and it will pass it to `settings.sub`, so it will fail to populate `settings.sub.value` and it will try to set `settings.sub.sub`. """ class SubSettings(pydantic.BaseSettings): value: str class Settings(pydantic.BaseSettings): sub: SubSettings class Config: env_prefix = "settings_" env_nested_delimiter = "_" env["settings_sub_value"] = "won't be set" expected_error = ( # settings.sub.value doesn't get set r".*sub -> value.*\n?.*value_error\.missing.*\n?" # Tries to assign settings.sub.sub r".*sub -> sub.*\n?.*value_error\.extra" ) with pytest.raises(pydantic.ValidationError, match=expected_error): Settings() def test_env_nested_delimiter_in_field(env): """Test pydantic fails to set value where the field has the delimiter. Pydantic will break down `with_delimiter_value` to `{delimiter: {value: ...}}` and it will pass it to `settings.with_delimiter`, so it will fail to populate `settings.with_delimiter.value` and it will try to set `settings.with_delimiter.delimiter`. """ class SubSettings(pydantic.BaseSettings): value: str class Settings(pydantic.BaseSettings): with_delimiter: SubSettings class Config: env_nested_delimiter = "_" env["with_delimiter_value"] = "won't be set" expected_error = ( # settings.with_delimiter.value doesn't get set r".*with_delimiter -> value.*\n?.*value_error\.missing.*\n?" # Tries to set settings.with_delimiter.delimiter r".*with_delimiter -> delimiter.*\n?.*value_error\.extra" ) with pytest.raises(pydantic.ValidationError, match=expected_error): Settings() ``` In my opinion this behaviour is wrong. Pydantic should either support this or raise an error that the class is wrongly configured. But the way it behaves right now is confusing since there's no error of wrong class setup, but the fields don't get set as expected from the environment variables. Here's a possible solution on adding support for allowing to have the delimiter in both in the prefix and in the field name: ```py class PrefixFixedEnvSettingsSource(EnvSettingsSource): def explode_env_vars( self, field: ModelField, env_vars: Mapping[str, Optional[str]] ) -> Dict[str, Any]: """ Fix original explode_env_vars which splits the prefix with env_nested_delimiter. This implemetation doesn't split the prefix. """ prefixes = [ f"{env_name}{self.env_nested_delimiter}" for env_name in field.field_info.extra["env_names"] ] result: Dict[str, Any] = {} for env_name, env_val in env_vars.items(): matching_prefixes = [ prefix for prefix in prefixes if env_name.startswith(prefix) ] if not matching_prefixes: continue longest_prefix = max(len(prefix) for prefix in matching_prefixes) *keys, last_key = env_name[longest_prefix:].split(self.env_nested_delimiter) env_var = result for key in keys: env_var = env_var.setdefault(key, {}) env_var[last_key] = env_val return result ```
0.0
8997cc5961139dd2695761a33c06a66adbf1430a
[ "tests/test_settings.py::test_nested_env_delimiter_with_prefix" ]
[ "tests/test_settings.py::test_sub_env", "tests/test_settings.py::test_sub_env_override", "tests/test_settings.py::test_sub_env_missing", "tests/test_settings.py::test_other_setting", "tests/test_settings.py::test_with_prefix", "tests/test_settings.py::test_nested_env_with_basemodel", "tests/test_settings.py::test_merge_dict", "tests/test_settings.py::test_nested_env_delimiter", "tests/test_settings.py::test_nested_env_delimiter_complex_required", "tests/test_settings.py::test_nested_env_delimiter_aliases", "tests/test_settings.py::test_list", "tests/test_settings.py::test_set_dict_model", "tests/test_settings.py::test_invalid_json", "tests/test_settings.py::test_required_sub_model", "tests/test_settings.py::test_non_class", "tests/test_settings.py::test_env_str", "tests/test_settings.py::test_env_list", "tests/test_settings.py::test_env_list_field", "tests/test_settings.py::test_env_list_last", "tests/test_settings.py::test_env_inheritance", "tests/test_settings.py::test_env_inheritance_field", "tests/test_settings.py::test_env_prefix_inheritance_config", "tests/test_settings.py::test_env_inheritance_config", "tests/test_settings.py::test_env_invalid", "tests/test_settings.py::test_env_field", "tests/test_settings.py::test_aliases_warning", "tests/test_settings.py::test_aliases_no_warning", "tests/test_settings.py::test_case_sensitive", "tests/test_settings.py::test_nested_dataclass", "tests/test_settings.py::test_env_takes_precedence", "tests/test_settings.py::test_config_file_settings_nornir", "tests/test_settings.py::test_env_union_with_complex_subfields_parses_json", "tests/test_settings.py::test_env_union_with_complex_subfields_parses_plain_if_json_fails", "tests/test_settings.py::test_env_union_without_complex_subfields_does_not_parse_json", "tests/test_settings.py::test_env_file_config", "tests/test_settings.py::test_env_file_config_case_sensitive", "tests/test_settings.py::test_env_file_export", "tests/test_settings.py::test_env_file_config_custom_encoding", "tests/test_settings.py::test_env_file_home_directory", "tests/test_settings.py::test_env_file_none", "tests/test_settings.py::test_env_file_override_file", "tests/test_settings.py::test_env_file_override_none", "tests/test_settings.py::test_env_file_not_a_file", "tests/test_settings.py::test_read_env_file_cast_sensitive", "tests/test_settings.py::test_read_env_file_syntax_wrong", "tests/test_settings.py::test_env_file_example", "tests/test_settings.py::test_env_file_custom_encoding", "tests/test_settings.py::test_alias_set", "tests/test_settings.py::test_prefix_on_parent", "tests/test_settings.py::test_frozenset", "tests/test_settings.py::test_secrets_path", "tests/test_settings.py::test_secrets_path_url", "tests/test_settings.py::test_secrets_path_json", "tests/test_settings.py::test_secrets_path_invalid_json", "tests/test_settings.py::test_secrets_missing", "tests/test_settings.py::test_secrets_invalid_secrets_dir", "tests/test_settings.py::test_secrets_missing_location", "tests/test_settings.py::test_secrets_file_is_a_directory", "tests/test_settings.py::test_secrets_dotenv_precedence", "tests/test_settings.py::test_external_settings_sources_precedence", "tests/test_settings.py::test_external_settings_sources_filter_env_vars", "tests/test_settings.py::test_customise_sources_empty", "tests/test_settings.py::test_builtins_settings_source_repr" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2022-04-04 20:10:48+00:00
mit
4,860
pydantic__pydantic-4012
diff --git a/pydantic/utils.py b/pydantic/utils.py --- a/pydantic/utils.py +++ b/pydantic/utils.py @@ -1,3 +1,4 @@ +import keyword import warnings import weakref from collections import OrderedDict, defaultdict, deque @@ -56,6 +57,7 @@ 'lenient_isinstance', 'lenient_issubclass', 'in_ipython', + 'is_valid_identifier', 'deep_update', 'update_not_none', 'almost_equal_floats', @@ -192,6 +194,15 @@ def in_ipython() -> bool: return True +def is_valid_identifier(identifier: str) -> bool: + """ + Checks that a string is a valid identifier and not a Python keyword. + :param identifier: The identifier to test. + :return: True if the identifier is valid. + """ + return identifier.isidentifier() and not keyword.iskeyword(identifier) + + KeyType = TypeVar('KeyType') @@ -244,8 +255,8 @@ def generate_model_signature( param_name = field.alias if field_name in merged_params or param_name in merged_params: continue - elif not param_name.isidentifier(): - if allow_names and field_name.isidentifier(): + elif not is_valid_identifier(param_name): + if allow_names and is_valid_identifier(field_name): param_name = field_name else: use_var_kw = True
pydantic/pydantic
8997cc5961139dd2695761a33c06a66adbf1430a
diff --git a/tests/test_model_signature.py b/tests/test_model_signature.py --- a/tests/test_model_signature.py +++ b/tests/test_model_signature.py @@ -84,6 +84,16 @@ class Config: assert _equals(str(signature(Foo)), '(*, foo: str) -> None') +def test_does_not_use_reserved_word(): + class Foo(BaseModel): + from_: str = Field(..., alias='from') + + class Config: + allow_population_by_field_name = True + + assert _equals(str(signature(Foo)), '(*, from_: str) -> None') + + def test_extra_allow_no_conflict(): class Model(BaseModel): spam: str
Model signatures contain reserved words. ### Checks * [x] I added a descriptive title to this issue * [x] I have searched (google, github) for similar issues and couldn't find anything * [x] I have read and followed [the docs](https://pydantic-docs.helpmanual.io/) and still think this is a bug # Bug When creating a model with a field that has an alias that is a python reserved word, the signature uses the reserved word even when `allow_population_by_field_name` is true. I expect the signature to use the field name in this case. I came across this issue when generating tests using hypothesis. This uses the model signature and was creating invalid test code as it was using the reserved words in the signature. ``` pydantic version: 1.9.0 pydantic compiled: False python version: 3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] platform: Windows-10-10.0.19041-SP0 optional deps. installed: ['devtools', 'dotenv', 'email-validator', 'typing-extensions'] ``` ```py from pydantic import BaseModel, Field from inspect import signature class Foo(BaseModel): from_: str = Field(..., alias='from') class Config: allow_population_by_field_name = True str(signature(Foo)) ``` > '(*, from: str) -> None' # Suggestion In `utils.generate_model_signature()` we have these two checks. ```py elif not param_name.isidentifier(): if allow_names and field_name.isidentifier(): ``` I propose replacing these with calls to the following (new) function. ```py def is_valid_identifier(identifier: str) -> bool: """ Checks that a string is a valid identifier and not a reserved word. :param identifier: The identifier to test. :return: True if the identifier is valid. """ return identifier.isidentifier() and not keyword.iskeyword(identifier) ``` I believe that this behaviour is closer to what a user would expect in the common case that they are generating models from a schema containing python reserved words.
0.0
8997cc5961139dd2695761a33c06a66adbf1430a
[ "tests/test_model_signature.py::test_does_not_use_reserved_word" ]
[ "tests/test_model_signature.py::test_model_signature", "tests/test_model_signature.py::test_custom_init_signature", "tests/test_model_signature.py::test_custom_init_signature_with_no_var_kw", "tests/test_model_signature.py::test_invalid_identifiers_signature", "tests/test_model_signature.py::test_use_field_name", "tests/test_model_signature.py::test_extra_allow_no_conflict", "tests/test_model_signature.py::test_extra_allow_conflict", "tests/test_model_signature.py::test_extra_allow_conflict_twice", "tests/test_model_signature.py::test_extra_allow_conflict_custom_signature", "tests/test_model_signature.py::test_signature_is_class_only" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-04-25 16:42:47+00:00
mit
4,861
pydantic__pydantic-4067
diff --git a/pydantic/fields.py b/pydantic/fields.py --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -1,3 +1,4 @@ +import copy from collections import Counter as CollectionCounter, defaultdict, deque from collections.abc import Hashable as CollectionsHashable, Iterable as CollectionsIterable from typing import ( @@ -446,6 +447,7 @@ def _get_field_info( raise ValueError(f'cannot specify multiple `Annotated` `Field`s for {field_name!r}') field_info = next(iter(field_infos), None) if field_info is not None: + field_info = copy.copy(field_info) field_info.update_from_config(field_info_from_config) if field_info.default is not Undefined: raise ValueError(f'`Field` default cannot be set in `Annotated` for {field_name!r}')
pydantic/pydantic
42acd8f8d2bd22f114e589672a054fe07a769e45
+1 ran into this issue, it's a very valid use case and should be an easy fix This also will happen if you call `ModelField.infer` twice on the same parameter/field, even if you are not using a type alias Seems like we are also affected by this issue. Any chance to fix this soon? @PrettyWood any chance the team can get to this bug soon? This appears related to #3714. @Jaakkonen - did you try running the unit tests after changing to a copy of the `FieldInfo` object? I got some failures so it might be that this mutation is required in other places. ``` FAILED tests/test_generics.py::test_replace_types - IndexError: tuple index out of range FAILED tests/test_schema.py::test_unenforced_constraints_schema[kwargs9-type_9] - IndexError: tuple index out of range Results (36.46s): 2287 passed 2 failed - tests/test_generics.py:761 test_replace_types - tests/test_schema.py:1520 test_unenforced_constraints_schema[kwargs9-type_9] 7 skipped make: *** [Makefile:63: test] Error 1 ``` @adriangb any chance you could have a go at a fix? 😄 🙏 I think this is also causing #3714 which in turn in one of the only remaining blockers to v1.9.1. BTW, I find that the code works with pydantic 1.8.2, so this problem may be introduced via 1.9.0 I also experience the same behavior as @StephenPCG. ``` C:\dev\pydantic-discrimination-union-problem>python -c "import pydantic.utils; print(pydantic.utils.version_info())" pydantic version: 1.9.0 pydantic compiled: True install path: C:\Users\jol\venv\pydantic-discrimination-union-problem\Lib\site-packages\pydantic python version: 3.9.9 (tags/v3.9.9:ccb0e6a, Nov 15 2021, 18:08:50) [MSC v.1929 64 bit (AMD64)] platform: Windows-10-10.0.19043-SP0 optional deps. installed: ['typing-extensions'] ``` I have a bigger example ([source](https://github.com/josteinl/pydantic-discrimination-union-problem/tree/pydantic_1.9.0_trial#yet-another-problem)) using FastAPI. ```python import enum from typing import List, Union, Literal from typing_extensions import Annotated from fastapi import FastAPI from pydantic import Field, BaseModel import uvicorn class CutleryTypeEnum(enum.IntEnum): KNIFE = 1 FORK = 2 SPOON = 3 class CutleryBase(BaseModel): name: str class Knife(CutleryBase): cutlery_type_id: Literal[CutleryTypeEnum.KNIFE] class Fork(CutleryBase): cutlery_type_id: Literal[CutleryTypeEnum.FORK] number_of_teeth: int = None class Spoon(CutleryBase): cutlery_type_id: Literal[CutleryTypeEnum.SPOON] volume: float = None Cutlery = Annotated[ Union[Knife, Fork, Spoon], Field(discriminator='cutlery_type_id'), ] app = FastAPI() @app.get("/cutlery", response_model=List[Cutlery]) async def get_cutlery(): return [{'cutlery_type_id': CutleryTypeEnum.KNIFE, 'name': 'My sharp knife'}, {'cutlery_type_id': CutleryTypeEnum.FORK, 'name': 'The three teeth fork'}, {'cutlery_type_id': CutleryTypeEnum.SPOON, 'name': 'Tea spoon'}] # # Enable the second usage of Cutlery result in traceback on startup # @app.get("/cutlery2", response_model=List[Cutlery]) async def get_cutlery2(): return [{'cutlery_type_id': CutleryTypeEnum.KNIFE, 'name': 'My sharp knife'}, {'cutlery_type_id': CutleryTypeEnum.KNIFE, 'name': 'My knife is sharp'}, {'cutlery_type_id': CutleryTypeEnum.FORK, 'name': 'The three teeth fork'}, {'cutlery_type_id': CutleryTypeEnum.SPOON, 'name': 'Tea spoon'}] uvicorn.run(app, host='127.0.0.1', port=80) ``` If I enable the endpoint /cutlery2 I get the following traceback on start-up: ``` python main.py Traceback (most recent call last): File "C:\dev\pydantic-discrimination-union-problem\main.py", line 64, in <module> async def get_cutlery2(): File "C:\Users\jol\venv\pydantic-discrimination-union-problem\lib\site-packages\fastapi\routing.py", line 582, in decorator self.add_api_route( File "C:\Users\jol\venv\pydantic-discrimination-union-problem\lib\site-packages\fastapi\routing.py", line 525, in add_api_route route = route_class( File "C:\Users\jol\venv\pydantic-discrimination-union-problem\lib\site-packages\fastapi\routing.py", line 351, in __init__ self.response_field = create_response_field( File "C:\Users\jol\venv\pydantic-discrimination-union-problem\lib\site-packages\fastapi\utils.py", line 65, in create_response_field return response_field(field_info=field_info) File "pydantic\fields.py", line 419, in pydantic.fields.ModelField.__init__ File "pydantic\fields.py", line 534, in pydantic.fields.ModelField.prepare File "pydantic\fields.py", line 728, in pydantic.fields.ModelField._type_analysis File "pydantic\fields.py", line 776, in pydantic.fields.ModelField._create_sub_type File "pydantic\fields.py", line 451, in pydantic.fields.ModelField._get_field_info ValueError: `Field` default cannot be set in `Annotated` for '_Response_get_cutlery2_cutlery2_get' ``` Replacing my Cutlery class with this seems to work OK: ```python class Cutlery(BaseModel): __root__: Annotated[ Union[Knife, Fork, Spoon], Field(discriminator='cutlery_type_id'), ] ``` > BTW, I find that the code works with pydantic 1.8.2, so this problem may be introduced via 1.9.0 Thanks for that. Some code working last year with 1.8.2 is not working with 1.9.0 and it looks like this is the reason. Also experiencing this error. In my case the error appears when I use an Annotated field twice in the same model. Using Pydantic v1.9.0. ``` from typing import Literal, Union, List from typing_extensions import Annotated from pydantic import BaseModel, Field class Cat(BaseModel): pet_type: Literal['cat'] class Dog(BaseModel): pet_type: Literal['dog'] Pets = Annotated[Union[Cat, Dog], Field(discriminator='pet_type')] # noqa: F821 class Model(BaseModel): pets_field1: Pets pets_field2: List[Pets] ``` `ValueError: 'Field' default cannot be set in 'Annotated' for 'pets_field2'` I think the fundamental problem here is the usage of our `Annotated` class inside a `List[]`. The code around this is way too complicated for me to understand. @havardthom have you tried to define `Pets` as: ```python class Pets(BaseModel): __root__: Annotated[ Union[Cat, Dog], Field(discriminator='pet_type'), ] ``` > I think the fundamental problem here is the usage of our `Annotated` class inside a `List[]`. The code around this is way too complicated for me to understand. > > @havardthom have you tried to define `Pets` as: > > ```python > class Pets(BaseModel): > __root__: Annotated[ > Union[Cat, Dog], > Field(discriminator='pet_type'), > ] > ``` Yes I got it working with root model, although I had to refactor parts of my solution to extract the `__root__` object. A pure annotation field would be preferable. I confirm that the following code runs smoothly in pydantic 1.8.2 but raises an error (as noted) in 1.9.0 ```python from __future__ import annotations from typing import List from typing import Literal from typing import Union from pydantic import BaseModel from pydantic import Field from typing_extensions import Annotated class A(BaseModel): operator: Literal["a"] foo: str cs: List[C] class B(BaseModel): operator: Literal["b"] foo: str cs: List[C] C = Annotated[ Union[A, B], Field(discriminator="operator"), ] A.update_forward_refs() # B is not prepared and requires call to update_forward_refs # but this will yield a ValueError in pydantic 1.9.0 B.update_forward_refs() # ValueError: `Field` default cannot be set in `Annotated` for '_cs' ```` Using a redefinition of `C` like suggested above (and in the docs) ```python class C(BaseModel): __root__: Annotated[Union[A, B], Field(discriminator="operator")] ``` does make the code run. However, it seems to also require some additional imho rather ugly attribute access ```python b = B(operator="b", foo="foo", cs=[A(operator="a", foo="bar", cs=[]] ) print( b.cs[0].__root__.bar ) # instead of previously b.cs[0].bar ``` Ran into this too, I've tried to see if I can understand what is causing this as `DiscriminatedUnion` is a super useful feature! Looks like this is a regression that was previously [caught here](https://github.com/samuelcolvin/pydantic/pull/2147/commits/6835179f5c431fa071dd50dfdc31685f2463a23c). The issue seems to be that the FieldInfo/Annotation is being mutated to set the default, which means on the second time around this is getting tripped up The regression appears to be introduced here when the `__eq__` was fixed: #2502 (specifically [this line](https://github.com/samuelcolvin/pydantic/blob/master/pydantic/fields.py#L454)) @PrettyWood / @JacobHayes - do you think it would it make sense to have a way of cloning the object here to avoid mutating the object here? Or would it be possible to avoid setting the `default` value here all together? # I've tested a fix where we do not mutate the original `FieldInfo` object, but this causes failures else where (in tests that do not directly call `_get_field_info`) so the it looks like the copy/new is a no go unfortunately. Appears to be related to this too #3702
diff --git a/tests/test_annotated.py b/tests/test_annotated.py --- a/tests/test_annotated.py +++ b/tests/test_annotated.py @@ -1,3 +1,5 @@ +from typing import List + import pytest from typing_extensions import Annotated @@ -132,3 +134,21 @@ class Config: assert Foo.schema(by_alias=True)['properties'] == { 'a': {'title': 'A', 'description': 'descr', 'foobar': 'hello', 'type': 'integer'}, } + + +def test_annotated_alias() -> None: + # https://github.com/samuelcolvin/pydantic/issues/2971 + + StrAlias = Annotated[str, Field(max_length=3)] + IntAlias = Annotated[int, Field(default_factory=lambda: 2)] + + Nested = Annotated[List[StrAlias], Field(description='foo')] + + class MyModel(BaseModel): + a: StrAlias = 'abc' + b: StrAlias + c: IntAlias + d: IntAlias + e: Nested + + assert MyModel(b='def', e=['xyz']) == MyModel(a='abc', b='def', c=2, d=2, e=['xyz'])
Annotated FieldInfo instance is mutated and reused if using type aliases ### Checks * [x] I added a descriptive title to this issue * [x] I have searched (google, github) for similar issues and couldn't find anything * [x] I have read and followed [the docs](https://pydantic-docs.helpmanual.io/) and still think this is a bug <!-- Sorry to sound so draconian, but every second saved replying to issues is time spend improving pydantic :-) --> # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.8.2 pydantic compiled: False install path: /tmp/tmp.pnuPT7tTpf/lib/python3.9/site-packages/pydantic python version: 3.9.6 (default, Jun 30 2021, 10:22:16) [GCC 11.1.0] platform: Linux-5.13.0-rc7-x86_64-with-glibc2.33 optional deps. installed: ['devtools', 'typing-extensions'] ``` Working version ```py from pydantic import BaseModel, constr, Field from typing import Annotated class MyModel(BaseModel): a: Annotated[str, Field(max_length=3)] = '' b: Annotated[str, Field(max_length=3)] MyModel(a="123", b='123', c='123') MyModel(a="1234", b='1234', c='1234') # ValidationError ``` Failing version: ```py from pydantic import BaseModel, constr, Field from typing import Annotated StrField3 = Annotated[str, Field(max_length=3)] class MyModel(BaseModel): # ValueError: `Field` default cannot be set in `Annotated` for 'b' a: StrField3 = '' b: StrField3 ``` The `.default` is set to `''` on the FieldInfo instance at [fields.py:404](https://github.com/samuelcolvin/pydantic/blob/master/pydantic/fields.py#L404). This can be fixed by copying the `FieldInfo` before mutating it and associating it with ModelField. ``` from copy import copy ... class ModelField(Representation): ... @staticmethod def _get_field_info( field_name: str, annotation: Any, value: Any, config: Type['BaseConfig'] ) -> Tuple[FieldInfo, Any]: .... if field_info is not None: field_info = copy(field_info) .... ``` ValueError raised when Nested Discriminated Unions are used twice ### Checks * [x] I added a descriptive title to this issue * [x] I have searched (google, github) for similar issues and couldn't find anything * [x] I have read and followed [the docs](https://pydantic-docs.helpmanual.io/) and still think this is a bug # Bug The Following code is copied from [doc](https://pydantic-docs.helpmanual.io/usage/types/#nested-discriminated-unions) as is except for the last `Model2`: ```py from typing import Literal, Union from typing_extensions import Annotated from pydantic import BaseModel, Field, ValidationError class BlackCat(BaseModel): pet_type: Literal["cat"] color: Literal["black"] black_name: str class WhiteCat(BaseModel): pet_type: Literal["cat"] color: Literal["white"] white_name: str # Can also be written with a custom root type # # class Cat(BaseModel): # __root__: Annotated[Union[BlackCat, WhiteCat], Field(discriminator='color')] Cat = Annotated[Union[BlackCat, WhiteCat], Field(discriminator="color")] class Dog(BaseModel): pet_type: Literal["dog"] name: str Pet = Annotated[Union[Cat, Dog], Field(discriminator="pet_type")] class Model(BaseModel): pet: Pet n: int # The above code is copied as is, the following is added class Model2(BaseModel): pet: Pet n: int ``` Run the above code, without the last `Model2`, the code runs well, but with `Model2`, the code throws the following error: ``` Traceback (most recent call last): File "/Users/stephen/Work/medieco/hub/hub-api/test.py", line 41, in <module> class Model2(BaseModel): File "pydantic/main.py", line 204, in pydantic.main.ModelMetaclass.__new__ File "pydantic/fields.py", line 488, in pydantic.fields.ModelField.infer File "pydantic/fields.py", line 419, in pydantic.fields.ModelField.__init__ File "pydantic/fields.py", line 534, in pydantic.fields.ModelField.prepare File "pydantic/fields.py", line 599, in pydantic.fields.ModelField._type_analysis File "pydantic/fields.py", line 633, in pydantic.fields.ModelField._type_analysis File "pydantic/fields.py", line 776, in pydantic.fields.ModelField._create_sub_type File "pydantic/fields.py", line 451, in pydantic.fields.ModelField._get_field_info ValueError: `Field` default cannot be set in `Annotated` for "pet_Annotated[Union[__main__.BlackCat, __main__.WhiteCat], FieldInfo(discriminator='color', extra={})]" ``` Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.9.0 pydantic compiled: True install path: /Users/stephen/work/.venv/lib/python3.9/site-packages/pydantic python version: 3.9.0 (default, Dec 20 2020, 11:26:29) [Clang 12.0.0 (clang-1200.0.32.28)] platform: macOS-12.1-x86_64-i386-64bit optional deps. installed: ['dotenv', 'email-validator', 'typing-extensions'] ```
0.0
42acd8f8d2bd22f114e589672a054fe07a769e45
[ "tests/test_annotated.py::test_annotated_alias" ]
[ "tests/test_annotated.py::test_annotated[misc-default]", "tests/test_annotated.py::test_annotated[misc-field-default-constraint]", "tests/test_annotated.py::test_annotated[annotated-field-value-default]", "tests/test_annotated.py::test_annotated[annotated-field-default_factory]", "tests/test_annotated.py::test_annotated_model_exceptions[annotated-field-default]", "tests/test_annotated.py::test_annotated_model_exceptions[annotated-field-dup]", "tests/test_annotated.py::test_annotated_model_exceptions[annotated-field-value-field-dup]", "tests/test_annotated.py::test_annotated_model_exceptions[annotated-field-default_factory-value-default]", "tests/test_annotated.py::test_annotated_instance_exceptions[misc-no-default]", "tests/test_annotated.py::test_annotated_instance_exceptions[annotated-field-no-default]", "tests/test_annotated.py::test_field_reuse", "tests/test_annotated.py::test_config_field_info" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2022-05-12 00:43:14+00:00
mit
4,862
pydantic__pydantic-4093
diff --git a/pydantic/config.py b/pydantic/config.py --- a/pydantic/config.py +++ b/pydantic/config.py @@ -2,20 +2,20 @@ from enum import Enum from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, Tuple, Type, Union +from typing_extensions import Literal, Protocol + 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): + class SchemaExtraCallable(Protocol): @overload def __call__(self, schema: Dict[str, Any]) -> None: pass @@ -63,8 +63,10 @@ class BaseConfig: json_encoders: Dict[Union[Type[Any], str], AnyCallable] = {} underscore_attrs_are_private: bool = False - # whether inherited models as fields should be reconstructed as base model - copy_on_model_validation: bool = True + # whether inherited models as fields should be reconstructed as base model, + # and whether such a copy should be shallow or deep + copy_on_model_validation: Literal['none', 'deep', 'shallow'] = 'shallow' + # whether `Union` should check all allowed types before even trying to coerce smart_union: bool = False diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -675,10 +675,28 @@ def __get_validators__(cls) -> 'CallableGenerator': @classmethod def validate(cls: Type['Model'], value: Any) -> 'Model': if isinstance(value, cls): - if cls.__config__.copy_on_model_validation: - return value._copy_and_set_values(value.__dict__, value.__fields_set__, deep=True) - else: + copy_on_model_validation = cls.__config__.copy_on_model_validation + # whether to deep or shallow copy the model on validation, None means do not copy + deep_copy: Optional[bool] = None + if copy_on_model_validation not in {'deep', 'shallow', 'none'}: + # Warn about deprecated behavior + warnings.warn( + "`copy_on_model_validation` should be a string: 'deep', 'shallow' or 'none'", DeprecationWarning + ) + if copy_on_model_validation: + deep_copy = False + + if copy_on_model_validation == 'shallow': + # shallow copy + deep_copy = False + elif copy_on_model_validation == 'deep': + # deep copy + deep_copy = True + + if deep_copy is None: return value + else: + return value._copy_and_set_values(value.__dict__, value.__fields_set__, deep=deep_copy) value = cls._enforce_dict_if_root(value)
pydantic/pydantic
a5edcb35d57a543143b0dc127dbcf8e143c38e6d
Thanks for reporting, please can you provide a self contained example that shows the error. I am experiencing the same, references that would've previously been carried through a hierarchy of types now get broken during validation. I will try to put together a repro and suggest changes to maintain the prior functionality https://github.com/samuelcolvin/pydantic/pull/3642/commits/ae408326e70d84510a8e25e8f6a6ae8871df2fd0 here is a fine repro: https://github.com/PrettyWood/pydantic/blob/ae408326e70d84510a8e25e8f6a6ae8871df2fd0/tests/test_main.py#L1564 That line was changed from `is` to `is not`. This is a breaking change in functionality Well that's not the same as the error shown above, that's just a change in behaviour. sure, but its a breaking change in behavior.
diff --git a/tests/test_main.py b/tests/test_main.py --- a/tests/test_main.py +++ b/tests/test_main.py @@ -1561,18 +1561,66 @@ class Config: assert t.user is not my_user assert t.user.hobbies == ['scuba diving'] - assert t.user.hobbies is not my_user.hobbies # `Config.copy_on_model_validation` does a deep copy + assert t.user.hobbies is my_user.hobbies # `Config.copy_on_model_validation` does a shallow copy assert t.user._priv == 13 assert t.user.password.get_secret_value() == 'hashedpassword' assert t.dict() == {'id': '1234567890', 'user': {'id': 42, 'hobbies': ['scuba diving']}} +def test_model_exclude_copy_on_model_validation_shallow(): + """When `Config.copy_on_model_validation` is set and `Config.copy_on_model_validation_shallow` is set, + do the same as the previous test but perform a shallow copy""" + + class User(BaseModel): + class Config: + copy_on_model_validation = 'shallow' + + hobbies: List[str] + + my_user = User(hobbies=['scuba diving']) + + class Transaction(BaseModel): + user: User = Field(...) + + t = Transaction(user=my_user) + + assert t.user is not my_user + assert t.user.hobbies is my_user.hobbies # unlike above, this should be a shallow copy + + [email protected]('comv_value', [True, False]) +def test_copy_on_model_validation_warning(comv_value): + class User(BaseModel): + class Config: + # True interpreted as 'shallow', False interpreted as 'none' + copy_on_model_validation = comv_value + + hobbies: List[str] + + my_user = User(hobbies=['scuba diving']) + + class Transaction(BaseModel): + user: User + + with pytest.warns(DeprecationWarning, match="`copy_on_model_validation` should be a string: 'deep', 'shallow' or"): + t = Transaction(user=my_user) + + if comv_value: + assert t.user is not my_user + else: + assert t.user is my_user + assert t.user.hobbies is my_user.hobbies + + def test_validation_deep_copy(): """By default, Config.copy_on_model_validation should do a deep copy""" class A(BaseModel): name: str + class Config: + copy_on_model_validation = 'deep' + class B(BaseModel): list_a: List[A] @@ -1987,7 +2035,7 @@ def __hash__(self): return id(self) class Config: - copy_on_model_validation = False + copy_on_model_validation = 'none' class Item(BaseModel): images: List[Image]
1.9.1 Breaking change with model deep copying ### Checks * [X] I added a descriptive title to this issue * [X] I have searched (google, github) for similar issues and couldn't find anything * [X] I have read and followed [the docs](https://pydantic-docs.helpmanual.io/) and still think this is a bug <!-- Sorry to sound so draconian, but every second saved replying to issues is time spend improving pydantic :-) --> # Bug https://github.com/samuelcolvin/pydantic/pull/3642/files The above PR changes the way models are copied and has created a breaking change in our code base. When running our test suite we now get the following error: ```log INTERNALERROR> File "/Users/worx/ape/src/ape_test/providers.py", line 19, in __init__ INTERNALERROR> super().__init__(**data) INTERNALERROR> File "pydantic/main.py", line 339, in pydantic.main.BaseModel.__init__ INTERNALERROR> File "pydantic/main.py", line 1038, in pydantic.main.validate_model INTERNALERROR> File "pydantic/fields.py", line 857, in pydantic.fields.ModelField.validate INTERNALERROR> File "pydantic/fields.py", line 1074, in pydantic.fields.ModelField._validate_singleton INTERNALERROR> File "pydantic/fields.py", line 1121, in pydantic.fields.ModelField._apply_validators INTERNALERROR> File "pydantic/class_validators.py", line 313, in pydantic.class_validators._generic_validator_basic.lambda12 INTERNALERROR> File "pydantic/main.py", line 679, in pydantic.main.BaseModel.validate INTERNALERROR> File "pydantic/main.py", line 605, in pydantic.main.BaseModel._copy_and_set_values INTERNALERROR> File "/Users/worx/.pyenv/versions/3.9.2/lib/python3.9/copy.py", line 146, in deepcopy INTERNALERROR> y = copier(x, memo) INTERNALERROR> File "/Users/worx/.pyenv/versions/3.9.2/lib/python3.9/copy.py", line 230, in _deepcopy_dict INTERNALERROR> y[deepcopy(key, memo)] = deepcopy(value, memo) INTERNALERROR> File "/Users/worx/.pyenv/versions/3.9.2/lib/python3.9/copy.py", line 151, in deepcopy INTERNALERROR> copier = getattr(x, "__deepcopy__", None) INTERNALERROR> File "/Users/worx/ape/src/ape/api/networks.py", line 183, in __getattr__ INTERNALERROR> return self.get_network(network_name) INTERNALERROR> File "/Users/worx/ape/src/ape/api/networks.py", line 320, in get_network INTERNALERROR> raise NetworkNotFoundError(network_name) INTERNALERROR> ape.exceptions.NetworkNotFoundError: No network named '--deepcopy--'. ``` Pinning to 1.9.0 as current fix. Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.9.1 pydantic compiled: True install path: /Users/worx/.pyenv/versions/3.9.2/envs/ape/lib/python3.9/site-packages/pydantic python version: 3.9.2 (default, Dec 2 2021, 09:57:33) [Clang 13.0.0 (clang-1300.0.29.3)] platform: macOS-12.3.1-arm64-arm-64bit optional deps. installed: ['typing-extensions'] ``` <!-- or if you're using pydantic prior to v1.3, manually include: OS, python version and pydantic version --> <!-- Please read the [docs](https://pydantic-docs.helpmanual.io/) and search through issues to confirm your bug hasn't already been reported. --> <!-- Where possible please include a self-contained code snippet describing your bug: --> ```py import pydantic ... ```
0.0
a5edcb35d57a543143b0dc127dbcf8e143c38e6d
[ "tests/test_main.py::test_model_exclude_copy_on_model_validation", "tests/test_main.py::test_model_exclude_copy_on_model_validation_shallow", "tests/test_main.py::test_copy_on_model_validation_warning[True]", "tests/test_main.py::test_copy_on_model_validation_warning[False]", "tests/test_main.py::test_inherited_model_field_untouched" ]
[ "tests/test_main.py::test_success", "tests/test_main.py::test_ultra_simple_missing", "tests/test_main.py::test_ultra_simple_failed", "tests/test_main.py::test_ultra_simple_repr", "tests/test_main.py::test_default_factory_field", "tests/test_main.py::test_default_factory_no_type_field", "tests/test_main.py::test_comparing", "tests/test_main.py::test_nullable_strings_success", "tests/test_main.py::test_nullable_strings_fails", "tests/test_main.py::test_recursion", "tests/test_main.py::test_recursion_fails", "tests/test_main.py::test_not_required", "tests/test_main.py::test_infer_type", "tests/test_main.py::test_allow_extra", "tests/test_main.py::test_allow_extra_repr", "tests/test_main.py::test_forbidden_extra_success", "tests/test_main.py::test_forbidden_extra_fails", "tests/test_main.py::test_disallow_mutation", "tests/test_main.py::test_extra_allowed", "tests/test_main.py::test_extra_ignored", "tests/test_main.py::test_set_attr", "tests/test_main.py::test_set_attr_invalid", "tests/test_main.py::test_any", "tests/test_main.py::test_alias", "tests/test_main.py::test_population_by_field_name", "tests/test_main.py::test_field_order", "tests/test_main.py::test_required", "tests/test_main.py::test_mutability", "tests/test_main.py::test_immutability[False-False]", "tests/test_main.py::test_immutability[False-True]", "tests/test_main.py::test_immutability[True-True]", "tests/test_main.py::test_not_frozen_are_not_hashable", "tests/test_main.py::test_with_declared_hash", "tests/test_main.py::test_frozen_with_hashable_fields_are_hashable", "tests/test_main.py::test_frozen_with_unhashable_fields_are_not_hashable", "tests/test_main.py::test_hash_function_give_different_result_for_different_object", "tests/test_main.py::test_const_validates", "tests/test_main.py::test_const_uses_default", "tests/test_main.py::test_const_validates_after_type_validators", "tests/test_main.py::test_const_with_wrong_value", "tests/test_main.py::test_const_with_validator", "tests/test_main.py::test_const_list", "tests/test_main.py::test_const_list_with_wrong_value", "tests/test_main.py::test_const_validation_json_serializable", "tests/test_main.py::test_validating_assignment_pass", "tests/test_main.py::test_validating_assignment_fail", "tests/test_main.py::test_validating_assignment_pre_root_validator_fail", "tests/test_main.py::test_validating_assignment_post_root_validator_fail", "tests/test_main.py::test_root_validator_many_values_change", "tests/test_main.py::test_enum_values", "tests/test_main.py::test_literal_enum_values", "tests/test_main.py::test_enum_raw", "tests/test_main.py::test_set_tuple_values", "tests/test_main.py::test_default_copy", "tests/test_main.py::test_arbitrary_type_allowed_validation_success", "tests/test_main.py::test_arbitrary_type_allowed_validation_fails", "tests/test_main.py::test_arbitrary_types_not_allowed", "tests/test_main.py::test_type_type_validation_success", "tests/test_main.py::test_type_type_subclass_validation_success", "tests/test_main.py::test_type_type_validation_fails_for_instance", "tests/test_main.py::test_type_type_validation_fails_for_basic_type", "tests/test_main.py::test_bare_type_type_validation_success", "tests/test_main.py::test_bare_type_type_validation_fails", "tests/test_main.py::test_annotation_field_name_shadows_attribute", "tests/test_main.py::test_value_field_name_shadows_attribute", "tests/test_main.py::test_class_var", "tests/test_main.py::test_fields_set", "tests/test_main.py::test_exclude_unset_dict", "tests/test_main.py::test_exclude_unset_recursive", "tests/test_main.py::test_dict_exclude_unset_populated_by_alias", "tests/test_main.py::test_dict_exclude_unset_populated_by_alias_with_extra", "tests/test_main.py::test_exclude_defaults", "tests/test_main.py::test_dir_fields", "tests/test_main.py::test_dict_with_extra_keys", "tests/test_main.py::test_root", "tests/test_main.py::test_root_list", "tests/test_main.py::test_root_nested", "tests/test_main.py::test_encode_nested_root", "tests/test_main.py::test_root_failed", "tests/test_main.py::test_root_undefined_failed", "tests/test_main.py::test_parse_root_as_mapping", "tests/test_main.py::test_parse_obj_non_mapping_root", "tests/test_main.py::test_parse_obj_nested_root", "tests/test_main.py::test_untouched_types", "tests/test_main.py::test_custom_types_fail_without_keep_untouched", "tests/test_main.py::test_model_iteration", "tests/test_main.py::test_model_export_nested_list[excluding", "tests/test_main.py::test_model_export_nested_list[should", "tests/test_main.py::test_model_export_nested_list[using", "tests/test_main.py::test_model_export_dict_exclusion[excluding", "tests/test_main.py::test_model_export_dict_exclusion[using", "tests/test_main.py::test_model_export_dict_exclusion[exclude", "tests/test_main.py::test_model_exclude_config_field_merging", "tests/test_main.py::test_validation_deep_copy", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[None-expected0-kinds0]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[None-expected0-kinds1]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[None-expected0-kinds2]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[None-expected0-kinds3]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[None-expected0-kinds4]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[None-expected0-kinds5]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[None-expected0-kinds6]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude1-expected1-kinds0]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude1-expected1-kinds1]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude1-expected1-kinds2]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude1-expected1-kinds3]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude1-expected1-kinds4]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude1-expected1-kinds5]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude1-expected1-kinds6]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude2-expected2-kinds0]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude2-expected2-kinds1]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude2-expected2-kinds2]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude2-expected2-kinds3]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude2-expected2-kinds4]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude2-expected2-kinds5]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude2-expected2-kinds6]", "tests/test_main.py::test_model_export_exclusion_inheritance", "tests/test_main.py::test_model_export_with_true_instead_of_ellipsis", "tests/test_main.py::test_model_export_inclusion", "tests/test_main.py::test_model_export_inclusion_inheritance", "tests/test_main.py::test_custom_init_subclass_params", "tests/test_main.py::test_update_forward_refs_does_not_modify_module_dict", "tests/test_main.py::test_two_defaults", "tests/test_main.py::test_default_factory", "tests/test_main.py::test_default_factory_called_once", "tests/test_main.py::test_default_factory_called_once_2", "tests/test_main.py::test_default_factory_validate_children", "tests/test_main.py::test_default_factory_parse", "tests/test_main.py::test_none_min_max_items", "tests/test_main.py::test_reuse_same_field", "tests/test_main.py::test_base_config_type_hinting", "tests/test_main.py::test_allow_mutation_field", "tests/test_main.py::test_repr_field", "tests/test_main.py::test_inherited_model_field_copy", "tests/test_main.py::test_mapping_retains_type_subclass", "tests/test_main.py::test_mapping_retains_type_defaultdict", "tests/test_main.py::test_mapping_retains_type_fallback_error", "tests/test_main.py::test_typing_coercion_dict", "tests/test_main.py::test_typing_non_coercion_of_dict_subclasses", "tests/test_main.py::test_typing_coercion_defaultdict", "tests/test_main.py::test_typing_coercion_counter", "tests/test_main.py::test_typing_counter_value_validation", "tests/test_main.py::test_class_kwargs_config", "tests/test_main.py::test_class_kwargs_config_json_encoders", "tests/test_main.py::test_class_kwargs_config_and_attr_conflict", "tests/test_main.py::test_class_kwargs_custom_config" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2022-05-19 18:29:01+00:00
mit
4,863
pydantic__pydantic-4187
diff --git a/pydantic/utils.py b/pydantic/utils.py --- a/pydantic/utils.py +++ b/pydantic/utils.py @@ -651,9 +651,14 @@ def smart_deepcopy(obj: Obj) -> Obj: obj_type = obj.__class__ if obj_type in IMMUTABLE_NON_COLLECTIONS_TYPES: return obj # fastest case: obj is immutable and not collection therefore will not be copied anyway - elif not obj and obj_type in BUILTIN_COLLECTIONS: - # faster way for empty collections, no need to copy its members - return obj if obj_type is tuple else obj.copy() # type: ignore # tuple doesn't have copy method + try: + if not obj and obj_type in BUILTIN_COLLECTIONS: + # faster way for empty collections, no need to copy its members + return obj if obj_type is tuple else obj.copy() # type: ignore # tuple doesn't have copy method + except (TypeError, ValueError, RuntimeError): + # do we really dare to catch ALL errors? Seems a bit risky + pass + return deepcopy(obj) # slowest way when we actually might need a deepcopy
pydantic/pydantic
8846ec4685e749b93907081450f592060eeb99b1
Off the top of my head, I don't know. That's a config setting called `copy_on_model_validation` try setting it to false and seeing if that avoids a copy that causes the problem. `copy_on_model_validation` didn't change things. I whittled the setup down to the minimum reproducible case: ```py from uuid import UUID, uuid4 import sqlalchemy as sa import sqlalchemy.dialects.postgresql as pg from pydantic import BaseModel as _BaseModel from sqlalchemy.ext.declarative import declarative_base class CommonBase(_BaseModel): id: UUID = sa.Column(pg.UUID(as_uuid=True), primary_key=True, default=uuid4) class Config: copy_on_model_validation = False BaseModel = declarative_base(cls=CommonBase) ``` I also updated to pydantic 1.9.1 without change 🤔 1.9.1 hasn't changed `smart_deepcopy` so that wouldn't make a difference. Really I don't think it's correct for the sqlalchemy type to be raising an error on `__bool__`, but I get why they want to. I think the best solution would be to catch errors like this in `smart_deepcopy` and just fall back to using `deepcopy`, but I wonder whether even deep copy can cope with this type? Something like ```py def smart_deepcopy(obj: Obj) -> Obj: """ Return type as is for immutable built-in types Use obj.copy() for built-in empty collections Use copy.deepcopy() for non-empty collections and unknown objects """ obj_type = obj.__class__ if obj_type in IMMUTABLE_NON_COLLECTIONS_TYPES: return obj # fastest case: obj is immutable and not collection therefore will not be copied anyway try: if not obj and obj_type in BUILTIN_COLLECTIONS: # faster way for empty collections, no need to copy its members return obj if obj_type is tuple else obj.copy() # type: ignore # tuple doesn't have copy method except (TypeError, ValueError, RuntimeError): # do we really dare to catch ALL errors? Seems a bit risky pass return deepcopy(obj) # slowest way when we actually might need a deepcopy ``` What do you think? PR welcome, but I'm not sure when I'll get around to it - I'm currently flat out on pydantic-core getting ready for pydantic v2. But at least your issue has made me think about how we deal with deepcopy in v2 😄 . per their [docs](https://docs.sqlalchemy.org/en/14/changelog/migration_06.html) > Code that wants to check for the presence of a ClauseElement expression should instead say: > `if expression is not None:` > ` print("the expression is:", expression)` So could this perhaps be fixed by changing the smart deep copy line to ```py if obj is None and obj_type in BUILTIN_COLLECTIONS: ``` Does this method expect other `obj` references that are falsy rather than `None`? if so, perhaps this: ```py if (obj is None or not obj) and obj_type in BUILTIN_COLLECTIONS: ``` That doesn't work, `None` is already covered by the `IMMUTABLE_NON_COLLECTIONS_TYPES` check above, and this line is using falsy as a proxy for empty on iterable types, so a `None` check is different. Isn't the immutable collection type check covering `None` on the `obj_type`, not `obj`? Isn't the raise happening on the `not obj` statement where sqlalchemy added the` __bool__` override? I'm not sure what you mean, but neither of your code suggestions will work. Best to try it and see what happens. You were right, my train of thought would have required a quite ugly double negative to work. I was only trying to avoid catching errors, but I suspect your proposed approach is the cleanest and safest. Will submit a pr
diff --git a/tests/test_utils.py b/tests/test_utils.py --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -461,6 +461,17 @@ def test_smart_deepcopy_collection(collection, mocker): assert smart_deepcopy(collection) is expected_value [email protected]('error', [TypeError, ValueError, RuntimeError]) +def test_smart_deepcopy_error(error, mocker): + class RaiseOnBooleanOperation(str): + def __bool__(self): + raise error('raised error') + + obj = RaiseOnBooleanOperation() + expected_value = deepcopy(obj) + assert smart_deepcopy(obj) == expected_value + + T = TypeVar('T')
smart_deepcopy causes sqlalchemy boolean value error on import ### Checks * [X] I added a descriptive title to this issue * [X] I have searched (google, github) for similar issues and couldn't find anything * [X] I have read and followed [the docs](https://pydantic-docs.helpmanual.io/) and still think this is a bug <!-- Sorry to sound so draconian, but every second saved replying to issues is time spend improving pydantic :-) --> # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` root@20116b25f897:/[REDACTED] # python -c "import pydantic.utils; print(pydantic.utils.version_info())" pydantic version: 1.8.2 pydantic compiled: False install path: /usr/local/lib/python3.10/site-packages/pydantic python version: 3.10.5 (main, Jun 7 2022, 18:49:47) [GCC 10.2.1 20210110] platform: Linux-5.10.104-linuxkit-x86_64-with-glibc2.31 optional deps. installed: ['dotenv', 'email-validator', 'typing-extensions'] ``` <!-- or if you're using pydantic prior to v1.3, manually include: OS, python version and pydantic version --> <!-- Please read the [docs](https://pydantic-docs.helpmanual.io/) and search through issues to confirm your bug hasn't already been reported. --> <!-- Where possible please include a self-contained code snippet describing your bug: --> ```py """Base class for all database models.""" from typing import Any, Dict, Optional from uuid import UUID, uuid4 import sqlalchemy as sa import sqlalchemy.dialects.postgresql as pg from inflection import underscore from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import declared_attr from sqlalchemy_utils import Timestamp from pydantic import BaseModel as _BaseModel class CommonBase(_BaseModel, Timestamp): """SQLAlchemy Base common base class for all database models.""" id: UUID = sa.Column(pg.UUID(as_uuid=True), primary_key=True, default=uuid4) @declared_attr def __tablename__(cls) -> Optional[str]: # pylint: disable=no-self-argument """Define table name for all models as the snake case of the model's name.""" return underscore(cls.__name__) def as_dict(self) -> Dict[str, Any]: """Return python dictionary of SQLAlchemy model.""" return self.__dict__ BaseModel = declarative_base(cls=CommonBase) ``` On import of this BaseModel, we are getting a hard to track down error that seems to be related to sqlalchemy boolean expressions, but stemming from the smart_deepcopy line in pydantic and I am not quite sure what the real issue is, and whether it is caused by pydantic, sqlalchemy, or my setup (most likely). The stack trace received on import is: ``` app/models/base_model.py:15: in <module> class CommonBase(_BaseModel, Timestamp): /usr/local/lib/python3.10/site-packages/pydantic/main.py:299: in __new__ fields[ann_name] = ModelField.infer( /usr/local/lib/python3.10/site-packages/pydantic/fields.py:411: in infer return cls( /usr/local/lib/python3.10/site-packages/pydantic/fields.py:342: in __init__ self.prepare() /usr/local/lib/python3.10/site-packages/pydantic/fields.py:445: in prepare self._set_default_and_type() /usr/local/lib/python3.10/site-packages/pydantic/fields.py:473: in _set_default_and_type default_value = self.get_default() /usr/local/lib/python3.10/site-packages/pydantic/fields.py:345: in get_default return smart_deepcopy(self.default) if self.default_factory is None else self.default_factory() /usr/local/lib/python3.10/site-packages/pydantic/utils.py:627: in smart_deepcopy elif not obj and obj_type in BUILTIN_COLLECTIONS: /usr/local/lib/python3.10/site-packages/sqlalchemy/sql/elements.py:582: in __bool__ raise TypeError("Boolean value of this clause is not defined") E TypeError: Boolean value of this clause is not defined ``` I placed a debugger just before the raise and found that: ``` (Pdb) self Column(None, UUID(as_uuid=True), table=None, primary_key=True, nullable=False, default=ColumnDefault(<function uuid4 at 0x7f99d085e200>)) (Pdb) self.__dict__ {'key': None, 'name': None, 'table': None, 'type': UUID(as_uuid=True), 'is_literal': False, 'primary_key': True, '_user_defined_nullable': symbol('NULL_UNSPECIFIED'), 'nullable': False, 'default': ColumnDefault(<function uuid4 at 0x7f99d085e200>), 'server_default': None, 'server_onupdate': None, 'index': None, 'unique': None, 'system': False, 'doc': None, 'onupdate': None, 'autoincrement': 'auto', 'constraints': set(), 'foreign_keys': set(), 'comment': None, 'computed': None, 'identity': None, '_creation_order': 88, 'comparator': <sqlalchemy.sql.type_api.TypeEngine.Comparator object at 0x7f99d07f0a00>, '_memoized_keys': frozenset({'comparator'})} ``` This is not new code in pydantic, and it also seems this check in sqlalchemy was [added almost a decade ago](https://docs.sqlalchemy.org/en/14/changelog/migration_06.html) so I am sure that is must be something wrong with either my expectatins or setup here. While investigating, it seems that this indeed is the correct way to setup a postgres UUID pk column within a pydantic model backed by sqlalchemy, but I am clearly missing something. Thanks for the incredible work you do on this library!
0.0
8846ec4685e749b93907081450f592060eeb99b1
[ "tests/test_utils.py::test_smart_deepcopy_error[TypeError]", "tests/test_utils.py::test_smart_deepcopy_error[ValueError]", "tests/test_utils.py::test_smart_deepcopy_error[RuntimeError]" ]
[ "tests/test_utils.py::test_import_module", "tests/test_utils.py::test_import_module_invalid", "tests/test_utils.py::test_import_no_attr", "tests/test_utils.py::test_display_as_type[str-str]", "tests/test_utils.py::test_display_as_type[string-str]", "tests/test_utils.py::test_display_as_type[value2-Union[str,", "tests/test_utils.py::test_display_as_type[list-list]", "tests/test_utils.py::test_lenient_issubclass", "tests/test_utils.py::test_lenient_issubclass_is_lenient", "tests/test_utils.py::test_truncate[object-<class", "tests/test_utils.py::test_truncate[abcdefghijklmnopqrstuvwxyz-'abcdefghijklmnopq\\u2026']", "tests/test_utils.py::test_truncate[input_value2-[0,", "tests/test_utils.py::test_unique_list[input_value0-output0]", "tests/test_utils.py::test_unique_list[input_value1-output1]", "tests/test_utils.py::test_unique_list[input_value2-output2]", "tests/test_utils.py::test_value_items", "tests/test_utils.py::test_value_items_merge[base0-override0-False-expected0]", "tests/test_utils.py::test_value_items_merge[None-None-False-None]", "tests/test_utils.py::test_value_items_merge[base2-override2-False-expected2]", "tests/test_utils.py::test_value_items_merge[base3-None-False-expected3]", "tests/test_utils.py::test_value_items_merge[None-override4-False-expected4]", "tests/test_utils.py::test_value_items_merge[None-override5-False-expected5]", "tests/test_utils.py::test_value_items_merge[base6-None-False-expected6]", "tests/test_utils.py::test_value_items_merge[base7-override7-False-expected7]", "tests/test_utils.py::test_value_items_merge[base8-override8-False-expected8]", "tests/test_utils.py::test_value_items_merge[base9-override9-False-expected9]", "tests/test_utils.py::test_value_items_merge[base10-override10-False-expected10]", "tests/test_utils.py::test_value_items_merge[base11-override11-False-expected11]", "tests/test_utils.py::test_value_items_merge[base12-override12-False-expected12]", "tests/test_utils.py::test_value_items_merge[base13-override13-False-expected13]", "tests/test_utils.py::test_value_items_merge[base14-override14-False-expected14]", "tests/test_utils.py::test_value_items_merge[base15-override15-False-expected15]", "tests/test_utils.py::test_value_items_merge[base16-override16-True-expected16]", "tests/test_utils.py::test_value_items_merge[None-None-True-None]", "tests/test_utils.py::test_value_items_merge[base18-override18-True-expected18]", "tests/test_utils.py::test_value_items_merge[base19-None-True-expected19]", "tests/test_utils.py::test_value_items_merge[None-override20-True-expected20]", "tests/test_utils.py::test_value_items_merge[None-override21-True-expected21]", "tests/test_utils.py::test_value_items_merge[base22-None-True-expected22]", "tests/test_utils.py::test_value_items_merge[base23-override23-True-expected23]", "tests/test_utils.py::test_value_items_merge[base24-override24-True-expected24]", "tests/test_utils.py::test_value_items_merge[base25-override25-True-expected25]", "tests/test_utils.py::test_value_items_merge[base26-override26-True-expected26]", "tests/test_utils.py::test_value_items_merge[base27-override27-True-expected27]", "tests/test_utils.py::test_value_items_merge[base28-override28-True-expected28]", "tests/test_utils.py::test_value_items_merge[base29-override29-True-expected29]", "tests/test_utils.py::test_value_items_merge[base30-override30-True-expected30]", "tests/test_utils.py::test_value_items_merge[base31-override31-True-expected31]", "tests/test_utils.py::test_value_items_merge[base32-True-False-True]", "tests/test_utils.py::test_value_items_merge[True-override33-False-expected33]", "tests/test_utils.py::test_value_items_merge[True-None-False-True]", "tests/test_utils.py::test_value_items_merge[base35-override35-False-expected35]", "tests/test_utils.py::test_value_items_error", "tests/test_utils.py::test_is_new_type", "tests/test_utils.py::test_new_type_supertype", "tests/test_utils.py::test_pretty", "tests/test_utils.py::test_pretty_color", "tests/test_utils.py::test_devtools_output", "tests/test_utils.py::test_devtools_output_validation_error", "tests/test_utils.py::test_deep_update[mapping0-updating_mapping0-expected_mapping0-extra", "tests/test_utils.py::test_deep_update[mapping1-updating_mapping1-expected_mapping1-values", "tests/test_utils.py::test_deep_update[mapping2-updating_mapping2-expected_mapping2-values", "tests/test_utils.py::test_deep_update[mapping3-updating_mapping3-expected_mapping3-deeply", "tests/test_utils.py::test_deep_update_is_not_mutating", "tests/test_utils.py::test_undefined_repr", "tests/test_utils.py::test_undefined_copy", "tests/test_utils.py::test_get_model", "tests/test_utils.py::test_version_info", "tests/test_utils.py::test_standard_version", "tests/test_utils.py::test_class_attribute", "tests/test_utils.py::test_all_literal_values", "tests/test_utils.py::test_path_type", "tests/test_utils.py::test_path_type_unknown", "tests/test_utils.py::test_smart_deepcopy_immutable_non_sequence[10]", "tests/test_utils.py::test_smart_deepcopy_immutable_non_sequence[1.0]", "tests/test_utils.py::test_smart_deepcopy_immutable_non_sequence[11]", "tests/test_utils.py::test_smart_deepcopy_immutable_non_sequence[12]", "tests/test_utils.py::test_smart_deepcopy_immutable_non_sequence[int]", "tests/test_utils.py::test_smart_deepcopy_immutable_non_sequence[None]", "tests/test_utils.py::test_smart_deepcopy_immutable_non_sequence[test_all_literal_values]", "tests/test_utils.py::test_smart_deepcopy_immutable_non_sequence[len]", "tests/test_utils.py::test_smart_deepcopy_immutable_non_sequence[obj8]", "tests/test_utils.py::test_smart_deepcopy_immutable_non_sequence[<lambda>]", "tests/test_utils.py::test_smart_deepcopy_immutable_non_sequence[obj10]", "tests/test_utils.py::test_smart_deepcopy_empty_collection[empty_collection0]", "tests/test_utils.py::test_smart_deepcopy_empty_collection[empty_collection1]", "tests/test_utils.py::test_smart_deepcopy_empty_collection[empty_collection2]", "tests/test_utils.py::test_smart_deepcopy_empty_collection[empty_collection3]", "tests/test_utils.py::test_smart_deepcopy_empty_collection[empty_collection4]", "tests/test_utils.py::test_smart_deepcopy_empty_collection[empty_collection5]", "tests/test_utils.py::test_smart_deepcopy_empty_collection[empty_collection6]", "tests/test_utils.py::test_smart_deepcopy_empty_collection[empty_collection7]", "tests/test_utils.py::test_smart_deepcopy_collection[collection0]", "tests/test_utils.py::test_smart_deepcopy_collection[collection1]", "tests/test_utils.py::test_smart_deepcopy_collection[collection2]", "tests/test_utils.py::test_smart_deepcopy_collection[collection3]", "tests/test_utils.py::test_smart_deepcopy_collection[collection4]", "tests/test_utils.py::test_smart_deepcopy_collection[collection5]", "tests/test_utils.py::test_smart_deepcopy_collection[collection6]", "tests/test_utils.py::test_smart_deepcopy_collection[collection7]", "tests/test_utils.py::test_get_origin[input_value0-Annotated]", "tests/test_utils.py::test_get_origin[input_value1-Callable]", "tests/test_utils.py::test_get_origin[input_value2-dict]", "tests/test_utils.py::test_get_origin[input_value3-list]", "tests/test_utils.py::test_get_origin[input_value4-output_value4]", "tests/test_utils.py::test_get_origin[int-None]", "tests/test_utils.py::test_resolve_annotations_no_module", "tests/test_utils.py::test_all_identical", "tests/test_utils.py::test_undefined_pickle", "tests/test_utils.py::test_limited_dict" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2022-06-27 13:47:37+00:00
mit
4,864
pydantic__pydantic-4191
diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -596,7 +596,9 @@ def construct(cls: Type['Model'], _fields_set: Optional['SetStr'] = None, **valu m = cls.__new__(cls) fields_values: Dict[str, Any] = {} for name, field in cls.__fields__.items(): - if name in values: + if field.alt_alias and field.alias in values: + fields_values[name] = values[field.alias] + elif name in values: fields_values[name] = values[name] elif not field.required: fields_values[name] = field.get_default()
pydantic/pydantic
f6c74a55d5b272add88d4cbe2efa46c4abc1760f
diff --git a/tests/test_aliases.py b/tests/test_aliases.py --- a/tests/test_aliases.py +++ b/tests/test_aliases.py @@ -1,5 +1,6 @@ import re -from typing import Any, List, Optional +from contextlib import nullcontext as does_not_raise +from typing import Any, ContextManager, List, Optional import pytest @@ -345,3 +346,39 @@ class Model(BaseModel): m = Model(**data) assert m.empty_string_key == 123 assert m.dict(by_alias=True) == data + + [email protected]( + 'use_construct, allow_population_by_field_name_config, arg_name, expectation', + [ + [False, True, 'bar', does_not_raise()], + [False, True, 'bar_', does_not_raise()], + [False, False, 'bar', does_not_raise()], + [False, False, 'bar_', pytest.raises(ValueError)], + [True, True, 'bar', does_not_raise()], + [True, True, 'bar_', does_not_raise()], + [True, False, 'bar', does_not_raise()], + [True, False, 'bar_', does_not_raise()], + ], +) +def test_allow_population_by_field_name_config( + use_construct: bool, + allow_population_by_field_name_config: bool, + arg_name: str, + expectation: ContextManager, +): + expected_value: int = 7 + + class Foo(BaseModel): + bar_: int = Field(..., alias='bar') + + class Config(BaseConfig): + allow_population_by_field_name = allow_population_by_field_name_config + + with expectation: + if use_construct: + f = Foo.construct(**{arg_name: expected_value}) + else: + f = Foo(**{arg_name: expected_value}) + + assert f.bar_ == expected_value
BaseModel.construct does not set aliased fields consistently with standard instantiation ### Checks * [x] I added a descriptive title to this issue * [x] I have searched (google, github) for similar issues and couldn't find anything * [x] I have read and followed [the docs](https://pydantic-docs.helpmanual.io/) and still think this is a bug <!-- Sorry to sound so draconian, but every second saved replying to issues is time spend improving pydantic :-) --> # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.8.2 pydantic compiled: False install path: /Users/kyleamos/Library/Caches/pypoetry/virtualenvs/api-KwVDv1SR-py3.9/lib/python3.9/site-packages/pydantic python version: 3.9.1 (default, Jan 18 2022, 12:54:24) [Clang 13.0.0 (clang-1300.0.29.30)] platform: macOS-12.1-arm64-arm-64bit optional deps. installed: ['email-validator', 'typing-extensions'] ``` <!-- or if you're using pydantic prior to v1.3, manually include: OS, python version and pydantic version --> <!-- Please read the [docs](https://pydantic-docs.helpmanual.io/) and search through issues to confirm your bug hasn't already been reported. --> <!-- Where possible please include a self-contained code snippet describing your bug: --> ```py from pydantic import BaseConfig, BaseModel, Field class Foo(BaseModel): class Config(BaseConfig): allow_population_by_field_name = True bar_: int = Field(..., alias="bar") expected_value = 2 assert Foo(bar=expected_value).bar_ == expected_value assert Foo.construct(bar=expected_value).bar_ == expected_value # AttributeError: 'Foo' object has no attribute 'bar_' ... ```
0.0
f6c74a55d5b272add88d4cbe2efa46c4abc1760f
[ "tests/test_aliases.py::test_allow_population_by_field_name_config[True-True-bar-expectation4]", "tests/test_aliases.py::test_allow_population_by_field_name_config[True-False-bar-expectation6]" ]
[ "tests/test_aliases.py::test_alias_generator", "tests/test_aliases.py::test_alias_generator_with_field_schema", "tests/test_aliases.py::test_alias_generator_wrong_type_error", "tests/test_aliases.py::test_infer_alias", "tests/test_aliases.py::test_alias_error", "tests/test_aliases.py::test_annotation_config", "tests/test_aliases.py::test_alias_camel_case", "tests/test_aliases.py::test_get_field_info_inherit", "tests/test_aliases.py::test_pop_by_field_name", "tests/test_aliases.py::test_alias_child_precedence", "tests/test_aliases.py::test_alias_generator_parent", "tests/test_aliases.py::test_alias_generator_on_parent", "tests/test_aliases.py::test_alias_generator_on_child", "tests/test_aliases.py::test_low_priority_alias", "tests/test_aliases.py::test_low_priority_alias_config", "tests/test_aliases.py::test_field_vs_config", "tests/test_aliases.py::test_alias_priority", "tests/test_aliases.py::test_empty_string_alias", "tests/test_aliases.py::test_allow_population_by_field_name_config[False-True-bar-expectation0]", "tests/test_aliases.py::test_allow_population_by_field_name_config[False-True-bar_-expectation1]", "tests/test_aliases.py::test_allow_population_by_field_name_config[False-False-bar-expectation2]", "tests/test_aliases.py::test_allow_population_by_field_name_config[False-False-bar_-expectation3]", "tests/test_aliases.py::test_allow_population_by_field_name_config[True-True-bar_-expectation5]", "tests/test_aliases.py::test_allow_population_by_field_name_config[True-False-bar_-expectation7]" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2022-06-28 21:01:03+00:00
mit
4,865
pydantic__pydantic-4224
diff --git a/docs/examples/types_url_building.py b/docs/examples/types_url_building.py new file mode 100644 --- /dev/null +++ b/docs/examples/types_url_building.py @@ -0,0 +1,10 @@ +from pydantic import AnyUrl, stricturl + +url = AnyUrl.build(scheme='https', host='example.com', query='query=my query') +print(url) + +my_url_builder = stricturl(quote_plus=True) +url = my_url_builder.build( + scheme='http', host='example.com', query='query=my query' +) +print(url) diff --git a/pydantic/networks.py b/pydantic/networks.py --- a/pydantic/networks.py +++ b/pydantic/networks.py @@ -26,6 +26,7 @@ cast, no_type_check, ) +from urllib.parse import quote, quote_plus from . import errors from .utils import Representation, update_not_none @@ -177,6 +178,7 @@ class AnyUrl(str): user_required: bool = False host_required: bool = True hidden_parts: Set[str] = set() + quote_plus: bool = False __slots__ = ('scheme', 'user', 'password', 'host', 'tld', 'host_type', 'port', 'path', 'query', 'fragment') @@ -239,18 +241,19 @@ def build( url = scheme + '://' if user: - url += user + url += cls.quote(user) if password: - url += ':' + password + url += ':' + cls.quote(password) if user or password: url += '@' url += host if port and ('port' not in cls.hidden_parts or cls.get_default_parts(parts).get('port') != port): url += ':' + port if path: - url += path + url += '/'.join(map(cls.quote, path.split('/'))) if query: - url += '?' + query + queries = query.split('&') + url += '?' + '&'.join(map(lambda s: '='.join(map(cls.quote, s.split('='))), queries)) if fragment: url += '#' + fragment return url @@ -391,6 +394,10 @@ def apply_default_parts(cls, parts: 'Parts') -> 'Parts': parts[key] = value # type: ignore[literal-required] return parts + @classmethod + def quote(cls, string: str, safe: str = '') -> str: + return quote_plus(string, safe) if cls.quote_plus else quote(string, safe) + def __repr__(self) -> str: extra = ', '.join(f'{n}={getattr(self, n)!r}' for n in self.__slots__ if getattr(self, n) is not None) return f'{self.__class__.__name__}({super().__repr__()}, {extra})' @@ -558,6 +565,7 @@ def stricturl( tld_required: bool = True, host_required: bool = True, allowed_schemes: Optional[Collection[str]] = None, + quote_plus: bool = False, ) -> Type[AnyUrl]: # use kwargs then define conf in a dict to aid with IDE type hinting namespace = dict( @@ -567,6 +575,7 @@ def stricturl( tld_required=tld_required, host_required=host_required, allowed_schemes=allowed_schemes, + quote_plus=quote_plus, ) return type('UrlValue', (AnyUrl,), namespace)
pydantic/pydantic
899b5f066124d8f49c5e4363c6deab5904446031
Should this also include the option for `quote_plus` in case it's needed for compatibility reasons? Hi @kkirsche! Sorry I'm not following, what are the compatibility reasons? Not all APIs, in my experience at least, support percent-encoded spaces (`%20` instead of ` `). Some, but not all, only accept plus-variants (`+` instead of ` `) of the space encodings, requiring the use of `quote_plus` instead of `quote`. Yeah sure I think this should be included.
diff --git a/tests/test_networks.py b/tests/test_networks.py --- a/tests/test_networks.py +++ b/tests/test_networks.py @@ -372,7 +372,7 @@ class Model(BaseModel): @pytest.mark.parametrize( 'value', - ['file:///foo/bar', 'file://localhost/foo/bar' 'file:////localhost/foo/bar'], + ['file:///foo/bar', 'file://localhost/foo/bar', 'file:////localhost/foo/bar'], ) def test_file_url_success(value): class Model(BaseModel): @@ -679,12 +679,31 @@ class Model2(BaseModel): (dict(scheme='ws', user='foo', password='x', host='example.net'), 'ws://foo:[email protected]'), (dict(scheme='ws', host='example.net', query='a=b', fragment='c=d'), 'ws://example.net?a=b#c=d'), (dict(scheme='http', host='example.net', port='1234'), 'http://example.net:1234'), + (dict(scheme='http', user='foo@bar', host='example.net'), 'http://foo%[email protected]'), + (dict(scheme='http', user='foo', password='a b', host='example.net'), 'http://foo:a%[email protected]'), + (dict(scheme='http', host='example.net', query='q=foo bar'), 'http://example.net?q=foo%20bar'), + (dict(scheme='http', host='example.net', path="/m&m's"), 'http://example.net/m%26m%27s'), ], ) def test_build_url(kwargs, expected): assert AnyUrl(None, **kwargs) == expected [email protected]( + 'kwargs,expected', + [ + (dict(scheme='https', host='example.com', query='query=my query'), 'https://example.com?query=my+query'), + ( + dict(scheme='https', host='example.com', user='my name', password='a password'), + 'https://my+name:[email protected]', + ), + (dict(scheme='https', host='example.com', path='/this is a path'), 'https://example.com/this+is+a+path'), + ], +) +def test_build_url_quote_plus(kwargs, expected): + assert stricturl(quote_plus=True).build(**kwargs) == expected + + @pytest.mark.parametrize( 'kwargs,expected', [
*Url.build functions doesn't percent-encode arguments ### Checks * [x] I added a descriptive title to this issue * [x] I have searched (google, github) for similar issues and couldn't find anything * [x] I have read and followed [the docs](https://pydantic-docs.helpmanual.io/) and still think this is a bug # Bug Using (AnyUrl, HttpUrl, AnyHttpUrl) build functions results an unusable URL if characters like: `:`, `/`, `?`, `#`, `[`, ` `, `]`, `@` exists in the following arguments: `user`, `password`, `path`, `query`, `fragment`. In other words these arguments should be [Percent-Encoded](https://tools.ietf.org/html/rfc3986#section-2.1) to work properly and not produce a Url that have characters that conflicts with the [url-spec](https://www.w3.org/Addressing/URL/url-spec.txt). Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.8.2 pydantic compiled: True install path: /.../.venv/lib/python3.9/site-packages/pydantic python version: 3.9.6 (default, Jul 3 2021, 17:50:42) [GCC 7.5.0] platform: Linux-5.4.0-80-generic-x86_64-with-glibc2.27 optional deps. installed: ['dotenv', 'email-validator', 'typing-extensions'] ``` # Example ```py >>> from pydantic import AnyUrl, HttpUrl, AnyHttpUrl >>> >>> AnyUrl.build( ... scheme="ws", ... user="@AwesomeUser", ... password="Pa##w0rd?:/", ... host="localhost", ... port="5000" ...) 'ws://@AwesomeUser:Pa##w0rd?:/@localhost:5000' >>> # ... >>> # The same result with `HttpUrl`, `AnyHttpUrl` ``` The easiest way to percent-encode in Python is to use the `urllib.parse.quote` function
0.0
899b5f066124d8f49c5e4363c6deab5904446031
[ "tests/test_networks.py::test_build_url[kwargs4-http://foo%[email protected]]", "tests/test_networks.py::test_build_url[kwargs5-http://foo:a%[email protected]]", "tests/test_networks.py::test_build_url[kwargs6-http://example.net?q=foo%20bar]", "tests/test_networks.py::test_build_url[kwargs7-http://example.net/m%26m%27s]", "tests/test_networks.py::test_build_url_quote_plus[kwargs0-https://example.com?query=my+query]", "tests/test_networks.py::test_build_url_quote_plus[kwargs1-https://my+name:[email protected]]", "tests/test_networks.py::test_build_url_quote_plus[kwargs2-https://example.com/this+is+a+path]" ]
[ "tests/test_networks.py::test_any_url_success[http://example.org]", "tests/test_networks.py::test_any_url_success[http://test]", "tests/test_networks.py::test_any_url_success[http://localhost0]", "tests/test_networks.py::test_any_url_success[https://example.org/whatever/next/]", "tests/test_networks.py::test_any_url_success[postgres://user:pass@localhost:5432/app]", "tests/test_networks.py::test_any_url_success[postgres://just-user@localhost:5432/app]", "tests/test_networks.py::test_any_url_success[postgresql+asyncpg://user:pass@localhost:5432/app]", "tests/test_networks.py::test_any_url_success[postgresql+pg8000://user:pass@localhost:5432/app]", "tests/test_networks.py::test_any_url_success[postgresql+psycopg2://postgres:postgres@localhost:5432/hatch]", "tests/test_networks.py::test_any_url_success[postgresql+psycopg2cffi://user:pass@localhost:5432/app]", "tests/test_networks.py::test_any_url_success[postgresql+py-postgresql://user:pass@localhost:5432/app]", "tests/test_networks.py::test_any_url_success[postgresql+pygresql://user:pass@localhost:5432/app]", "tests/test_networks.py::test_any_url_success[foo-bar://example.org]", "tests/test_networks.py::test_any_url_success[foo.bar://example.org]", "tests/test_networks.py::test_any_url_success[foo0bar://example.org]", "tests/test_networks.py::test_any_url_success[https://example.org]", "tests/test_networks.py::test_any_url_success[http://localhost1]", "tests/test_networks.py::test_any_url_success[http://localhost/]", "tests/test_networks.py::test_any_url_success[http://localhost:8000]", "tests/test_networks.py::test_any_url_success[http://localhost:8000/]", "tests/test_networks.py::test_any_url_success[https://foo_bar.example.com/]", "tests/test_networks.py::test_any_url_success[ftp://example.org]", "tests/test_networks.py::test_any_url_success[ftps://example.org]", "tests/test_networks.py::test_any_url_success[http://example.co.jp]", "tests/test_networks.py::test_any_url_success[http://www.example.com/a%C2%B1b]", "tests/test_networks.py::test_any_url_success[http://www.example.com/~username/]", "tests/test_networks.py::test_any_url_success[http://info.example.com?fred]", "tests/test_networks.py::test_any_url_success[http://info.example.com/?fred]", "tests/test_networks.py::test_any_url_success[http://xn--mgbh0fb.xn--kgbechtv/]", "tests/test_networks.py::test_any_url_success[http://example.com/blue/red%3Fand+green]", "tests/test_networks.py::test_any_url_success[http://www.example.com/?array%5Bkey%5D=value]", "tests/test_networks.py::test_any_url_success[http://xn--rsum-bpad.example.org/]", "tests/test_networks.py::test_any_url_success[http://123.45.67.8/]", "tests/test_networks.py::test_any_url_success[http://123.45.67.8:8329/]", "tests/test_networks.py::test_any_url_success[http://[2001:db8::ff00:42]:8329]", "tests/test_networks.py::test_any_url_success[http://[2001::1]:8329]", "tests/test_networks.py::test_any_url_success[http://[2001:db8::1]/]", "tests/test_networks.py::test_any_url_success[http://www.example.com:8000/foo]", "tests/test_networks.py::test_any_url_success[http://www.cwi.nl:80/%7Eguido/Python.html]", "tests/test_networks.py::test_any_url_success[https://www.python.org/\\u043f\\u0443\\u0442\\u044c]", "tests/test_networks.py::test_any_url_success[http://\\u0430\\u043d\\u0434\\u0440\\u0435\\[email protected]]", "tests/test_networks.py::test_any_url_success[https://example.com]", "tests/test_networks.py::test_any_url_success[https://exam_ple.com/]", "tests/test_networks.py::test_any_url_success[http://twitter.com/@handle/]", "tests/test_networks.py::test_any_url_success[http://11.11.11.11.example.com/action]", "tests/test_networks.py::test_any_url_success[http://abc.11.11.11.11.example.com/action]", "tests/test_networks.py::test_any_url_success[http://example#]", "tests/test_networks.py::test_any_url_success[http://example/#]", "tests/test_networks.py::test_any_url_success[http://example/#fragment]", "tests/test_networks.py::test_any_url_success[http://example/?#]", "tests/test_networks.py::test_any_url_success[http://example.org/path#]", "tests/test_networks.py::test_any_url_success[http://example.org/path#fragment]", "tests/test_networks.py::test_any_url_success[http://example.org/path?query#]", "tests/test_networks.py::test_any_url_success[http://example.org/path?query#fragment]", "tests/test_networks.py::test_any_url_success[file://localhost/foo/bar]", "tests/test_networks.py::test_any_url_invalid[http:///example.com/-value_error.url.host-URL", "tests/test_networks.py::test_any_url_invalid[https:///example.com/-value_error.url.host-URL", "tests/test_networks.py::test_any_url_invalid[http://.example.com:8000/foo-value_error.url.host-URL", "tests/test_networks.py::test_any_url_invalid[https://example.org\\\\-value_error.url.host-URL", "tests/test_networks.py::test_any_url_invalid[https://exampl$e.org-value_error.url.host-URL", "tests/test_networks.py::test_any_url_invalid[http://??-value_error.url.host-URL", "tests/test_networks.py::test_any_url_invalid[http://.-value_error.url.host-URL", "tests/test_networks.py::test_any_url_invalid[http://..-value_error.url.host-URL", "tests/test_networks.py::test_any_url_invalid[https://example.org", "tests/test_networks.py::test_any_url_invalid[$https://example.org-value_error.url.scheme-invalid", "tests/test_networks.py::test_any_url_invalid[../icons/logo.gif-value_error.url.scheme-invalid", "tests/test_networks.py::test_any_url_invalid[abc-value_error.url.scheme-invalid", "tests/test_networks.py::test_any_url_invalid[..-value_error.url.scheme-invalid", "tests/test_networks.py::test_any_url_invalid[/-value_error.url.scheme-invalid", "tests/test_networks.py::test_any_url_invalid[+http://example.com/-value_error.url.scheme-invalid", "tests/test_networks.py::test_any_url_invalid[ht*tp://example.com/-value_error.url.scheme-invalid", "tests/test_networks.py::test_any_url_invalid[", "tests/test_networks.py::test_any_url_invalid[-value_error.any_str.min_length-ensure", "tests/test_networks.py::test_any_url_invalid[None-type_error.none.not_allowed-none", "tests/test_networks.py::test_any_url_invalid[http://2001:db8::ff00:42:8329-value_error.url.extra-URL", "tests/test_networks.py::test_any_url_invalid[http://[192.168.1.1]:8329-value_error.url.host-URL", "tests/test_networks.py::test_any_url_invalid[http://example.com:99999-value_error.url.port-URL", "tests/test_networks.py::test_any_url_invalid[http://example##-value_error.url.extra-URL", "tests/test_networks.py::test_any_url_invalid[http://example/##-value_error.url.extra-URL", "tests/test_networks.py::test_any_url_invalid[file:///foo/bar-value_error.url.host-URL", "tests/test_networks.py::test_any_url_parts", "tests/test_networks.py::test_url_repr", "tests/test_networks.py::test_ipv4_port", "tests/test_networks.py::test_ipv4_no_port", "tests/test_networks.py::test_ipv6_port", "tests/test_networks.py::test_int_domain", "tests/test_networks.py::test_co_uk", "tests/test_networks.py::test_user_no_password", "tests/test_networks.py::test_user_info_no_user", "tests/test_networks.py::test_at_in_path", "tests/test_networks.py::test_fragment_without_query", "tests/test_networks.py::test_http_url_success[http://example.org]", "tests/test_networks.py::test_http_url_success[http://example.org/foobar]", "tests/test_networks.py::test_http_url_success[http://example.org.]", "tests/test_networks.py::test_http_url_success[http://example.org./foobar]", "tests/test_networks.py::test_http_url_success[HTTP://EXAMPLE.ORG]", "tests/test_networks.py::test_http_url_success[https://example.org]", "tests/test_networks.py::test_http_url_success[https://example.org?a=1&b=2]", "tests/test_networks.py::test_http_url_success[https://example.org#a=3;b=3]", "tests/test_networks.py::test_http_url_success[https://foo_bar.example.com/]", "tests/test_networks.py::test_http_url_success[https://exam_ple.com/]", "tests/test_networks.py::test_http_url_success[https://example.xn--p1ai]", "tests/test_networks.py::test_http_url_success[https://example.xn--vermgensberatung-pwb]", "tests/test_networks.py::test_http_url_success[https://example.xn--zfr164b]", "tests/test_networks.py::test_http_url_invalid[ftp://example.com/-value_error.url.scheme-URL", "tests/test_networks.py::test_http_url_invalid[http://foobar/-value_error.url.host-URL", "tests/test_networks.py::test_http_url_invalid[http://localhost/-value_error.url.host-URL", "tests/test_networks.py::test_http_url_invalid[https://example.123-value_error.url.host-URL", "tests/test_networks.py::test_http_url_invalid[https://example.ab123-value_error.url.host-URL", "tests/test_networks.py::test_http_url_invalid[xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-value_error.any_str.max_length-ensure", "tests/test_networks.py::test_coerse_url[", "tests/test_networks.py::test_coerse_url[https://www.example.com-https://www.example.com]", "tests/test_networks.py::test_coerse_url[https://www.\\u0430\\u0440\\u0440\\u04cf\\u0435.com/-https://www.xn--80ak6aa92e.com/]", "tests/test_networks.py::test_coerse_url[https://exampl\\xa3e.org-https://xn--example-gia.org]", "tests/test_networks.py::test_coerse_url[https://example.\\u73e0\\u5b9d-https://example.xn--pbt977c]", "tests/test_networks.py::test_coerse_url[https://example.verm\\xf6gensberatung-https://example.xn--vermgensberatung-pwb]", "tests/test_networks.py::test_coerse_url[https://example.\\u0440\\u0444-https://example.xn--p1ai]", "tests/test_networks.py::test_coerse_url[https://exampl\\xa3e.\\u73e0\\u5b9d-https://xn--example-gia.xn--pbt977c]", "tests/test_networks.py::test_parses_tld[", "tests/test_networks.py::test_parses_tld[https://www.example.com-com]", "tests/test_networks.py::test_parses_tld[https://www.example.com?param=value-com]", "tests/test_networks.py::test_parses_tld[https://example.\\u73e0\\u5b9d-xn--pbt977c]", "tests/test_networks.py::test_parses_tld[https://exampl\\xa3e.\\u73e0\\u5b9d-xn--pbt977c]", "tests/test_networks.py::test_parses_tld[https://example.verm\\xf6gensberatung-xn--vermgensberatung-pwb]", "tests/test_networks.py::test_parses_tld[https://example.\\u0440\\u0444-xn--p1ai]", "tests/test_networks.py::test_parses_tld[https://example.\\u0440\\u0444?param=value-xn--p1ai]", "tests/test_networks.py::test_file_url_success[file:///foo/bar]", "tests/test_networks.py::test_file_url_success[file://localhost/foo/bar]", "tests/test_networks.py::test_file_url_success[file:////localhost/foo/bar]", "tests/test_networks.py::test_get_default_parts", "tests/test_networks.py::test_http_urls_default_port[https://www.example.com-443]", "tests/test_networks.py::test_http_urls_default_port[https://www.example.com:443-443]", "tests/test_networks.py::test_http_urls_default_port[https://www.example.com:8089-8089]", "tests/test_networks.py::test_http_urls_default_port[http://www.example.com-80]", "tests/test_networks.py::test_http_urls_default_port[http://www.example.com:80-80]", "tests/test_networks.py::test_http_urls_default_port[http://www.example.com:8080-8080]", "tests/test_networks.py::test_postgres_dsns[postgres://user:pass@localhost:5432/app]", "tests/test_networks.py::test_postgres_dsns[postgresql://user:pass@localhost:5432/app]", "tests/test_networks.py::test_postgres_dsns[postgresql+asyncpg://user:pass@localhost:5432/app]", "tests/test_networks.py::test_postgres_dsns[postgres://user:[email protected],host2.db.net:6432/app]", "tests/test_networks.py::test_postgres_dsns_validation_error[postgres://user:[email protected]:4321,/foo/bar:5432/app-error_message0]", "tests/test_networks.py::test_postgres_dsns_validation_error[postgres://user:[email protected],/app-error_message1]", "tests/test_networks.py::test_postgres_dsns_validation_error[postgres://user:pass@/foo/bar:5432,host1.db.net:4321/app-error_message2]", "tests/test_networks.py::test_postgres_dsns_validation_error[postgres://localhost:5432/app-error_message3]", "tests/test_networks.py::test_postgres_dsns_validation_error[postgres://user@/foo/bar:5432/app-error_message4]", "tests/test_networks.py::test_postgres_dsns_validation_error[http://example.org-error_message5]", "tests/test_networks.py::test_multihost_postgres_dsns", "tests/test_networks.py::test_cockroach_dsns", "tests/test_networks.py::test_amqp_dsns", "tests/test_networks.py::test_redis_dsns", "tests/test_networks.py::test_mongodb_dsns", "tests/test_networks.py::test_kafka_dsns", "tests/test_networks.py::test_custom_schemes", "tests/test_networks.py::test_build_url[kwargs0-ws://[email protected]]", "tests/test_networks.py::test_build_url[kwargs1-ws://foo:[email protected]]", "tests/test_networks.py::test_build_url[kwargs2-ws://example.net?a=b#c=d]", "tests/test_networks.py::test_build_url[kwargs3-http://example.net:1234]", "tests/test_networks.py::test_build_any_http_url[AnyHttpUrl-kwargs0-http://example.net]", "tests/test_networks.py::test_build_any_http_url[AnyHttpUrl-kwargs1-https://example.net]", "tests/test_networks.py::test_build_any_http_url[AnyHttpUrl-kwargs2-http://[email protected]]", "tests/test_networks.py::test_build_any_http_url[AnyHttpUrl-kwargs3-https://[email protected]]", "tests/test_networks.py::test_build_any_http_url[AnyHttpUrl-kwargs4-http://[email protected]:123]", "tests/test_networks.py::test_build_any_http_url[AnyHttpUrl-kwargs5-https://[email protected]:123]", "tests/test_networks.py::test_build_any_http_url[AnyHttpUrl-kwargs6-http://foo:[email protected]]", "tests/test_networks.py::test_build_any_http_url[AnyHttpUrl-kwargs7-http2://foo:[email protected]]", "tests/test_networks.py::test_build_any_http_url[AnyHttpUrl-kwargs8-http://example.net?a=b#c=d]", "tests/test_networks.py::test_build_any_http_url[AnyHttpUrl-kwargs9-http2://example.net?a=b#c=d]", "tests/test_networks.py::test_build_any_http_url[AnyHttpUrl-kwargs10-http://example.net:1234]", "tests/test_networks.py::test_build_any_http_url[AnyHttpUrl-kwargs11-https://example.net:1234]", "tests/test_networks.py::test_build_any_http_url[HttpUrl-kwargs0-http://example.net]", "tests/test_networks.py::test_build_any_http_url[HttpUrl-kwargs1-https://example.net]", "tests/test_networks.py::test_build_any_http_url[HttpUrl-kwargs2-http://[email protected]]", "tests/test_networks.py::test_build_any_http_url[HttpUrl-kwargs3-https://[email protected]]", "tests/test_networks.py::test_build_any_http_url[HttpUrl-kwargs4-http://[email protected]:123]", "tests/test_networks.py::test_build_any_http_url[HttpUrl-kwargs5-https://[email protected]:123]", "tests/test_networks.py::test_build_any_http_url[HttpUrl-kwargs6-http://foo:[email protected]]", "tests/test_networks.py::test_build_any_http_url[HttpUrl-kwargs7-http2://foo:[email protected]]", "tests/test_networks.py::test_build_any_http_url[HttpUrl-kwargs8-http://example.net?a=b#c=d]", "tests/test_networks.py::test_build_any_http_url[HttpUrl-kwargs9-http2://example.net?a=b#c=d]", "tests/test_networks.py::test_build_any_http_url[HttpUrl-kwargs10-http://example.net:1234]", "tests/test_networks.py::test_build_any_http_url[HttpUrl-kwargs11-https://example.net:1234]", "tests/test_networks.py::test_build_http_url_port[AnyHttpUrl-kwargs0-http://[email protected]:80]", "tests/test_networks.py::test_build_http_url_port[AnyHttpUrl-kwargs1-https://[email protected]:443]", "tests/test_networks.py::test_build_http_url_port[HttpUrl-kwargs2-http://[email protected]]", "tests/test_networks.py::test_build_http_url_port[HttpUrl-kwargs3-https://[email protected]]", "tests/test_networks.py::test_son", "tests/test_networks.py::test_address_valid[[email protected]@example.com]", "tests/test_networks.py::test_address_valid[[email protected]@muelcolvin.com]", "tests/test_networks.py::test_address_valid[Samuel", "tests/test_networks.py::test_address_valid[foobar", "tests/test_networks.py::test_address_valid[", "tests/test_networks.py::test_address_valid[[email protected]", "tests/test_networks.py::test_address_valid[foo", "tests/test_networks.py::test_address_valid[FOO", "tests/test_networks.py::test_address_valid[<[email protected]>", "tests/test_networks.py::test_address_valid[\\xf1o\\xf1\\[email protected]\\xf1o\\xf1\\xf3-\\xf1o\\xf1\\[email protected]]", "tests/test_networks.py::test_address_valid[\\u6211\\[email protected]\\u6211\\u8cb7-\\u6211\\[email protected]]", "tests/test_networks.py::test_address_valid[\\u7532\\u6590\\u9ed2\\u5ddd\\u65e5\\[email protected]\\u7532\\u6590\\u9ed2\\u5ddd\\u65e5\\u672c-\\u7532\\u6590\\u9ed2\\u5ddd\\u65e5\\[email protected]]", "tests/test_networks.py::test_address_valid[\\u0447\\u0435\\u0431\\u0443\\u0440\\u0430\\u0448\\u043a\\u0430\\u044f\\u0449\\u0438\\u043a-\\u0441-\\u0430\\u043f\\u0435\\u043b\\u044c\\u0441\\u0438\\u043d\\u0430\\u043c\\u0438.\\u0440\\[email protected]\\u0447\\u0435\\u0431\\u0443\\u0440\\u0430\\u0448\\u043a\\u0430\\u044f\\u0449\\u0438\\u043a-\\u0441-\\u0430\\u043f\\u0435\\u043b\\u044c\\u0441\\u0438\\u043d\\u0430\\u043c\\u0438.\\u0440\\u0444-\\u0447\\u0435\\u0431\\u0443\\u0440\\u0430\\u0448\\u043a\\u0430\\u044f\\u0449\\u0438\\u043a-\\u0441-\\u0430\\u043f\\u0435\\u043b\\u044c\\u0441\\u0438\\u043d\\u0430\\u043c\\u0438.\\u0440\\[email protected]]", "tests/test_networks.py::test_address_valid[\\u0909\\u0926\\u093e\\u0939\\u0930\\u0923.\\u092a\\u0930\\u0940\\u0915\\u094d\\[email protected]\\u0909\\u0926\\u093e\\u0939\\u0930\\u0923.\\u092a\\u0930\\u0940\\u0915\\u094d\\u0937-\\u0909\\u0926\\u093e\\u0939\\u0930\\u0923.\\u092a\\u0930\\u0940\\u0915\\u094d\\[email protected]]", "tests/test_networks.py::test_address_valid[[email protected]@example.com]", "tests/test_networks.py::test_address_valid[[email protected]", "tests/test_networks.py::test_address_valid[\\u03b9\\u03c9\\u03ac\\u03bd\\u03bd\\u03b7\\u03c2@\\u03b5\\u03b5\\u03c4\\u03c4.gr-\\u03b9\\u03c9\\u03ac\\u03bd\\u03bd\\u03b7\\u03c2-\\u03b9\\u03c9\\u03ac\\u03bd\\u03bd\\u03b7\\u03c2@\\u03b5\\u03b5\\u03c4\\u03c4.gr]", "tests/test_networks.py::test_address_invalid[f", "tests/test_networks.py::test_address_invalid[foo.bar@exam\\nple.com", "tests/test_networks.py::test_address_invalid[foobar]", "tests/test_networks.py::test_address_invalid[foobar", "tests/test_networks.py::test_address_invalid[@example.com]", "tests/test_networks.py::test_address_invalid[[email protected]]", "tests/test_networks.py::test_address_invalid[[email protected]]", "tests/test_networks.py::test_address_invalid[foo", "tests/test_networks.py::test_address_invalid[foo@[email protected]]", "tests/test_networks.py::test_address_invalid[\\[email protected]]", "tests/test_networks.py::test_address_invalid[\\[email protected]]", "tests/test_networks.py::test_address_invalid[\\[email protected]]", "tests/test_networks.py::test_address_invalid[", "tests/test_networks.py::test_address_invalid[\\[email protected]]", "tests/test_networks.py::test_address_invalid[\"@example.com0]", "tests/test_networks.py::test_address_invalid[\"@example.com1]", "tests/test_networks.py::test_address_invalid[,@example.com]", "tests/test_networks.py::test_email_str", "tests/test_networks.py::test_name_email" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-07-10 07:52:41+00:00
mit
4,866
pydantic__pydantic-4225
diff --git a/pydantic/validators.py b/pydantic/validators.py --- a/pydantic/validators.py +++ b/pydantic/validators.py @@ -555,11 +555,14 @@ def pattern_validator(v: Any) -> Pattern[str]: NamedTupleT = TypeVar('NamedTupleT', bound=NamedTuple) -def make_namedtuple_validator(namedtuple_cls: Type[NamedTupleT]) -> Callable[[Tuple[Any, ...]], NamedTupleT]: +def make_namedtuple_validator( + namedtuple_cls: Type[NamedTupleT], config: Type['BaseConfig'] +) -> Callable[[Tuple[Any, ...]], NamedTupleT]: from .annotated_types import create_model_from_namedtuple NamedTupleModel = create_model_from_namedtuple( namedtuple_cls, + __config__=config, __module__=namedtuple_cls.__module__, ) namedtuple_cls.__pydantic_model__ = NamedTupleModel # type: ignore[attr-defined] @@ -690,7 +693,7 @@ def find_validators( # noqa: C901 (ignore complexity) return if is_namedtuple(type_): yield tuple_validator - yield make_namedtuple_validator(type_) + yield make_namedtuple_validator(type_, config) return if is_typeddict(type_): yield make_typeddict_validator(type_, config)
pydantic/pydantic
fd2991fe6a73819b48c906e3c3274e8e47d0f761
diff --git a/tests/test_annotated_types.py b/tests/test_annotated_types.py --- a/tests/test_annotated_types.py +++ b/tests/test_annotated_types.py @@ -146,6 +146,29 @@ class Model(BaseModel): Model.parse_obj({'t': [-1]}) +def test_namedtuple_arbitrary_type(): + class CustomClass: + pass + + class Tup(NamedTuple): + c: CustomClass + + class Model(BaseModel): + x: Tup + + class Config: + arbitrary_types_allowed = True + + data = {'x': Tup(c=CustomClass())} + model = Model.parse_obj(data) + assert isinstance(model.x.c, CustomClass) + + with pytest.raises(RuntimeError): + + class ModelNoArbitraryTypes(BaseModel): + x: Tup + + def test_typeddict(): class TD(TypedDict): a: int
arbitrary_types_allowed does not propagate to the model which is created for a NamedTuple ### Checks * [x] I added a descriptive title to this issue * [x] I have searched (google, github) for similar issues and couldn't find anything * [x] I have read and followed [the docs](https://pydantic-docs.helpmanual.io/) and still think this is a bug # Bug When using a NamedTuple as a field in a pydantic model, it cannot have arbitrary types - even if `arbitrary_types_allowed` is `True` on the model. I found that when `create_model_from_namedtuple` is [called](https://github.com/samuelcolvin/pydantic/blob/master/pydantic/validators.py#L561), `config` is not passed (but for `TypedDict`, it _is_ [passed](https://github.com/samuelcolvin/pydantic/blob/master/pydantic/validators.py#L585)). Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.9.1 pydantic compiled: True install path: /home/rory/lab/mres/task/co/.venv/lib/python3.9/site-packages/pydantic python version: 3.9.13 (main, May 27 2022, 11:07:19) [GCC 12.1.0] platform: Linux-5.18.7-arch1-1-x86_64-with-glibc2.35 optional deps. installed: ['typing-extensions'] ``` ```py from typing import NamedTuple import pydantic class Foo: pass class Bar(NamedTuple): foo: Foo class MyModel(pydantic.BaseModel): bar: Bar class Config: arbitrary_types_allowed = True ``` ![image](https://user-images.githubusercontent.com/9436784/177740846-791a8db5-2c1f-459f-b97a-31951faaa7bf.png)
0.0
fd2991fe6a73819b48c906e3c3274e8e47d0f761
[ "tests/test_annotated_types.py::test_namedtuple_arbitrary_type" ]
[ "tests/test_annotated_types.py::test_namedtuple", "tests/test_annotated_types.py::test_namedtuple_schema", "tests/test_annotated_types.py::test_namedtuple_right_length", "tests/test_annotated_types.py::test_namedtuple_postponed_annotation", "tests/test_annotated_types.py::test_typeddict", "tests/test_annotated_types.py::test_typeddict_non_total", "tests/test_annotated_types.py::test_partial_new_typeddict", "tests/test_annotated_types.py::test_typeddict_extra", "tests/test_annotated_types.py::test_typeddict_schema", "tests/test_annotated_types.py::test_typeddict_postponed_annotation" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_media" ], "has_test_patch": true, "is_lite": false }
2022-07-10 14:44:13+00:00
mit
4,867
pydantic__pydantic-4252
diff --git a/pydantic/fields.py b/pydantic/fields.py --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -148,7 +148,7 @@ def __init__(self, default: Any = Undefined, **kwargs: Any) -> None: self.default = default self.default_factory = kwargs.pop('default_factory', None) self.alias = kwargs.pop('alias', None) - self.alias_priority = kwargs.pop('alias_priority', 2 if self.alias else None) + self.alias_priority = kwargs.pop('alias_priority', 2 if self.alias is not None else None) self.title = kwargs.pop('title', None) self.description = kwargs.pop('description', None) self.exclude = kwargs.pop('exclude', None) @@ -394,8 +394,8 @@ def __init__( ) -> None: self.name: str = name - self.has_alias: bool = bool(alias) - self.alias: str = alias or name + self.has_alias: bool = alias is not None + self.alias: str = alias if alias is not None else name self.type_: Any = convert_generics(type_) self.outer_type_: Any = type_ self.class_validators = class_validators or {}
pydantic/pydantic
50bc758495f5e22f3ad86d03bcf6c645a7d029cf
diff --git a/tests/test_aliases.py b/tests/test_aliases.py --- a/tests/test_aliases.py +++ b/tests/test_aliases.py @@ -335,3 +335,13 @@ def alias_generator(x): 'd_config_parent', 'e_generator_child', ] + + +def test_empty_string_alias(): + class Model(BaseModel): + empty_string_key: int = Field(alias='') + + data = {'': 123} + m = Model(**data) + assert m.empty_string_key == 123 + assert m.dict(by_alias=True) == data
An empty string is a valid JSON attribute name ### Checks * [ x] I added a descriptive title to this issue * [ x] I have searched (google, github) for similar issues and couldn't find anything * [ x] I have read and followed [the docs](https://pydantic-docs.helpmanual.io/) and still think this is a bug # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.9.0 pydantic compiled: False install path: /Users/s_tsaplin/projects/github.com/sergeytsaplin/pydantic/pydantic python version: 3.9.13 (main, May 19 2022, 14:10:54) [Clang 13.1.6 (clang-1316.0.21.2)] platform: macOS-12.4-x86_64-i386-64bit optional deps. installed: ['devtools', 'dotenv', 'email-validator', 'typing-extensions'] ``` ```py from pydantic import BaseModel, Field class Model(BaseModel): empty_string_key: int = Field(alias='') data = {'': 123} m = Model(**data) m.dict(by_alias=True) ``` ## Current behavior: The code causes the exception: ``` Traceback (most recent call last): File "<masked>/.pyenv/versions/3.10.1/lib/python3.10/code.py", line 90, in runcode exec(code, self.locals) File "<input>", line 1, in <module> File "pydantic/main.py", line 341, in pydantic.main.BaseModel.__init__ pydantic.error_wrappers.ValidationError: 1 validation error for Model empty_string_key field required (type=value_error.missing) ``` ## Expected result: The code should print: ``` {'': 123} ``` Links: * https://stackoverflow.com/questions/58916957/is-an-empty-string-a-valid-json-key * https://datatracker.ietf.org/doc/html/rfc6901#section-5
0.0
50bc758495f5e22f3ad86d03bcf6c645a7d029cf
[ "tests/test_aliases.py::test_empty_string_alias" ]
[ "tests/test_aliases.py::test_alias_generator", "tests/test_aliases.py::test_alias_generator_with_field_schema", "tests/test_aliases.py::test_alias_generator_wrong_type_error", "tests/test_aliases.py::test_infer_alias", "tests/test_aliases.py::test_alias_error", "tests/test_aliases.py::test_annotation_config", "tests/test_aliases.py::test_alias_camel_case", "tests/test_aliases.py::test_get_field_info_inherit", "tests/test_aliases.py::test_pop_by_field_name", "tests/test_aliases.py::test_alias_child_precedence", "tests/test_aliases.py::test_alias_generator_parent", "tests/test_aliases.py::test_alias_generator_on_parent", "tests/test_aliases.py::test_alias_generator_on_child", "tests/test_aliases.py::test_low_priority_alias", "tests/test_aliases.py::test_low_priority_alias_config", "tests/test_aliases.py::test_field_vs_config", "tests/test_aliases.py::test_alias_priority" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2022-07-19 11:13:58+00:00
mit
4,868
pydantic__pydantic-4329
diff --git a/pydantic/datetime_parse.py b/pydantic/datetime_parse.py --- a/pydantic/datetime_parse.py +++ b/pydantic/datetime_parse.py @@ -223,7 +223,7 @@ def parse_duration(value: StrBytesIntFloat) -> timedelta: if isinstance(value, (int, float)): # below code requires a string - value = str(value) + value = f'{value:f}' elif isinstance(value, bytes): value = value.decode()
pydantic/pydantic
5293adb3d3d1b6fcdb4e1ffc188a560fe601260c
diff --git a/tests/test_datetime_parse.py b/tests/test_datetime_parse.py --- a/tests/test_datetime_parse.py +++ b/tests/test_datetime_parse.py @@ -175,6 +175,7 @@ def test_parse_python_format(delta): ('30', timedelta(seconds=30)), (30, timedelta(seconds=30)), (30.1, timedelta(seconds=30, milliseconds=100)), + (9.9e-05, timedelta(microseconds=99)), # minutes seconds ('15:30', timedelta(minutes=15, seconds=30)), ('5:30', timedelta(minutes=5, seconds=30)),
Serialization -> de-serialisation fails for small timedelta (< 100 microseconds) ### Checks * [x] I added a descriptive title to this issue * [x] I have searched (google, github) for similar issues and couldn't find anything * [x] I have read and followed [the docs](https://pydantic-docs.helpmanual.io/) and still think this is a bug <!-- Sorry to sound so draconian, but every second saved replying to issues is time spend improving pydantic :-) --> # Bug The serialization -> de-serialization of a model with small `timedelta` raises a `ValidationError`. The de-serialization fails only when the `timedelta` is below 100 microseconds, see the following example: ```py from datetime import timedelta from pydantic import BaseModel class Model(BaseModel): duration: timedelta # This works model = Model(duration=timedelta(microseconds=100)) Model.parse_raw(model.json()) # This Fails model = Model(duration=timedelta(microseconds=99)) Model.parse_raw(model.json()) ``` Last line throws the following error: ```py pydantic.error_wrappers.ValidationError: 1 validation error for Model duration invalid duration format (type=value_error.duration) ``` I believe the error comes from the `parse_duration` function, and in particular the line where the input value is converted to `str`. https://github.com/samuelcolvin/pydantic/blob/c256dccbb383a7fd462f62fcb5d55558eb3cb108/pydantic/datetime_parse.py#L226-L231 Indeed `str(0.0001)` gives `"0.0001"` but `str(0.000099)` gives `"9.9e-5"`, thus the `re.match` fails. Changing `value = str(value)` to `value = "f{value:.6f}"` should fix this. I would be happy to create a PR to solve the issue. # System information Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.8.2 pydantic compiled: True install path: <my-home>/.pyenv/versions/3.7.11/envs/pydantic/lib/python3.7/site-packages/pydantic python version: 3.7.11 (default, Aug 31 2021, 20:43:02) [Clang 10.0.1 (clang-1001.0.46.4)] platform: Darwin-19.6.0-x86_64-i386-64bit optional deps. installed: ['typing-extensions'] ```
0.0
5293adb3d3d1b6fcdb4e1ffc188a560fe601260c
[ "tests/test_datetime_parse.py::test_parse_durations[9.9e-05-result4]" ]
[ "tests/test_datetime_parse.py::test_date_parsing[1494012444.883309-result0]", "tests/test_datetime_parse.py::test_date_parsing[1494012444.883309-result1]", "tests/test_datetime_parse.py::test_date_parsing[1494012444.883309-result2]", "tests/test_datetime_parse.py::test_date_parsing[1494012444-result3]", "tests/test_datetime_parse.py::test_date_parsing[1494012444-result4]", "tests/test_datetime_parse.py::test_date_parsing[0-result5]", "tests/test_datetime_parse.py::test_date_parsing[2012-04-23-result6]", "tests/test_datetime_parse.py::test_date_parsing[2012-04-23-result7]", "tests/test_datetime_parse.py::test_date_parsing[2012-4-9-result8]", "tests/test_datetime_parse.py::test_date_parsing[value9-result9]", "tests/test_datetime_parse.py::test_date_parsing[value10-result10]", "tests/test_datetime_parse.py::test_date_parsing[x20120423-DateError]", "tests/test_datetime_parse.py::test_date_parsing[2012-04-56-DateError]", "tests/test_datetime_parse.py::test_date_parsing[19999999999-result13]", "tests/test_datetime_parse.py::test_date_parsing[20000000001-result14]", "tests/test_datetime_parse.py::test_date_parsing[1549316052-result15]", "tests/test_datetime_parse.py::test_date_parsing[1549316052104-result16]", "tests/test_datetime_parse.py::test_date_parsing[1549316052104324-result17]", "tests/test_datetime_parse.py::test_date_parsing[1549316052104324096-result18]", "tests/test_datetime_parse.py::test_date_parsing[infinity-result19]", "tests/test_datetime_parse.py::test_date_parsing[inf-result20]", "tests/test_datetime_parse.py::test_date_parsing[inf-result21]", "tests/test_datetime_parse.py::test_date_parsing[infinity", "tests/test_datetime_parse.py::test_date_parsing[10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000-result23]", "tests/test_datetime_parse.py::test_date_parsing[inf-result24]", "tests/test_datetime_parse.py::test_date_parsing[-infinity-result25]", "tests/test_datetime_parse.py::test_date_parsing[-inf-result26]", "tests/test_datetime_parse.py::test_date_parsing[nan-ValueError]", "tests/test_datetime_parse.py::test_time_parsing[09:15:00-result0]", "tests/test_datetime_parse.py::test_time_parsing[10:10-result1]", "tests/test_datetime_parse.py::test_time_parsing[10:20:30.400-result2]", "tests/test_datetime_parse.py::test_time_parsing[10:20:30.400-result3]", "tests/test_datetime_parse.py::test_time_parsing[4:8:16-result4]", "tests/test_datetime_parse.py::test_time_parsing[value5-result5]", "tests/test_datetime_parse.py::test_time_parsing[3610-result6]", "tests/test_datetime_parse.py::test_time_parsing[3600.5-result7]", "tests/test_datetime_parse.py::test_time_parsing[86399-result8]", "tests/test_datetime_parse.py::test_time_parsing[11:05:00-05:30-result9]", "tests/test_datetime_parse.py::test_time_parsing[11:05:00-0530-result10]", "tests/test_datetime_parse.py::test_time_parsing[11:05:00Z-result11]", "tests/test_datetime_parse.py::test_time_parsing[11:05:00+00-result12]", "tests/test_datetime_parse.py::test_time_parsing[11:05-06-result13]", "tests/test_datetime_parse.py::test_time_parsing[11:05+06-result14]", "tests/test_datetime_parse.py::test_time_parsing[86400-TimeError]", "tests/test_datetime_parse.py::test_time_parsing[xxx-TimeError]", "tests/test_datetime_parse.py::test_time_parsing[091500-TimeError0]", "tests/test_datetime_parse.py::test_time_parsing[091500-TimeError1]", "tests/test_datetime_parse.py::test_time_parsing[09:15:90-TimeError]", "tests/test_datetime_parse.py::test_time_parsing[11:05:00Y-TimeError]", "tests/test_datetime_parse.py::test_time_parsing[11:05:00-25:00-TimeError]", "tests/test_datetime_parse.py::test_datetime_parsing[1494012444.883309-result0]", "tests/test_datetime_parse.py::test_datetime_parsing[1494012444.883309-result1]", "tests/test_datetime_parse.py::test_datetime_parsing[1494012444-result2]", "tests/test_datetime_parse.py::test_datetime_parsing[1494012444-result3]", "tests/test_datetime_parse.py::test_datetime_parsing[1494012444-result4]", "tests/test_datetime_parse.py::test_datetime_parsing[1494012444000.883309-result5]", "tests/test_datetime_parse.py::test_datetime_parsing[-1494012444000.883309-result6]", "tests/test_datetime_parse.py::test_datetime_parsing[1494012444000-result7]", "tests/test_datetime_parse.py::test_datetime_parsing[2012-04-23T09:15:00-result8]", "tests/test_datetime_parse.py::test_datetime_parsing[2012-4-9", "tests/test_datetime_parse.py::test_datetime_parsing[2012-04-23T09:15:00Z-result10]", "tests/test_datetime_parse.py::test_datetime_parsing[2012-04-23T10:20:30.400+02:30-result12]", "tests/test_datetime_parse.py::test_datetime_parsing[2012-04-23T10:20:30.400+02-result13]", "tests/test_datetime_parse.py::test_datetime_parsing[2012-04-23T10:20:30.400-02-result14]", "tests/test_datetime_parse.py::test_datetime_parsing[2012-04-23T10:20:30.400-02-result15]", "tests/test_datetime_parse.py::test_datetime_parsing[value16-result16]", "tests/test_datetime_parse.py::test_datetime_parsing[0-result17]", "tests/test_datetime_parse.py::test_datetime_parsing[x20120423091500-DateTimeError]", "tests/test_datetime_parse.py::test_datetime_parsing[2012-04-56T09:15:90-DateTimeError]", "tests/test_datetime_parse.py::test_datetime_parsing[2012-04-23T11:05:00-25:00-DateTimeError]", "tests/test_datetime_parse.py::test_datetime_parsing[19999999999-result21]", "tests/test_datetime_parse.py::test_datetime_parsing[20000000001-result22]", "tests/test_datetime_parse.py::test_datetime_parsing[1549316052-result23]", "tests/test_datetime_parse.py::test_datetime_parsing[1549316052104-result24]", "tests/test_datetime_parse.py::test_datetime_parsing[1549316052104324-result25]", "tests/test_datetime_parse.py::test_datetime_parsing[1549316052104324096-result26]", "tests/test_datetime_parse.py::test_datetime_parsing[infinity-result27]", "tests/test_datetime_parse.py::test_datetime_parsing[inf-result28]", "tests/test_datetime_parse.py::test_datetime_parsing[inf", "tests/test_datetime_parse.py::test_datetime_parsing[1e+50-result30]", "tests/test_datetime_parse.py::test_datetime_parsing[inf-result31]", "tests/test_datetime_parse.py::test_datetime_parsing[-infinity-result32]", "tests/test_datetime_parse.py::test_datetime_parsing[-inf-result33]", "tests/test_datetime_parse.py::test_datetime_parsing[nan-ValueError]", "tests/test_datetime_parse.py::test_parse_python_format[delta0]", "tests/test_datetime_parse.py::test_parse_python_format[delta1]", "tests/test_datetime_parse.py::test_parse_python_format[delta2]", "tests/test_datetime_parse.py::test_parse_python_format[delta3]", "tests/test_datetime_parse.py::test_parse_python_format[delta4]", "tests/test_datetime_parse.py::test_parse_python_format[delta5]", "tests/test_datetime_parse.py::test_parse_python_format[delta6]", "tests/test_datetime_parse.py::test_parse_durations[value0-result0]", "tests/test_datetime_parse.py::test_parse_durations[30-result1]", "tests/test_datetime_parse.py::test_parse_durations[30-result2]", "tests/test_datetime_parse.py::test_parse_durations[30.1-result3]", "tests/test_datetime_parse.py::test_parse_durations[15:30-result5]", "tests/test_datetime_parse.py::test_parse_durations[5:30-result6]", "tests/test_datetime_parse.py::test_parse_durations[10:15:30-result7]", "tests/test_datetime_parse.py::test_parse_durations[1:15:30-result8]", "tests/test_datetime_parse.py::test_parse_durations[100:200:300-result9]", "tests/test_datetime_parse.py::test_parse_durations[4", "tests/test_datetime_parse.py::test_parse_durations[15:30.1-result12]", "tests/test_datetime_parse.py::test_parse_durations[15:30.01-result13]", "tests/test_datetime_parse.py::test_parse_durations[15:30.001-result14]", "tests/test_datetime_parse.py::test_parse_durations[15:30.0001-result15]", "tests/test_datetime_parse.py::test_parse_durations[15:30.00001-result16]", "tests/test_datetime_parse.py::test_parse_durations[15:30.000001-result17]", "tests/test_datetime_parse.py::test_parse_durations[15:30.000001-result18]", "tests/test_datetime_parse.py::test_parse_durations[-4", "tests/test_datetime_parse.py::test_parse_durations[-172800-result20]", "tests/test_datetime_parse.py::test_parse_durations[-15:30-result21]", "tests/test_datetime_parse.py::test_parse_durations[-1:15:30-result22]", "tests/test_datetime_parse.py::test_parse_durations[-30.1-result23]", "tests/test_datetime_parse.py::test_parse_durations[P4Y-DurationError]", "tests/test_datetime_parse.py::test_parse_durations[P4M-DurationError]", "tests/test_datetime_parse.py::test_parse_durations[P4W-DurationError]", "tests/test_datetime_parse.py::test_parse_durations[P4D-result27]", "tests/test_datetime_parse.py::test_parse_durations[P0.5D-result28]", "tests/test_datetime_parse.py::test_parse_durations[PT5H-result29]", "tests/test_datetime_parse.py::test_parse_durations[PT5M-result30]", "tests/test_datetime_parse.py::test_parse_durations[PT5S-result31]", "tests/test_datetime_parse.py::test_parse_durations[PT0.000005S-result32]", "tests/test_datetime_parse.py::test_parse_durations[PT0.000005S-result33]", "tests/test_datetime_parse.py::test_model_type_errors[dt-value0-invalid", "tests/test_datetime_parse.py::test_model_type_errors[dt-value1-invalid", "tests/test_datetime_parse.py::test_model_type_errors[dt-object-invalid", "tests/test_datetime_parse.py::test_model_type_errors[d-value3-invalid", "tests/test_datetime_parse.py::test_model_type_errors[d-value4-invalid", "tests/test_datetime_parse.py::test_model_type_errors[d-object-invalid", "tests/test_datetime_parse.py::test_model_type_errors[t-value6-invalid", "tests/test_datetime_parse.py::test_model_type_errors[t-value7-invalid", "tests/test_datetime_parse.py::test_model_type_errors[t-object-invalid", "tests/test_datetime_parse.py::test_model_type_errors[td-value9-invalid", "tests/test_datetime_parse.py::test_model_type_errors[td-value10-invalid", "tests/test_datetime_parse.py::test_model_type_errors[td-object-invalid", "tests/test_datetime_parse.py::test_unicode_decode_error[dt0]", "tests/test_datetime_parse.py::test_unicode_decode_error[d]", "tests/test_datetime_parse.py::test_unicode_decode_error[t]", "tests/test_datetime_parse.py::test_unicode_decode_error[dt1]", "tests/test_datetime_parse.py::test_nan" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2022-08-05 11:20:26+00:00
mit
4,869
pydantic__pydantic-4335
diff --git a/pydantic/schema.py b/pydantic/schema.py --- a/pydantic/schema.py +++ b/pydantic/schema.py @@ -705,7 +705,8 @@ def field_singleton_sub_fields_schema( else: s: Dict[str, Any] = {} # https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#discriminator-object - if field.discriminator_key is not None: + field_has_discriminator: bool = field.discriminator_key is not None + if field_has_discriminator: assert field.sub_fields_mapping is not None discriminator_models_refs: Dict[str, Union[str, Dict[str, Any]]] = {} @@ -748,16 +749,16 @@ def field_singleton_sub_fields_schema( definitions.update(sub_definitions) if schema_overrides and 'allOf' in sub_schema: # if the sub_field is a referenced schema we only need the referenced - # object. Otherwise we will end up with several allOf inside anyOf. + # object. Otherwise we will end up with several allOf inside anyOf/oneOf. # See https://github.com/pydantic/pydantic/issues/1209 sub_schema = sub_schema['allOf'][0] - if sub_schema.keys() == {'discriminator', 'anyOf'}: - # we don't want discriminator information inside anyOf choices, this is dealt with elsewhere + if sub_schema.keys() == {'discriminator', 'oneOf'}: + # we don't want discriminator information inside oneOf choices, this is dealt with elsewhere sub_schema.pop('discriminator') sub_field_schemas.append(sub_schema) nested_models.update(sub_nested_models) - s['anyOf'] = sub_field_schemas + s['oneOf' if field_has_discriminator else 'anyOf'] = sub_field_schemas return s, definitions, nested_models
pydantic/pydantic
11d8589423ac82f64eb4007bdad824f4a6217434
diff --git a/tests/test_dataclasses.py b/tests/test_dataclasses.py --- a/tests/test_dataclasses.py +++ b/tests/test_dataclasses.py @@ -1190,7 +1190,7 @@ class Users(BaseModel): } -def test_discrimated_union_basemodel_instance_value(): +def test_discriminated_union_basemodel_instance_value(): @pydantic.dataclasses.dataclass class A: l: Literal['a'] @@ -1212,7 +1212,7 @@ class Top: 'sub': { 'title': 'Sub', 'discriminator': {'propertyName': 'l', 'mapping': {'a': '#/definitions/A', 'b': '#/definitions/B'}}, - 'anyOf': [{'$ref': '#/definitions/A'}, {'$ref': '#/definitions/B'}], + 'oneOf': [{'$ref': '#/definitions/A'}, {'$ref': '#/definitions/B'}], } }, 'required': ['sub'], diff --git a/tests/test_forward_ref.py b/tests/test_forward_ref.py --- a/tests/test_forward_ref.py +++ b/tests/test_forward_ref.py @@ -588,7 +588,7 @@ class Dog(BaseModel): assert module.Pet.schema() == { 'title': 'Pet', 'discriminator': {'propertyName': 'type', 'mapping': {'cat': '#/definitions/Cat', 'dog': '#/definitions/Dog'}}, - 'anyOf': [{'$ref': '#/definitions/Cat'}, {'$ref': '#/definitions/Dog'}], + 'oneOf': [{'$ref': '#/definitions/Cat'}, {'$ref': '#/definitions/Dog'}], 'definitions': { 'Cat': { 'title': 'Cat', diff --git a/tests/test_schema.py b/tests/test_schema.py --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -2675,7 +2675,7 @@ class Model(BaseModel): 'lizard': '#/definitions/Lizard', }, }, - 'anyOf': [ + 'oneOf': [ {'$ref': '#/definitions/Cat'}, {'$ref': '#/definitions/Dog'}, {'$ref': '#/definitions/Lizard'}, @@ -2708,7 +2708,7 @@ class Model(BaseModel): 'propertyName': 'color', 'mapping': {'black': '#/definitions/BlackCat', 'white': '#/definitions/WhiteCat'}, }, - 'anyOf': [{'$ref': '#/definitions/BlackCat'}, {'$ref': '#/definitions/WhiteCat'}], + 'oneOf': [{'$ref': '#/definitions/BlackCat'}, {'$ref': '#/definitions/WhiteCat'}], }, 'Dog': { 'title': 'Dog', @@ -2775,11 +2775,11 @@ class Model(BaseModel): 'dog': '#/definitions/Dog', }, }, - 'anyOf': [ + 'oneOf': [ { - 'anyOf': [ + 'oneOf': [ { - 'anyOf': [ + 'oneOf': [ {'$ref': '#/definitions/BlackCatWithHeight'}, {'$ref': '#/definitions/BlackCatWithWeight'}, ] @@ -2858,7 +2858,7 @@ class Model(BaseModel): 'properties': { 'number': {'title': 'Number', 'type': 'integer'}, 'pet': { - 'anyOf': [{'$ref': '#/definitions/Cat'}, {'$ref': '#/definitions/Dog'}], + 'oneOf': [{'$ref': '#/definitions/Cat'}, {'$ref': '#/definitions/Dog'}], 'discriminator': { 'mapping': {'cat': '#/definitions/Cat', 'dog': '#/definitions/Dog'}, 'propertyName': 'typeOfPet', @@ -2960,9 +2960,9 @@ class Model(BaseModel): 'dog': '#/definitions/Dog', }, }, - 'anyOf': [ + 'oneOf': [ { - 'anyOf': [ + 'oneOf': [ {'$ref': '#/definitions/BlackCat'}, {'$ref': '#/definitions/WhiteCat'}, ],
Union produces anyOf instead of oneOf for OpenAPI generation ### Checks * [x] I added a descriptive title to this issue * [x] I have searched (google, github) for similar issues and couldn't find anything * [x] I have read and followed [the docs](https://pydantic-docs.helpmanual.io/) and still think this is a bug <!-- Sorry to sound so draconian, but every second saved replying to issues is time spend improving pydantic :-) --> # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.9.0 pydantic compiled: True install path: C:\Users\DEKOEHLS\Programme\Anaconda3\Lib\site-packages\pydantic python version: 3.9.7 (default, Sep 16 2021, 16:59:28) [MSC v.1916 64 bit (AMD64)] platform: Windows-10-10.0.19042-SP0 optional deps. installed: ['dotenv', 'typing-extensions'] ``` <!-- or if you're using pydantic prior to v1.3, manually include: OS, python version and pydantic version --> <!-- Please read the [docs](https://pydantic-docs.helpmanual.io/) and search through issues to confirm your bug hasn't already been reported. --> <!-- Where possible please include a self-contained code snippet describing your bug: --> ```py from typing import Literal, Union from pydantic import BaseModel, Field class Cat(BaseModel): pet_type: Literal['cat'] meows: int class Dog(BaseModel): pet_type: Literal['dog'] barks: float class Pet(BaseModel): __root__: Union[Cat, Dog] = Field(..., discriminator='pet_type') Pet.schema_json() ``` Hi all, Example from https://pydantic-docs.helpmanual.io/usage/types/#discriminated-unions-aka-tagged-unions: Using the class Pet above in FastAPI to allow either Cat or Dog as an input leads to an OpenAPI.json which makes Pet like (printed as yaml) ````yaml Pet: anyOf: - $ref: '#/components/schemas/Cat' - $ref: '#/components/schemas/Dog' discriminator: propertyName: pet_type ```` both OpenApi (https://swagger.io/docs/specification/data-models/oneof-anyof-allof-not/) and the specification https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.2.md#discriminatorObject linked by the pydantic docs (link on top) state that it should be oneOf. This also corresponds to the "typing" interpretation of *Union* which is, besides the naming, not a union of the arguments but a "one of those elements" I already found a issue here which has been closed: https://github.com/samuelcolvin/pydantic/issues/656 I didn't understand the arguments to be honest, However, I think it's just wrong to make it an anyOf. I tried to post it on FastAPI since it leads to an incorrect openapi.json so I thought maybe a workaround on FastAPI side was meaningful. They forwarded me back here though. https://github.com/tiangolo/fastapi/issues/4959 Best Stefan
0.0
11d8589423ac82f64eb4007bdad824f4a6217434
[ "tests/test_dataclasses.py::test_discriminated_union_basemodel_instance_value", "tests/test_forward_ref.py::test_discriminated_union_forward_ref", "tests/test_schema.py::test_discriminated_union", "tests/test_schema.py::test_discriminated_annotated_union", "tests/test_schema.py::test_alias_same", "tests/test_schema.py::test_discriminated_union_in_list" ]
[ "tests/test_dataclasses.py::test_simple", "tests/test_dataclasses.py::test_model_name", "tests/test_dataclasses.py::test_value_error", "tests/test_dataclasses.py::test_frozen", "tests/test_dataclasses.py::test_validate_assignment", "tests/test_dataclasses.py::test_validate_assignment_error", "tests/test_dataclasses.py::test_not_validate_assignment", "tests/test_dataclasses.py::test_validate_assignment_value_change", "tests/test_dataclasses.py::test_validate_assignment_extra", "tests/test_dataclasses.py::test_post_init", "tests/test_dataclasses.py::test_post_init_validation", "tests/test_dataclasses.py::test_post_init_inheritance_chain", "tests/test_dataclasses.py::test_post_init_post_parse", "tests/test_dataclasses.py::test_post_init_post_parse_types", "tests/test_dataclasses.py::test_post_init_assignment", "tests/test_dataclasses.py::test_inheritance", "tests/test_dataclasses.py::test_validate_long_string_error", "tests/test_dataclasses.py::test_validate_assigment_long_string_error", "tests/test_dataclasses.py::test_no_validate_assigment_long_string_error", "tests/test_dataclasses.py::test_nested_dataclass", "tests/test_dataclasses.py::test_arbitrary_types_allowed", "tests/test_dataclasses.py::test_nested_dataclass_model", "tests/test_dataclasses.py::test_fields", "tests/test_dataclasses.py::test_default_factory_field", "tests/test_dataclasses.py::test_default_factory_singleton_field", "tests/test_dataclasses.py::test_schema", "tests/test_dataclasses.py::test_nested_schema", "tests/test_dataclasses.py::test_initvar", "tests/test_dataclasses.py::test_derived_field_from_initvar", "tests/test_dataclasses.py::test_initvars_post_init", "tests/test_dataclasses.py::test_initvars_post_init_post_parse", "tests/test_dataclasses.py::test_classvar", "tests/test_dataclasses.py::test_frozenset_field", "tests/test_dataclasses.py::test_inheritance_post_init", "tests/test_dataclasses.py::test_hashable_required", "tests/test_dataclasses.py::test_hashable_optional[1]", "tests/test_dataclasses.py::test_hashable_optional[None]", "tests/test_dataclasses.py::test_hashable_optional[default2]", "tests/test_dataclasses.py::test_override_builtin_dataclass", "tests/test_dataclasses.py::test_override_builtin_dataclass_2", "tests/test_dataclasses.py::test_override_builtin_dataclass_nested", "tests/test_dataclasses.py::test_override_builtin_dataclass_nested_schema", "tests/test_dataclasses.py::test_inherit_builtin_dataclass", "tests/test_dataclasses.py::test_dataclass_arbitrary", "tests/test_dataclasses.py::test_forward_stdlib_dataclass_params", "tests/test_dataclasses.py::test_pydantic_callable_field", "tests/test_dataclasses.py::test_pickle_overriden_builtin_dataclass", "tests/test_dataclasses.py::test_config_field_info_create_model", "tests/test_dataclasses.py::test_issue_2162[foo0-bar0]", "tests/test_dataclasses.py::test_issue_2162[foo1-bar1]", "tests/test_dataclasses.py::test_issue_2162[foo2-bar2]", "tests/test_dataclasses.py::test_issue_2162[foo3-bar3]", "tests/test_dataclasses.py::test_issue_2383", "tests/test_dataclasses.py::test_issue_2398", "tests/test_dataclasses.py::test_issue_2424", "tests/test_dataclasses.py::test_issue_2541", "tests/test_dataclasses.py::test_issue_2555", "tests/test_dataclasses.py::test_issue_2594", "tests/test_dataclasses.py::test_schema_description_unset", "tests/test_dataclasses.py::test_schema_description_set", "tests/test_dataclasses.py::test_issue_3011", "tests/test_dataclasses.py::test_issue_3162", "tests/test_dataclasses.py::test_post_init_after_validation", "tests/test_dataclasses.py::test_keeps_custom_properties", "tests/test_dataclasses.py::test_ignore_extra", "tests/test_dataclasses.py::test_ignore_extra_subclass", "tests/test_dataclasses.py::test_allow_extra", "tests/test_dataclasses.py::test_allow_extra_subclass", "tests/test_dataclasses.py::test_forbid_extra", "tests/test_dataclasses.py::test_post_init_allow_extra", "tests/test_dataclasses.py::test_self_reference_dataclass", "tests/test_forward_ref.py::test_postponed_annotations", "tests/test_forward_ref.py::test_postponed_annotations_optional", "tests/test_forward_ref.py::test_postponed_annotations_auto_update_forward_refs", "tests/test_forward_ref.py::test_forward_ref_auto_update_no_model", "tests/test_forward_ref.py::test_forward_ref_one_of_fields_not_defined", "tests/test_forward_ref.py::test_basic_forward_ref", "tests/test_forward_ref.py::test_self_forward_ref_module", "tests/test_forward_ref.py::test_self_forward_ref_collection", "tests/test_forward_ref.py::test_self_forward_ref_local", "tests/test_forward_ref.py::test_missing_update_forward_refs", "tests/test_forward_ref.py::test_forward_ref_dataclass", "tests/test_forward_ref.py::test_forward_ref_dataclass_with_future_annotations", "tests/test_forward_ref.py::test_forward_ref_sub_types", "tests/test_forward_ref.py::test_forward_ref_nested_sub_types", "tests/test_forward_ref.py::test_self_reference_json_schema", "tests/test_forward_ref.py::test_self_reference_json_schema_with_future_annotations", "tests/test_forward_ref.py::test_circular_reference_json_schema", "tests/test_forward_ref.py::test_circular_reference_json_schema_with_future_annotations", "tests/test_forward_ref.py::test_forward_ref_with_field", "tests/test_forward_ref.py::test_forward_ref_optional", "tests/test_forward_ref.py::test_forward_ref_with_create_model", "tests/test_forward_ref.py::test_resolve_forward_ref_dataclass", "tests/test_forward_ref.py::test_nested_forward_ref", "tests/test_forward_ref.py::test_class_var_as_string", "tests/test_forward_ref.py::test_json_encoder_str", "tests/test_forward_ref.py::test_json_encoder_forward_ref", "tests/test_schema.py::test_key", "tests/test_schema.py::test_by_alias", "tests/test_schema.py::test_ref_template", "tests/test_schema.py::test_by_alias_generator", "tests/test_schema.py::test_sub_model", "tests/test_schema.py::test_schema_class", "tests/test_schema.py::test_schema_repr", "tests/test_schema.py::test_schema_class_by_alias", "tests/test_schema.py::test_choices", "tests/test_schema.py::test_enum_modify_schema", "tests/test_schema.py::test_enum_schema_custom_field", "tests/test_schema.py::test_enum_and_model_have_same_behaviour", "tests/test_schema.py::test_enum_includes_extra_without_other_params", "tests/test_schema.py::test_list_enum_schema_extras", "tests/test_schema.py::test_json_schema", "tests/test_schema.py::test_list_sub_model", "tests/test_schema.py::test_optional", "tests/test_schema.py::test_any", "tests/test_schema.py::test_set", "tests/test_schema.py::test_const_str", "tests/test_schema.py::test_const_false", "tests/test_schema.py::test_tuple[tuple-extra_props0]", "tests/test_schema.py::test_tuple[field_type1-extra_props1]", "tests/test_schema.py::test_tuple[field_type2-extra_props2]", "tests/test_schema.py::test_tuple[field_type3-extra_props3]", "tests/test_schema.py::test_deque", "tests/test_schema.py::test_bool", "tests/test_schema.py::test_strict_bool", "tests/test_schema.py::test_dict", "tests/test_schema.py::test_list", "tests/test_schema.py::test_list_union_dict[field_type0-expected_schema0]", "tests/test_schema.py::test_list_union_dict[field_type1-expected_schema1]", "tests/test_schema.py::test_list_union_dict[field_type2-expected_schema2]", "tests/test_schema.py::test_list_union_dict[field_type3-expected_schema3]", "tests/test_schema.py::test_list_union_dict[field_type4-expected_schema4]", "tests/test_schema.py::test_date_types[datetime-expected_schema0]", "tests/test_schema.py::test_date_types[date-expected_schema1]", "tests/test_schema.py::test_date_types[time-expected_schema2]", "tests/test_schema.py::test_date_types[timedelta-expected_schema3]", "tests/test_schema.py::test_str_basic_types[field_type0-expected_schema0]", "tests/test_schema.py::test_str_basic_types[field_type1-expected_schema1]", "tests/test_schema.py::test_str_basic_types[field_type2-expected_schema2]", "tests/test_schema.py::test_str_basic_types[field_type3-expected_schema3]", "tests/test_schema.py::test_str_constrained_types[StrictStr-expected_schema0]", "tests/test_schema.py::test_str_constrained_types[ConstrainedStr-expected_schema1]", "tests/test_schema.py::test_str_constrained_types[ConstrainedStrValue-expected_schema2]", "tests/test_schema.py::test_special_str_types[AnyUrl-expected_schema0]", "tests/test_schema.py::test_special_str_types[UrlValue-expected_schema1]", "tests/test_schema.py::test_email_str_types[EmailStr-email]", "tests/test_schema.py::test_email_str_types[NameEmail-name-email]", "tests/test_schema.py::test_secret_types[SecretBytes-string]", "tests/test_schema.py::test_secret_types[SecretStr-string]", "tests/test_schema.py::test_special_int_types[ConstrainedInt-expected_schema0]", "tests/test_schema.py::test_special_int_types[ConstrainedIntValue-expected_schema1]", "tests/test_schema.py::test_special_int_types[ConstrainedIntValue-expected_schema2]", "tests/test_schema.py::test_special_int_types[ConstrainedIntValue-expected_schema3]", "tests/test_schema.py::test_special_int_types[PositiveInt-expected_schema4]", "tests/test_schema.py::test_special_int_types[NegativeInt-expected_schema5]", "tests/test_schema.py::test_special_int_types[NonNegativeInt-expected_schema6]", "tests/test_schema.py::test_special_int_types[NonPositiveInt-expected_schema7]", "tests/test_schema.py::test_special_float_types[ConstrainedFloat-expected_schema0]", "tests/test_schema.py::test_special_float_types[ConstrainedFloatValue-expected_schema1]", "tests/test_schema.py::test_special_float_types[ConstrainedFloatValue-expected_schema2]", "tests/test_schema.py::test_special_float_types[ConstrainedFloatValue-expected_schema3]", "tests/test_schema.py::test_special_float_types[PositiveFloat-expected_schema4]", "tests/test_schema.py::test_special_float_types[NegativeFloat-expected_schema5]", "tests/test_schema.py::test_special_float_types[NonNegativeFloat-expected_schema6]", "tests/test_schema.py::test_special_float_types[NonPositiveFloat-expected_schema7]", "tests/test_schema.py::test_special_float_types[ConstrainedDecimal-expected_schema8]", "tests/test_schema.py::test_special_float_types[ConstrainedDecimalValue-expected_schema9]", "tests/test_schema.py::test_special_float_types[ConstrainedDecimalValue-expected_schema10]", "tests/test_schema.py::test_special_float_types[ConstrainedDecimalValue-expected_schema11]", "tests/test_schema.py::test_uuid_types[UUID-uuid]", "tests/test_schema.py::test_uuid_types[UUID1-uuid1]", "tests/test_schema.py::test_uuid_types[UUID3-uuid3]", "tests/test_schema.py::test_uuid_types[UUID4-uuid4]", "tests/test_schema.py::test_uuid_types[UUID5-uuid5]", "tests/test_schema.py::test_path_types[FilePath-file-path]", "tests/test_schema.py::test_path_types[DirectoryPath-directory-path]", "tests/test_schema.py::test_path_types[Path-path]", "tests/test_schema.py::test_json_type", "tests/test_schema.py::test_ipv4address_type", "tests/test_schema.py::test_ipv6address_type", "tests/test_schema.py::test_ipvanyaddress_type", "tests/test_schema.py::test_ipv4interface_type", "tests/test_schema.py::test_ipv6interface_type", "tests/test_schema.py::test_ipvanyinterface_type", "tests/test_schema.py::test_ipv4network_type", "tests/test_schema.py::test_ipv6network_type", "tests/test_schema.py::test_ipvanynetwork_type", "tests/test_schema.py::test_callable_type[type_0-default_value0]", "tests/test_schema.py::test_callable_type[type_1-<lambda>]", "tests/test_schema.py::test_callable_type[type_2-default_value2]", "tests/test_schema.py::test_callable_type[type_3-<lambda>]", "tests/test_schema.py::test_error_non_supported_types", "tests/test_schema.py::test_flat_models_unique_models", "tests/test_schema.py::test_flat_models_with_submodels", "tests/test_schema.py::test_flat_models_with_submodels_from_sequence", "tests/test_schema.py::test_model_name_maps", "tests/test_schema.py::test_schema_overrides", "tests/test_schema.py::test_schema_overrides_w_union", "tests/test_schema.py::test_schema_from_models", "tests/test_schema.py::test_schema_with_refs[#/components/schemas/-None]", "tests/test_schema.py::test_schema_with_refs[None-#/components/schemas/{model}]", "tests/test_schema.py::test_schema_with_refs[#/components/schemas/-#/{model}/schemas/]", "tests/test_schema.py::test_schema_with_custom_ref_template", "tests/test_schema.py::test_schema_ref_template_key_error", "tests/test_schema.py::test_schema_no_definitions", "tests/test_schema.py::test_list_default", "tests/test_schema.py::test_enum_str_default", "tests/test_schema.py::test_enum_int_default", "tests/test_schema.py::test_dict_default", "tests/test_schema.py::test_constraints_schema[kwargs0-str-expected_extra0]", "tests/test_schema.py::test_constraints_schema[kwargs1-ConstrainedStrValue-expected_extra1]", "tests/test_schema.py::test_constraints_schema[kwargs2-str-expected_extra2]", "tests/test_schema.py::test_constraints_schema[kwargs3-bytes-expected_extra3]", "tests/test_schema.py::test_constraints_schema[kwargs4-str-expected_extra4]", "tests/test_schema.py::test_constraints_schema[kwargs5-int-expected_extra5]", "tests/test_schema.py::test_constraints_schema[kwargs6-int-expected_extra6]", "tests/test_schema.py::test_constraints_schema[kwargs7-int-expected_extra7]", "tests/test_schema.py::test_constraints_schema[kwargs8-int-expected_extra8]", "tests/test_schema.py::test_constraints_schema[kwargs9-int-expected_extra9]", "tests/test_schema.py::test_constraints_schema[kwargs10-float-expected_extra10]", "tests/test_schema.py::test_constraints_schema[kwargs11-float-expected_extra11]", "tests/test_schema.py::test_constraints_schema[kwargs12-float-expected_extra12]", "tests/test_schema.py::test_constraints_schema[kwargs13-float-expected_extra13]", "tests/test_schema.py::test_constraints_schema[kwargs14-float-expected_extra14]", "tests/test_schema.py::test_constraints_schema[kwargs15-float-expected_extra15]", "tests/test_schema.py::test_constraints_schema[kwargs16-float-expected_extra16]", "tests/test_schema.py::test_constraints_schema[kwargs17-float-expected_extra17]", "tests/test_schema.py::test_constraints_schema[kwargs18-float-expected_extra18]", "tests/test_schema.py::test_constraints_schema[kwargs19-Decimal-expected_extra19]", "tests/test_schema.py::test_constraints_schema[kwargs20-Decimal-expected_extra20]", "tests/test_schema.py::test_constraints_schema[kwargs21-Decimal-expected_extra21]", "tests/test_schema.py::test_constraints_schema[kwargs22-Decimal-expected_extra22]", "tests/test_schema.py::test_constraints_schema[kwargs23-Decimal-expected_extra23]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs0-int]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs1-float]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs2-Decimal]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs3-bool]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs4-int]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs5-str]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs6-bytes]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs7-str]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs8-bool]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs9-type_9]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs10-type_10]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs11-ConstrainedListValue]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs12-ConstrainedSetValue]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs13-ConstrainedFrozenSetValue]", "tests/test_schema.py::test_constraints_schema_validation[kwargs0-str-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs1-str-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs2-bytes-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs3-str-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs4-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs5-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs6-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs7-int-2]", "tests/test_schema.py::test_constraints_schema_validation[kwargs8-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs9-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs10-int-5]", "tests/test_schema.py::test_constraints_schema_validation[kwargs11-float-3.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs12-float-2.1]", "tests/test_schema.py::test_constraints_schema_validation[kwargs13-float-3.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs14-float-4.9]", "tests/test_schema.py::test_constraints_schema_validation[kwargs15-float-3.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs16-float-2.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs17-float-3.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs18-float-5.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs19-float-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs20-float-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs21-Decimal-value21]", "tests/test_schema.py::test_constraints_schema_validation[kwargs22-Decimal-value22]", "tests/test_schema.py::test_constraints_schema_validation[kwargs23-Decimal-value23]", "tests/test_schema.py::test_constraints_schema_validation[kwargs24-Decimal-value24]", "tests/test_schema.py::test_constraints_schema_validation[kwargs25-Decimal-value25]", "tests/test_schema.py::test_constraints_schema_validation[kwargs26-Decimal-value26]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs0-str-foobar]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs1-str-f]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs2-str-bar]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs3-int-2]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs4-int-5]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs5-int-1]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs6-int-6]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs7-float-2.0]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs8-float-5.0]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs9-float-1.9]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs10-float-5.1]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs11-Decimal-value11]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs12-Decimal-value12]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs13-Decimal-value13]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs14-Decimal-value14]", "tests/test_schema.py::test_schema_kwargs", "tests/test_schema.py::test_schema_dict_constr", "tests/test_schema.py::test_bytes_constrained_types[ConstrainedBytes-expected_schema0]", "tests/test_schema.py::test_bytes_constrained_types[ConstrainedBytesValue-expected_schema1]", "tests/test_schema.py::test_optional_dict", "tests/test_schema.py::test_optional_validator", "tests/test_schema.py::test_field_with_validator", "tests/test_schema.py::test_unparameterized_schema_generation", "tests/test_schema.py::test_known_model_optimization", "tests/test_schema.py::test_root", "tests/test_schema.py::test_root_list", "tests/test_schema.py::test_root_nested_model", "tests/test_schema.py::test_new_type_schema", "tests/test_schema.py::test_literal_schema", "tests/test_schema.py::test_literal_enum", "tests/test_schema.py::test_color_type", "tests/test_schema.py::test_model_with_schema_extra", "tests/test_schema.py::test_model_with_schema_extra_callable", "tests/test_schema.py::test_model_with_schema_extra_callable_no_model_class", "tests/test_schema.py::test_model_with_schema_extra_callable_classmethod", "tests/test_schema.py::test_model_with_schema_extra_callable_instance_method", "tests/test_schema.py::test_model_with_extra_forbidden", "tests/test_schema.py::test_enforced_constraints[int-kwargs0-field_schema0]", "tests/test_schema.py::test_enforced_constraints[annotation1-kwargs1-field_schema1]", "tests/test_schema.py::test_enforced_constraints[annotation2-kwargs2-field_schema2]", "tests/test_schema.py::test_enforced_constraints[annotation3-kwargs3-field_schema3]", "tests/test_schema.py::test_enforced_constraints[annotation4-kwargs4-field_schema4]", "tests/test_schema.py::test_enforced_constraints[annotation5-kwargs5-field_schema5]", "tests/test_schema.py::test_enforced_constraints[annotation6-kwargs6-field_schema6]", "tests/test_schema.py::test_enforced_constraints[annotation7-kwargs7-field_schema7]", "tests/test_schema.py::test_real_vs_phony_constraints", "tests/test_schema.py::test_subfield_field_info", "tests/test_schema.py::test_dataclass", "tests/test_schema.py::test_schema_attributes", "tests/test_schema.py::test_model_process_schema_enum", "tests/test_schema.py::test_path_modify_schema", "tests/test_schema.py::test_frozen_set", "tests/test_schema.py::test_iterable", "tests/test_schema.py::test_new_type", "tests/test_schema.py::test_multiple_models_with_same_name", "tests/test_schema.py::test_multiple_enums_with_same_name", "tests/test_schema.py::test_schema_for_generic_field", "tests/test_schema.py::test_namedtuple_default", "tests/test_schema.py::test_advanced_generic_schema", "tests/test_schema.py::test_nested_generic", "tests/test_schema.py::test_nested_generic_model", "tests/test_schema.py::test_complex_nested_generic", "tests/test_schema.py::test_schema_with_field_parameter", "tests/test_schema.py::test_nested_python_dataclasses", "tests/test_schema.py::test_extra_inheritance" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2022-08-06 03:31:20+00:00
mit
4,870
pydantic__pydantic-4350
diff --git a/pydantic/config.py b/pydantic/config.py --- a/pydantic/config.py +++ b/pydantic/config.py @@ -2,6 +2,8 @@ from enum import Enum from typing import TYPE_CHECKING, Any, Callable, Dict, ForwardRef, Optional, Tuple, Type, Union +from typing_extensions import Literal, Protocol + from .typing import AnyCallable from .utils import GetterDict from .version import compiled @@ -9,14 +11,12 @@ 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): + class SchemaExtraCallable(Protocol): @overload def __call__(self, schema: Dict[str, Any]) -> None: pass @@ -40,7 +40,7 @@ class Extra(str, Enum): # https://github.com/cython/cython/issues/4003 # Will be fixed with Cython 3 but still in alpha right now if not compiled: - from typing_extensions import Literal, TypedDict + from typing_extensions import TypedDict class ConfigDict(TypedDict, total=False): title: Optional[str] @@ -103,8 +103,10 @@ class BaseConfig: json_encoders: Dict[Union[Type[Any], str, ForwardRef], AnyCallable] = {} underscore_attrs_are_private: bool = False - # whether inherited models as fields should be reconstructed as base model - copy_on_model_validation: bool = True + # whether inherited models as fields should be reconstructed as base model, + # and whether such a copy should be shallow or deep + copy_on_model_validation: Literal['none', 'deep', 'shallow'] = 'shallow' + # whether `Union` should check all allowed types before even trying to coerce smart_union: bool = False # whether dataclass `__post_init__` should be run before or after validation diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -679,10 +679,28 @@ def __get_validators__(cls) -> 'CallableGenerator': @classmethod def validate(cls: Type['Model'], value: Any) -> 'Model': if isinstance(value, cls): - if cls.__config__.copy_on_model_validation: - return value._copy_and_set_values(value.__dict__, value.__fields_set__, deep=True) - else: + copy_on_model_validation = cls.__config__.copy_on_model_validation + # whether to deep or shallow copy the model on validation, None means do not copy + deep_copy: Optional[bool] = None + if copy_on_model_validation not in {'deep', 'shallow', 'none'}: + # Warn about deprecated behavior + warnings.warn( + "`copy_on_model_validation` should be a string: 'deep', 'shallow' or 'none'", DeprecationWarning + ) + if copy_on_model_validation: + deep_copy = False + + if copy_on_model_validation == 'shallow': + # shallow copy + deep_copy = False + elif copy_on_model_validation == 'deep': + # deep copy + deep_copy = True + + if deep_copy is None: return value + else: + return value._copy_and_set_values(value.__dict__, value.__fields_set__, deep=deep_copy) value = cls._enforce_dict_if_root(value) diff --git a/pydantic/version.py b/pydantic/version.py --- a/pydantic/version.py +++ b/pydantic/version.py @@ -1,6 +1,6 @@ __all__ = 'compiled', 'VERSION', 'version_info' -VERSION = '1.9.0' +VERSION = '1.9.2' try: import cython # type: ignore
pydantic/pydantic
9599a3d25643751e114b874a9b8e630cf031417c
diff --git a/tests/test_main.py b/tests/test_main.py --- a/tests/test_main.py +++ b/tests/test_main.py @@ -1561,18 +1561,66 @@ class Config: assert t.user is not my_user assert t.user.hobbies == ['scuba diving'] - assert t.user.hobbies is not my_user.hobbies # `Config.copy_on_model_validation` does a deep copy + assert t.user.hobbies is my_user.hobbies # `Config.copy_on_model_validation` does a shallow copy assert t.user._priv == 13 assert t.user.password.get_secret_value() == 'hashedpassword' assert t.dict() == {'id': '1234567890', 'user': {'id': 42, 'hobbies': ['scuba diving']}} +def test_model_exclude_copy_on_model_validation_shallow(): + """When `Config.copy_on_model_validation` is set and `Config.copy_on_model_validation_shallow` is set, + do the same as the previous test but perform a shallow copy""" + + class User(BaseModel): + class Config: + copy_on_model_validation = 'shallow' + + hobbies: List[str] + + my_user = User(hobbies=['scuba diving']) + + class Transaction(BaseModel): + user: User = Field(...) + + t = Transaction(user=my_user) + + assert t.user is not my_user + assert t.user.hobbies is my_user.hobbies # unlike above, this should be a shallow copy + + [email protected]('comv_value', [True, False]) +def test_copy_on_model_validation_warning(comv_value): + class User(BaseModel): + class Config: + # True interpreted as 'shallow', False interpreted as 'none' + copy_on_model_validation = comv_value + + hobbies: List[str] + + my_user = User(hobbies=['scuba diving']) + + class Transaction(BaseModel): + user: User + + with pytest.warns(DeprecationWarning, match="`copy_on_model_validation` should be a string: 'deep', 'shallow' or"): + t = Transaction(user=my_user) + + if comv_value: + assert t.user is not my_user + else: + assert t.user is my_user + assert t.user.hobbies is my_user.hobbies + + def test_validation_deep_copy(): """By default, Config.copy_on_model_validation should do a deep copy""" class A(BaseModel): name: str + class Config: + copy_on_model_validation = 'deep' + class B(BaseModel): list_a: List[A] @@ -1986,7 +2034,7 @@ def __hash__(self): return id(self) class Config: - copy_on_model_validation = False + copy_on_model_validation = 'none' class Item(BaseModel): images: List[Image]
v1.9.1 release missing from `HISTORY.md` on `master` The latest version of Pydantic is v1.9.1, however the most recent version mentioned in the HISTORY.md file on `master` is v1.9.0: https://github.com/samuelcolvin/pydantic/blob/9a0ae097bfdefa9bfb41e19d71a5001fe8240e36/HISTORY.md It seems the new changelog entry for 1.9.1 was only added to the 1.9.1 tag/branch: https://github.com/samuelcolvin/pydantic/blob/v1.9.1/HISTORY.md#v191-2022-05-19 ...however that tag is not what people see when first navigating to the repo to find out recent changes :-)
0.0
9599a3d25643751e114b874a9b8e630cf031417c
[ "tests/test_main.py::test_model_exclude_copy_on_model_validation", "tests/test_main.py::test_model_exclude_copy_on_model_validation_shallow", "tests/test_main.py::test_copy_on_model_validation_warning[True]", "tests/test_main.py::test_copy_on_model_validation_warning[False]", "tests/test_main.py::test_inherited_model_field_untouched" ]
[ "tests/test_main.py::test_success", "tests/test_main.py::test_ultra_simple_missing", "tests/test_main.py::test_ultra_simple_failed", "tests/test_main.py::test_ultra_simple_repr", "tests/test_main.py::test_default_factory_field", "tests/test_main.py::test_default_factory_no_type_field", "tests/test_main.py::test_comparing", "tests/test_main.py::test_nullable_strings_success", "tests/test_main.py::test_nullable_strings_fails", "tests/test_main.py::test_recursion", "tests/test_main.py::test_recursion_fails", "tests/test_main.py::test_not_required", "tests/test_main.py::test_infer_type", "tests/test_main.py::test_allow_extra", "tests/test_main.py::test_allow_extra_repr", "tests/test_main.py::test_forbidden_extra_success", "tests/test_main.py::test_forbidden_extra_fails", "tests/test_main.py::test_disallow_mutation", "tests/test_main.py::test_extra_allowed", "tests/test_main.py::test_extra_ignored", "tests/test_main.py::test_set_attr", "tests/test_main.py::test_set_attr_invalid", "tests/test_main.py::test_any", "tests/test_main.py::test_alias", "tests/test_main.py::test_population_by_field_name", "tests/test_main.py::test_field_order", "tests/test_main.py::test_required", "tests/test_main.py::test_mutability", "tests/test_main.py::test_immutability[False-False]", "tests/test_main.py::test_immutability[False-True]", "tests/test_main.py::test_immutability[True-True]", "tests/test_main.py::test_not_frozen_are_not_hashable", "tests/test_main.py::test_with_declared_hash", "tests/test_main.py::test_frozen_with_hashable_fields_are_hashable", "tests/test_main.py::test_frozen_with_unhashable_fields_are_not_hashable", "tests/test_main.py::test_hash_function_give_different_result_for_different_object", "tests/test_main.py::test_const_validates", "tests/test_main.py::test_const_uses_default", "tests/test_main.py::test_const_validates_after_type_validators", "tests/test_main.py::test_const_with_wrong_value", "tests/test_main.py::test_const_with_validator", "tests/test_main.py::test_const_list", "tests/test_main.py::test_const_list_with_wrong_value", "tests/test_main.py::test_const_validation_json_serializable", "tests/test_main.py::test_validating_assignment_pass", "tests/test_main.py::test_validating_assignment_fail", "tests/test_main.py::test_validating_assignment_pre_root_validator_fail", "tests/test_main.py::test_validating_assignment_post_root_validator_fail", "tests/test_main.py::test_root_validator_many_values_change", "tests/test_main.py::test_enum_values", "tests/test_main.py::test_literal_enum_values", "tests/test_main.py::test_enum_raw", "tests/test_main.py::test_set_tuple_values", "tests/test_main.py::test_default_copy", "tests/test_main.py::test_arbitrary_type_allowed_validation_success", "tests/test_main.py::test_arbitrary_type_allowed_validation_fails", "tests/test_main.py::test_arbitrary_types_not_allowed", "tests/test_main.py::test_type_type_validation_success", "tests/test_main.py::test_type_type_subclass_validation_success", "tests/test_main.py::test_type_type_validation_fails_for_instance", "tests/test_main.py::test_type_type_validation_fails_for_basic_type", "tests/test_main.py::test_bare_type_type_validation_success", "tests/test_main.py::test_bare_type_type_validation_fails", "tests/test_main.py::test_annotation_field_name_shadows_attribute", "tests/test_main.py::test_value_field_name_shadows_attribute", "tests/test_main.py::test_class_var", "tests/test_main.py::test_fields_set", "tests/test_main.py::test_exclude_unset_dict", "tests/test_main.py::test_exclude_unset_recursive", "tests/test_main.py::test_dict_exclude_unset_populated_by_alias", "tests/test_main.py::test_dict_exclude_unset_populated_by_alias_with_extra", "tests/test_main.py::test_exclude_defaults", "tests/test_main.py::test_dir_fields", "tests/test_main.py::test_dict_with_extra_keys", "tests/test_main.py::test_root", "tests/test_main.py::test_root_list", "tests/test_main.py::test_root_nested", "tests/test_main.py::test_encode_nested_root", "tests/test_main.py::test_root_failed", "tests/test_main.py::test_root_undefined_failed", "tests/test_main.py::test_parse_root_as_mapping", "tests/test_main.py::test_parse_obj_non_mapping_root", "tests/test_main.py::test_parse_obj_nested_root", "tests/test_main.py::test_untouched_types", "tests/test_main.py::test_custom_types_fail_without_keep_untouched", "tests/test_main.py::test_model_iteration", "tests/test_main.py::test_model_export_nested_list[excluding", "tests/test_main.py::test_model_export_nested_list[should", "tests/test_main.py::test_model_export_nested_list[using", "tests/test_main.py::test_model_export_dict_exclusion[excluding", "tests/test_main.py::test_model_export_dict_exclusion[using", "tests/test_main.py::test_model_export_dict_exclusion[exclude", "tests/test_main.py::test_model_exclude_config_field_merging", "tests/test_main.py::test_validation_deep_copy", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[None-expected0-kinds0]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[None-expected0-kinds1]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[None-expected0-kinds2]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[None-expected0-kinds3]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[None-expected0-kinds4]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[None-expected0-kinds5]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[None-expected0-kinds6]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude1-expected1-kinds0]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude1-expected1-kinds1]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude1-expected1-kinds2]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude1-expected1-kinds3]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude1-expected1-kinds4]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude1-expected1-kinds5]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude1-expected1-kinds6]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude2-expected2-kinds0]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude2-expected2-kinds1]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude2-expected2-kinds2]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude2-expected2-kinds3]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude2-expected2-kinds4]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude2-expected2-kinds5]", "tests/test_main.py::test_model_export_exclusion_with_fields_and_config[exclude2-expected2-kinds6]", "tests/test_main.py::test_model_export_exclusion_inheritance", "tests/test_main.py::test_model_export_with_true_instead_of_ellipsis", "tests/test_main.py::test_model_export_inclusion", "tests/test_main.py::test_model_export_inclusion_inheritance", "tests/test_main.py::test_custom_init_subclass_params", "tests/test_main.py::test_update_forward_refs_does_not_modify_module_dict", "tests/test_main.py::test_two_defaults", "tests/test_main.py::test_default_factory", "tests/test_main.py::test_default_factory_called_once", "tests/test_main.py::test_default_factory_called_once_2", "tests/test_main.py::test_default_factory_validate_children", "tests/test_main.py::test_default_factory_parse", "tests/test_main.py::test_none_min_max_items", "tests/test_main.py::test_reuse_same_field", "tests/test_main.py::test_base_config_type_hinting", "tests/test_main.py::test_allow_mutation_field", "tests/test_main.py::test_repr_field", "tests/test_main.py::test_inherited_model_field_copy", "tests/test_main.py::test_mapping_retains_type_subclass", "tests/test_main.py::test_mapping_retains_type_defaultdict", "tests/test_main.py::test_mapping_retains_type_fallback_error", "tests/test_main.py::test_typing_coercion_dict", "tests/test_main.py::test_typing_non_coercion_of_dict_subclasses", "tests/test_main.py::test_typing_coercion_defaultdict", "tests/test_main.py::test_typing_coercion_counter", "tests/test_main.py::test_typing_counter_value_validation", "tests/test_main.py::test_class_kwargs_config", "tests/test_main.py::test_class_kwargs_config_json_encoders", "tests/test_main.py::test_class_kwargs_config_and_attr_conflict", "tests/test_main.py::test_class_kwargs_custom_config", "tests/test_main.py::test_final_field_decl_withou_default_val[none-no-arg]", "tests/test_main.py::test_final_field_decl_withou_default_val[none-with-arg]", "tests/test_main.py::test_final_field_decl_withou_default_val[field-no-arg]", "tests/test_main.py::test_final_field_decl_withou_default_val[field-with-arg]", "tests/test_main.py::test_final_field_decl_with_default_val[no-arg]", "tests/test_main.py::test_final_field_decl_with_default_val[with-arg]", "tests/test_main.py::test_final_field_reassignment", "tests/test_main.py::test_field_by_default_is_not_final" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2022-08-08 15:01:50+00:00
mit
4,871
pydantic__pydantic-4354
diff --git a/pydantic/dataclasses.py b/pydantic/dataclasses.py --- a/pydantic/dataclasses.py +++ b/pydantic/dataclasses.py @@ -385,6 +385,10 @@ def create_pydantic_model_from_dataclass( def _dataclass_validate_values(self: 'Dataclass') -> None: + # validation errors can occur if this function is called twice on an already initialised dataclass. + # for example if Extra.forbid is enabled, it would consider __pydantic_initialised__ an invalid extra property + if getattr(self, '__pydantic_initialised__'): + return if getattr(self, '__pydantic_has_field_info_default__', False): # We need to remove `FieldInfo` values since they are not valid as input # It's ok to do that because they are obviously the default values!
pydantic/pydantic
f6c74a55d5b272add88d4cbe2efa46c4abc1760f
Very good catch, thank you @DetachHead.
diff --git a/tests/test_dataclasses.py b/tests/test_dataclasses.py --- a/tests/test_dataclasses.py +++ b/tests/test_dataclasses.py @@ -1360,3 +1360,27 @@ class A: A(1, '') assert A(b='hi').b == 'hi' + + +def test_extra_forbid_list_no_error(): + @pydantic.dataclasses.dataclass(config=dict(extra=Extra.forbid)) + class Bar: + ... + + @pydantic.dataclasses.dataclass + class Foo: + a: List[Bar] + + assert isinstance(Foo(a=[Bar()]).a[0], Bar) + + +def test_extra_forbid_list_error(): + @pydantic.dataclasses.dataclass(config=dict(extra=Extra.forbid)) + class Bar: + ... + + with pytest.raises(TypeError, match=re.escape("__init__() got an unexpected keyword argument 'a'")): + + @pydantic.dataclasses.dataclass + class Foo: + a: List[Bar(a=1)]
"extra fields not permitted" error when using `Extra.forbid` on `dataclass` property that's a `dict` or `list` of another `dataclass` ### Initial Checks - [X] I have searched GitHub for a duplicate issue and I'm sure this is something new - [X] I have searched Google & StackOverflow for a solution and couldn't find anything - [X] I have read and followed [the docs](https://pydantic-docs.helpmanual.io) and still think this is a bug - [X] I am confident that the issue is with pydantic (not my code, or another library in the ecosystem like [FastAPI](https://fastapi.tiangolo.com) or [mypy](https://mypy.readthedocs.io/en/stable)) ### Description when instanciating a `dataclass` where a property is a `list` or `dict` of another `dataclass`, it causes this error: > extra fields not permitted (type=value_error.extra) ### Example Code ```Python from pydantic import Extra from pydantic.dataclasses import dataclass class ExtraPropertiesForbidden: extra = Extra.forbid @dataclass(config=ExtraPropertiesForbidden) class Bar: ... @dataclass(config=ExtraPropertiesForbidden) class Foo: a: list[Bar] a = Foo(a=[Bar()]) # error: extra fields not permitted (type=value_error.extra) ``` ### Python, Pydantic & OS Version this issue seems to have been introduced after the 1.9.1 release. this occurred after installing the latest commit from master: ``` pip uninstall pydantic pip install git+https://github.com/samuelcolvin/pydantic.git@a69136d2096e327ed48954a298c775dceb1551d1 ``` ```Text pydantic version: 1.9.0 pydantic compiled: False install path: C:\Users\chungus\AppData\Local\pypoetry\Cache\virtualenvs\project-e01-Hfn1-py3.10\Lib\site-packages\pydantic python version: 3.10.6 (tags/v3.10.6:9c7b4bd, Aug 1 2022, 21:53:49) [MSC v.1932 64 bit (AMD64)] platform: Windows-10-10.0.19042-SP0 optional deps. installed: ['typing-extensions'] ``` ### Affected Components - [ ] [Compatibility between releases](https://pydantic-docs.helpmanual.io/changelog/) - [ ] [Data validation/parsing](https://pydantic-docs.helpmanual.io/usage/models/#basic-model-usage) - [ ] [Data serialization](https://pydantic-docs.helpmanual.io/usage/exporting_models/) - `.dict()` and `.json()` - [ ] [JSON Schema](https://pydantic-docs.helpmanual.io/usage/schema/) - [X] [Dataclasses](https://pydantic-docs.helpmanual.io/usage/dataclasses/) - [X] [Model Config](https://pydantic-docs.helpmanual.io/usage/model_config/) - [ ] [Field Types](https://pydantic-docs.helpmanual.io/usage/types/) - adding or changing a particular data type - [ ] [Function validation decorator](https://pydantic-docs.helpmanual.io/usage/validation_decorator/) - [ ] [Generic Models](https://pydantic-docs.helpmanual.io/usage/models/#generic-models) - [ ] [Other Model behaviour](https://pydantic-docs.helpmanual.io/usage/models/) - `construct()`, pickling, private attributes, ORM mode - [ ] [Settings Management](https://pydantic-docs.helpmanual.io/usage/settings/) - [ ] [Plugins](https://pydantic-docs.helpmanual.io/) and integration with other tools - mypy, FastAPI, python-devtools, Hypothesis, VS Code, PyCharm, etc.
0.0
f6c74a55d5b272add88d4cbe2efa46c4abc1760f
[ "tests/test_dataclasses.py::test_extra_forbid_list_no_error" ]
[ "tests/test_dataclasses.py::test_simple", "tests/test_dataclasses.py::test_model_name", "tests/test_dataclasses.py::test_value_error", "tests/test_dataclasses.py::test_frozen", "tests/test_dataclasses.py::test_validate_assignment", "tests/test_dataclasses.py::test_validate_assignment_error", "tests/test_dataclasses.py::test_not_validate_assignment", "tests/test_dataclasses.py::test_validate_assignment_value_change", "tests/test_dataclasses.py::test_validate_assignment_extra", "tests/test_dataclasses.py::test_post_init", "tests/test_dataclasses.py::test_post_init_validation", "tests/test_dataclasses.py::test_post_init_inheritance_chain", "tests/test_dataclasses.py::test_post_init_post_parse", "tests/test_dataclasses.py::test_post_init_post_parse_types", "tests/test_dataclasses.py::test_post_init_assignment", "tests/test_dataclasses.py::test_inheritance", "tests/test_dataclasses.py::test_validate_long_string_error", "tests/test_dataclasses.py::test_validate_assigment_long_string_error", "tests/test_dataclasses.py::test_no_validate_assigment_long_string_error", "tests/test_dataclasses.py::test_nested_dataclass", "tests/test_dataclasses.py::test_arbitrary_types_allowed", "tests/test_dataclasses.py::test_nested_dataclass_model", "tests/test_dataclasses.py::test_fields", "tests/test_dataclasses.py::test_default_factory_field", "tests/test_dataclasses.py::test_default_factory_singleton_field", "tests/test_dataclasses.py::test_schema", "tests/test_dataclasses.py::test_nested_schema", "tests/test_dataclasses.py::test_initvar", "tests/test_dataclasses.py::test_derived_field_from_initvar", "tests/test_dataclasses.py::test_initvars_post_init", "tests/test_dataclasses.py::test_initvars_post_init_post_parse", "tests/test_dataclasses.py::test_classvar", "tests/test_dataclasses.py::test_frozenset_field", "tests/test_dataclasses.py::test_inheritance_post_init", "tests/test_dataclasses.py::test_hashable_required", "tests/test_dataclasses.py::test_hashable_optional[1]", "tests/test_dataclasses.py::test_hashable_optional[None]", "tests/test_dataclasses.py::test_hashable_optional[default2]", "tests/test_dataclasses.py::test_override_builtin_dataclass", "tests/test_dataclasses.py::test_override_builtin_dataclass_2", "tests/test_dataclasses.py::test_override_builtin_dataclass_nested", "tests/test_dataclasses.py::test_override_builtin_dataclass_nested_schema", "tests/test_dataclasses.py::test_inherit_builtin_dataclass", "tests/test_dataclasses.py::test_dataclass_arbitrary", "tests/test_dataclasses.py::test_forward_stdlib_dataclass_params", "tests/test_dataclasses.py::test_pydantic_callable_field", "tests/test_dataclasses.py::test_pickle_overriden_builtin_dataclass", "tests/test_dataclasses.py::test_config_field_info_create_model", "tests/test_dataclasses.py::test_issue_2162[foo0-bar0]", "tests/test_dataclasses.py::test_issue_2162[foo1-bar1]", "tests/test_dataclasses.py::test_issue_2162[foo2-bar2]", "tests/test_dataclasses.py::test_issue_2162[foo3-bar3]", "tests/test_dataclasses.py::test_issue_2383", "tests/test_dataclasses.py::test_issue_2398", "tests/test_dataclasses.py::test_issue_2424", "tests/test_dataclasses.py::test_issue_2541", "tests/test_dataclasses.py::test_issue_2555", "tests/test_dataclasses.py::test_issue_2594", "tests/test_dataclasses.py::test_schema_description_unset", "tests/test_dataclasses.py::test_schema_description_set", "tests/test_dataclasses.py::test_issue_3011", "tests/test_dataclasses.py::test_issue_3162", "tests/test_dataclasses.py::test_discrimated_union_basemodel_instance_value", "tests/test_dataclasses.py::test_post_init_after_validation", "tests/test_dataclasses.py::test_keeps_custom_properties", "tests/test_dataclasses.py::test_ignore_extra", "tests/test_dataclasses.py::test_ignore_extra_subclass", "tests/test_dataclasses.py::test_allow_extra", "tests/test_dataclasses.py::test_allow_extra_subclass", "tests/test_dataclasses.py::test_forbid_extra", "tests/test_dataclasses.py::test_post_init_allow_extra", "tests/test_dataclasses.py::test_self_reference_dataclass", "tests/test_dataclasses.py::test_extra_forbid_list_error" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_git_commit_hash", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2022-08-09 00:38:49+00:00
mit
4,872
pydantic__pydantic-4361
diff --git a/pydantic/dataclasses.py b/pydantic/dataclasses.py --- a/pydantic/dataclasses.py +++ b/pydantic/dataclasses.py @@ -310,8 +310,7 @@ def new_init(self: 'Dataclass', *args: Any, **kwargs: Any) -> None: # set arg value by default initvars_and_values[f.name] = args[i] except IndexError: - initvars_and_values[f.name] = f.default - initvars_and_values.update(kwargs) + initvars_and_values[f.name] = kwargs.get(f.name, f.default) self.__post_init_post_parse__(**initvars_and_values)
pydantic/pydantic
11d8589423ac82f64eb4007bdad824f4a6217434
I can confirm the error. It seems we have the problem because [we update the initvars_and_values by kwargs](https://github.com/samuelcolvin/pydantic/blob/a69136d2096e327ed48954a298c775dceb1551d1/pydantic/dataclasses.py#L263) that I am not sure is the right behavior or not. @samuelcolvin what do you think? https://github.com/samuelcolvin/pydantic/blob/a69136d2096e327ed48954a298c775dceb1551d1/pydantic/dataclasses.py#L263
diff --git a/tests/test_dataclasses.py b/tests/test_dataclasses.py --- a/tests/test_dataclasses.py +++ b/tests/test_dataclasses.py @@ -600,6 +600,17 @@ def __post_init_post_parse__(self, base_path): assert PathDataPostInitPostParse('world', base_path='/hello').path == Path('/hello/world') +def test_post_init_post_parse_without_initvars(): + @pydantic.dataclasses.dataclass + class Foo: + a: int + + def __post_init_post_parse__(self): + ... + + Foo(a=1) + + def test_classvar(): @pydantic.dataclasses.dataclass class TestClassVar:
`__post_init_post_parse__` is incorrectly passed keyword arguments when no `__post_init__` is defined ### Initial Checks - [X] I have searched GitHub for a duplicate issue and I'm sure this is something new - [X] I have searched Google & StackOverflow for a solution and couldn't find anything - [X] I have read and followed [the docs](https://pydantic-docs.helpmanual.io) and still think this is a bug - [X] I am confident that the issue is with pydantic (not my code, or another library in the ecosystem like [FastAPI](https://fastapi.tiangolo.com) or [mypy](https://mypy.readthedocs.io/en/stable)) ### Description when a `__post_init_post_parse__` method is defined on a `dataclass` without a `__post_init__`, it incorrectly passes keyword args to it, when the args are not annotated with `InitVar` as specified in [the docs](https://pydantic-docs.helpmanual.io/usage/dataclasses/#initialize-hooks) ### Example Code ```Python from pydantic.dataclasses import dataclass @dataclass class Foo: a: int # uncomment this and the error goes away # def __post_init__(self): # ... def __post_init_post_parse__(self): # TypeError: Foo.__post_init_post_parse__() got an unexpected keyword argument 'a' ... a = Foo(a=1) ``` ### Python, Pydantic & OS Version this issue seems to have been introduced after the 1.9.1 release. this occurred after installing the latest commit from master: ``` pip uninstall pydantic pip install git+https://github.com/samuelcolvin/pydantic.git@a69136d2096e327ed48954a298c775dceb1551d1 ``` ```Text pydantic version: 1.9.0 pydantic compiled: False install path: C:\Users\chungus\AppData\Local\pypoetry\Cache\virtualenvs\project-e01-Hfn1-py3.10\Lib\site-packages\pydantic python version: 3.10.6 (tags/v3.10.6:9c7b4bd, Aug 1 2022, 21:53:49) [MSC v.1932 64 bit (AMD64)] platform: Windows-10-10.0.19042-SP0 optional deps. installed: ['typing-extensions'] ``` ### Affected Components - [ ] [Compatibility between releases](https://pydantic-docs.helpmanual.io/changelog/) - [ ] [Data validation/parsing](https://pydantic-docs.helpmanual.io/usage/models/#basic-model-usage) - [ ] [Data serialization](https://pydantic-docs.helpmanual.io/usage/exporting_models/) - `.dict()` and `.json()` - [ ] [JSON Schema](https://pydantic-docs.helpmanual.io/usage/schema/) - [X] [Dataclasses](https://pydantic-docs.helpmanual.io/usage/dataclasses/) - [ ] [Model Config](https://pydantic-docs.helpmanual.io/usage/model_config/) - [ ] [Field Types](https://pydantic-docs.helpmanual.io/usage/types/) - adding or changing a particular data type - [ ] [Function validation decorator](https://pydantic-docs.helpmanual.io/usage/validation_decorator/) - [ ] [Generic Models](https://pydantic-docs.helpmanual.io/usage/models/#generic-models) - [ ] [Other Model behaviour](https://pydantic-docs.helpmanual.io/usage/models/) - `construct()`, pickling, private attributes, ORM mode - [ ] [Settings Management](https://pydantic-docs.helpmanual.io/usage/settings/) - [ ] [Plugins](https://pydantic-docs.helpmanual.io/) and integration with other tools - mypy, FastAPI, python-devtools, Hypothesis, VS Code, PyCharm, etc.
0.0
11d8589423ac82f64eb4007bdad824f4a6217434
[ "tests/test_dataclasses.py::test_post_init_post_parse_without_initvars" ]
[ "tests/test_dataclasses.py::test_simple", "tests/test_dataclasses.py::test_model_name", "tests/test_dataclasses.py::test_value_error", "tests/test_dataclasses.py::test_frozen", "tests/test_dataclasses.py::test_validate_assignment", "tests/test_dataclasses.py::test_validate_assignment_error", "tests/test_dataclasses.py::test_not_validate_assignment", "tests/test_dataclasses.py::test_validate_assignment_value_change", "tests/test_dataclasses.py::test_validate_assignment_extra", "tests/test_dataclasses.py::test_post_init", "tests/test_dataclasses.py::test_post_init_validation", "tests/test_dataclasses.py::test_post_init_inheritance_chain", "tests/test_dataclasses.py::test_post_init_post_parse", "tests/test_dataclasses.py::test_post_init_post_parse_types", "tests/test_dataclasses.py::test_post_init_assignment", "tests/test_dataclasses.py::test_inheritance", "tests/test_dataclasses.py::test_validate_long_string_error", "tests/test_dataclasses.py::test_validate_assigment_long_string_error", "tests/test_dataclasses.py::test_no_validate_assigment_long_string_error", "tests/test_dataclasses.py::test_nested_dataclass", "tests/test_dataclasses.py::test_arbitrary_types_allowed", "tests/test_dataclasses.py::test_nested_dataclass_model", "tests/test_dataclasses.py::test_fields", "tests/test_dataclasses.py::test_default_factory_field", "tests/test_dataclasses.py::test_default_factory_singleton_field", "tests/test_dataclasses.py::test_schema", "tests/test_dataclasses.py::test_nested_schema", "tests/test_dataclasses.py::test_initvar", "tests/test_dataclasses.py::test_derived_field_from_initvar", "tests/test_dataclasses.py::test_initvars_post_init", "tests/test_dataclasses.py::test_initvars_post_init_post_parse", "tests/test_dataclasses.py::test_classvar", "tests/test_dataclasses.py::test_frozenset_field", "tests/test_dataclasses.py::test_inheritance_post_init", "tests/test_dataclasses.py::test_hashable_required", "tests/test_dataclasses.py::test_hashable_optional[1]", "tests/test_dataclasses.py::test_hashable_optional[None]", "tests/test_dataclasses.py::test_hashable_optional[default2]", "tests/test_dataclasses.py::test_override_builtin_dataclass", "tests/test_dataclasses.py::test_override_builtin_dataclass_2", "tests/test_dataclasses.py::test_override_builtin_dataclass_nested", "tests/test_dataclasses.py::test_override_builtin_dataclass_nested_schema", "tests/test_dataclasses.py::test_inherit_builtin_dataclass", "tests/test_dataclasses.py::test_dataclass_arbitrary", "tests/test_dataclasses.py::test_forward_stdlib_dataclass_params", "tests/test_dataclasses.py::test_pydantic_callable_field", "tests/test_dataclasses.py::test_pickle_overriden_builtin_dataclass", "tests/test_dataclasses.py::test_config_field_info_create_model", "tests/test_dataclasses.py::test_issue_2162[foo0-bar0]", "tests/test_dataclasses.py::test_issue_2162[foo1-bar1]", "tests/test_dataclasses.py::test_issue_2162[foo2-bar2]", "tests/test_dataclasses.py::test_issue_2162[foo3-bar3]", "tests/test_dataclasses.py::test_issue_2383", "tests/test_dataclasses.py::test_issue_2398", "tests/test_dataclasses.py::test_issue_2424", "tests/test_dataclasses.py::test_issue_2541", "tests/test_dataclasses.py::test_issue_2555", "tests/test_dataclasses.py::test_issue_2594", "tests/test_dataclasses.py::test_schema_description_unset", "tests/test_dataclasses.py::test_schema_description_set", "tests/test_dataclasses.py::test_issue_3011", "tests/test_dataclasses.py::test_issue_3162", "tests/test_dataclasses.py::test_discrimated_union_basemodel_instance_value", "tests/test_dataclasses.py::test_post_init_after_validation", "tests/test_dataclasses.py::test_keeps_custom_properties", "tests/test_dataclasses.py::test_ignore_extra", "tests/test_dataclasses.py::test_ignore_extra_subclass", "tests/test_dataclasses.py::test_allow_extra", "tests/test_dataclasses.py::test_allow_extra_subclass", "tests/test_dataclasses.py::test_forbid_extra", "tests/test_dataclasses.py::test_post_init_allow_extra", "tests/test_dataclasses.py::test_self_reference_dataclass" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_git_commit_hash" ], "has_test_patch": true, "is_lite": false }
2022-08-09 22:22:05+00:00
mit
4,873
pydantic__pydantic-4383
diff --git a/pydantic/schema.py b/pydantic/schema.py --- a/pydantic/schema.py +++ b/pydantic/schema.py @@ -57,6 +57,7 @@ ConstrainedStr, SecretBytes, SecretStr, + StrictBytes, conbytes, condecimal, confloat, @@ -1087,7 +1088,13 @@ def constraint_func(**kw: Any) -> Type[Any]: constraint_func = constr elif issubclass(type_, bytes): attrs = ('max_length', 'min_length', 'regex') - constraint_func = conbytes + if issubclass(type_, StrictBytes): + + def constraint_func(**kw: Any) -> Type[Any]: + return type(type_.__name__, (type_,), kw) + + else: + constraint_func = conbytes elif issubclass(type_, numeric_types) and not issubclass( type_, (
pydantic/pydantic
7344374dd01894b4a30bb1d17ab8c1e9c59a0b98
The reason is, by setting the `max_length` in `b` (`b: StrictBytes = Field(..., max_length=5)`), it won't be considered as `StrictBytes` anymore. then the provided value `123` will be converted to `bytes` during validation ```python from pydantic import BaseModel, StrictBytes, Field class Model(BaseModel): a: StrictBytes = Field(...) b: StrictBytes = Field(..., max_length=5) m = Model(a=b'arthur', b=123) # does not raise print(m) # a=b'arthur' b=b'123' ``` I am not sure if is it an intended behavior or not. @samuelcolvin what is your opinion here? It's an error, happy to review a PR if it's simple and submitted asap. Otherwise this is/will be fixed in V2.
diff --git a/tests/test_types.py b/tests/test_types.py --- a/tests/test_types.py +++ b/tests/test_types.py @@ -1634,6 +1634,18 @@ class Model(BaseModel): Model(v=0.42) +def test_strict_bytes_max_length(): + class Model(BaseModel): + u: StrictBytes = Field(..., max_length=5) + + assert Model(u=b'foo').u == b'foo' + + with pytest.raises(ValidationError, match='byte type expected'): + Model(u=123) + with pytest.raises(ValidationError, match='ensure this value has at most 5 characters'): + Model(u=b'1234567') + + def test_strict_bytes_subclass(): class MyStrictBytes(StrictBytes): pass
`StrictBytes` does not raise `ValidationError` when `max_length` is present in `Field` ### Initial Checks - [X] I have searched GitHub for a duplicate issue and I'm sure this is something new - [X] I have searched Google & StackOverflow for a solution and couldn't find anything - [X] I have read and followed [the docs](https://pydantic-docs.helpmanual.io) and still think this is a bug - [X] I am confident that the issue is with pydantic (not my code, or another library in the ecosystem like [FastAPI](https://fastapi.tiangolo.com) or [mypy](https://mypy.readthedocs.io/en/stable)) ### Description I'm using pydantic version 1.9.2. Mind this model: ```python # my_model/__init__.py from pydantic import BaseModel, StrictBytes, Field class Model(BaseModel): a: StrictBytes = Field(...) b: StrictBytes = Field(..., max_length=5) ``` Even though `b` is `StrictBytes`, I can create an object with the following line: `m = Model(a=b'arthur', b=123)` which I assume is a bug. I cannot create an object the other way around: `m = Model(a=123, b=b'art')`, which I assume is the intended behaviour. --- Here follows a pytest example: ```python # tests/test_my_model.py from my_model import Model import pytest from pydantic import ValidationError def test_normal(): m = Model(a=b'arthur', b=b'lucas') assert m.a == b'arthur' assert m.b == b'lucas' def test_large(): with pytest.raises(ValidationError) as error: m = Model(a=b'arthur', b=b'arthur') assert 'b\n' in str(error.value) assert 'value_error.any_str.max_length' in str(error.value) def test_a_str(): with pytest.raises(ValidationError) as error: m = Model(a=123123, b=b'lucas') assert 'a\n' in str(error.value) assert 'type_error.bytes' in str(error.value) def test_b_str(): with pytest.raises(ValidationError) as error: m = Model(a=b'arthur', b=123) # does not raise assert 'b\n' in str(error.value) assert 'type_error.bytes' in str(error.value) ``` And the output from pytest: ```bash platform linux -- Python 3.10.6, pytest-6.2.5, py-1.11.0, pluggy-1.0.0 rootdir: /home/arthurazs/Desktop/my_model collected 4 items tests/test_my_model.py ...F [100%] ====================================== FAILURES ======================================= _____________________________________ test_b_str ______________________________________ def test_b_str(): > with pytest.raises(ValidationError) as error: E Failed: DID NOT RAISE <class 'pydantic.error_wrappers.ValidationError'> tests/test_my_model.py:24: Failed =============================== short test summary info =============================== FAILED tests/test_my_model.py::test_b_str - Failed: DID NOT RAISE <class 'pydantic.e... ============================= 1 failed, 3 passed in 0.04s ============================= ``` ### Example Code ```Python from pydantic import BaseModel, StrictBytes, Field class Model(BaseModel): a: StrictBytes = Field(...) b: StrictBytes = Field(..., max_length=5) m = Model(a=b'arthur', b=123) # does not raise ``` ### Python, Pydantic & OS Version ```Text pydantic version: 1.9.2 pydantic compiled: True install path: /home/arthurazs/.cache/pypoetry/virtualenvs/asd-8JLwExQw-py3.10/lib/python3.10/site-packages/pydantic python version: 3.10.6 (main, Aug 2 2022, 15:11:28) [GCC 9.4.0] platform: Linux-5.15.0-46-generic-x86_64-with-glibc2.31 optional deps. installed: ['typing-extensions'] ``` ### Affected Components - [ ] [Compatibility between releases](https://pydantic-docs.helpmanual.io/changelog/) - [X] [Data validation/parsing](https://pydantic-docs.helpmanual.io/usage/models/#basic-model-usage) - [ ] [Data serialization](https://pydantic-docs.helpmanual.io/usage/exporting_models/) - `.dict()` and `.json()` - [ ] [JSON Schema](https://pydantic-docs.helpmanual.io/usage/schema/) - [ ] [Dataclasses](https://pydantic-docs.helpmanual.io/usage/dataclasses/) - [ ] [Model Config](https://pydantic-docs.helpmanual.io/usage/model_config/) - [X] [Field Types](https://pydantic-docs.helpmanual.io/usage/types/) - adding or changing a particular data type - [ ] [Function validation decorator](https://pydantic-docs.helpmanual.io/usage/validation_decorator/) - [ ] [Generic Models](https://pydantic-docs.helpmanual.io/usage/models/#generic-models) - [ ] [Other Model behaviour](https://pydantic-docs.helpmanual.io/usage/models/) - `construct()`, pickling, private attributes, ORM mode - [ ] [Settings Management](https://pydantic-docs.helpmanual.io/usage/settings/) - [ ] [Plugins](https://pydantic-docs.helpmanual.io/) and integration with other tools - mypy, FastAPI, python-devtools, Hypothesis, VS Code, PyCharm, etc.
0.0
7344374dd01894b4a30bb1d17ab8c1e9c59a0b98
[ "tests/test_types.py::test_strict_bytes_max_length" ]
[ "tests/test_types.py::test_constrained_bytes_good", "tests/test_types.py::test_constrained_bytes_default", "tests/test_types.py::test_constrained_bytes_too_long", "tests/test_types.py::test_constrained_bytes_upper[True-abcd-ABCD]", "tests/test_types.py::test_constrained_bytes_upper[False-aBcD-aBcD]", "tests/test_types.py::test_constrained_bytes_lower[True-ABCD-abcd]", "tests/test_types.py::test_constrained_bytes_lower[False-ABCD-ABCD]", "tests/test_types.py::test_constrained_bytes_strict_true", "tests/test_types.py::test_constrained_bytes_strict_false", "tests/test_types.py::test_constrained_bytes_strict_default", "tests/test_types.py::test_constrained_list_good", "tests/test_types.py::test_constrained_list_default", "tests/test_types.py::test_constrained_list_too_long", "tests/test_types.py::test_constrained_list_too_short", "tests/test_types.py::test_constrained_list_not_unique_hashable_items", "tests/test_types.py::test_constrained_list_not_unique_unhashable_items", "tests/test_types.py::test_constrained_list_optional", "tests/test_types.py::test_constrained_list_constraints", "tests/test_types.py::test_constrained_list_item_type_fails", "tests/test_types.py::test_conlist", "tests/test_types.py::test_conlist_wrong_type_default", "tests/test_types.py::test_constrained_set_good", "tests/test_types.py::test_constrained_set_default", "tests/test_types.py::test_constrained_set_default_invalid", "tests/test_types.py::test_constrained_set_too_long", "tests/test_types.py::test_constrained_set_too_short", "tests/test_types.py::test_constrained_set_optional", "tests/test_types.py::test_constrained_set_constraints", "tests/test_types.py::test_constrained_set_item_type_fails", "tests/test_types.py::test_conset", "tests/test_types.py::test_conset_not_required", "tests/test_types.py::test_confrozenset", "tests/test_types.py::test_confrozenset_not_required", "tests/test_types.py::test_constrained_frozenset_optional", "tests/test_types.py::test_constrained_str_good", "tests/test_types.py::test_constrained_str_default", "tests/test_types.py::test_constrained_str_too_long", "tests/test_types.py::test_constrained_str_upper[True-abcd-ABCD]", "tests/test_types.py::test_constrained_str_upper[False-aBcD-aBcD]", "tests/test_types.py::test_constrained_str_lower[True-ABCD-abcd]", "tests/test_types.py::test_constrained_str_lower[False-ABCD-ABCD]", "tests/test_types.py::test_constrained_str_max_length_0", "tests/test_types.py::test_module_import", "tests/test_types.py::test_pyobject_none", "tests/test_types.py::test_pyobject_callable", "tests/test_types.py::test_default_validators[bool_check-True-True0]", "tests/test_types.py::test_default_validators[bool_check-1-True0]", "tests/test_types.py::test_default_validators[bool_check-y-True]", "tests/test_types.py::test_default_validators[bool_check-Y-True]", "tests/test_types.py::test_default_validators[bool_check-yes-True]", "tests/test_types.py::test_default_validators[bool_check-Yes-True]", "tests/test_types.py::test_default_validators[bool_check-YES-True]", "tests/test_types.py::test_default_validators[bool_check-true-True]", "tests/test_types.py::test_default_validators[bool_check-True-True1]", "tests/test_types.py::test_default_validators[bool_check-TRUE-True0]", "tests/test_types.py::test_default_validators[bool_check-on-True]", "tests/test_types.py::test_default_validators[bool_check-On-True]", "tests/test_types.py::test_default_validators[bool_check-ON-True]", "tests/test_types.py::test_default_validators[bool_check-1-True1]", "tests/test_types.py::test_default_validators[bool_check-t-True]", "tests/test_types.py::test_default_validators[bool_check-T-True]", "tests/test_types.py::test_default_validators[bool_check-TRUE-True1]", "tests/test_types.py::test_default_validators[bool_check-False-False0]", "tests/test_types.py::test_default_validators[bool_check-0-False0]", "tests/test_types.py::test_default_validators[bool_check-n-False]", "tests/test_types.py::test_default_validators[bool_check-N-False]", "tests/test_types.py::test_default_validators[bool_check-no-False]", "tests/test_types.py::test_default_validators[bool_check-No-False]", "tests/test_types.py::test_default_validators[bool_check-NO-False]", "tests/test_types.py::test_default_validators[bool_check-false-False]", "tests/test_types.py::test_default_validators[bool_check-False-False1]", "tests/test_types.py::test_default_validators[bool_check-FALSE-False0]", "tests/test_types.py::test_default_validators[bool_check-off-False]", "tests/test_types.py::test_default_validators[bool_check-Off-False]", "tests/test_types.py::test_default_validators[bool_check-OFF-False]", "tests/test_types.py::test_default_validators[bool_check-0-False1]", "tests/test_types.py::test_default_validators[bool_check-f-False]", "tests/test_types.py::test_default_validators[bool_check-F-False]", "tests/test_types.py::test_default_validators[bool_check-FALSE-False1]", "tests/test_types.py::test_default_validators[bool_check-None-ValidationError]", "tests/test_types.py::test_default_validators[bool_check--ValidationError]", "tests/test_types.py::test_default_validators[bool_check-value36-ValidationError]", "tests/test_types.py::test_default_validators[bool_check-value37-ValidationError]", "tests/test_types.py::test_default_validators[bool_check-value38-ValidationError]", "tests/test_types.py::test_default_validators[bool_check-value39-ValidationError]", "tests/test_types.py::test_default_validators[bool_check-2-ValidationError0]", "tests/test_types.py::test_default_validators[bool_check-2-ValidationError1]", "tests/test_types.py::test_default_validators[bool_check-2-ValidationError2]", "tests/test_types.py::test_default_validators[bool_check-\\x81-ValidationError]", "tests/test_types.py::test_default_validators[bool_check-value44-ValidationError]", "tests/test_types.py::test_default_validators[str_check-s-s0]", "tests/test_types.py::test_default_validators[str_check-", "tests/test_types.py::test_default_validators[str_check-s-s1]", "tests/test_types.py::test_default_validators[str_check-1-1]", "tests/test_types.py::test_default_validators[str_check-xxxxxxxxxxx-ValidationError0]", "tests/test_types.py::test_default_validators[str_check-xxxxxxxxxxx-ValidationError1]", "tests/test_types.py::test_default_validators[bytes_check-s-s0]", "tests/test_types.py::test_default_validators[bytes_check-", "tests/test_types.py::test_default_validators[bytes_check-s-s1]", "tests/test_types.py::test_default_validators[bytes_check-1-1]", "tests/test_types.py::test_default_validators[bytes_check-value57-xx]", "tests/test_types.py::test_default_validators[bytes_check-True-True]", "tests/test_types.py::test_default_validators[bytes_check-False-False]", "tests/test_types.py::test_default_validators[bytes_check-value60-ValidationError]", "tests/test_types.py::test_default_validators[bytes_check-xxxxxxxxxxx-ValidationError0]", "tests/test_types.py::test_default_validators[bytes_check-xxxxxxxxxxx-ValidationError1]", "tests/test_types.py::test_default_validators[int_check-1-10]", "tests/test_types.py::test_default_validators[int_check-1.9-1]", "tests/test_types.py::test_default_validators[int_check-1-11]", "tests/test_types.py::test_default_validators[int_check-1.9-ValidationError]", "tests/test_types.py::test_default_validators[int_check-1-12]", "tests/test_types.py::test_default_validators[int_check-12-120]", "tests/test_types.py::test_default_validators[int_check-12-121]", "tests/test_types.py::test_default_validators[int_check-12-122]", "tests/test_types.py::test_default_validators[float_check-1-1.00]", "tests/test_types.py::test_default_validators[float_check-1.0-1.00]", "tests/test_types.py::test_default_validators[float_check-1.0-1.01]", "tests/test_types.py::test_default_validators[float_check-1-1.01]", "tests/test_types.py::test_default_validators[float_check-1.0-1.02]", "tests/test_types.py::test_default_validators[float_check-1-1.02]", "tests/test_types.py::test_default_validators[uuid_check-ebcdab58-6eb8-46fb-a190-d07a33e9eac8-result77]", "tests/test_types.py::test_default_validators[uuid_check-value78-result78]", "tests/test_types.py::test_default_validators[uuid_check-ebcdab58-6eb8-46fb-a190-d07a33e9eac8-result79]", "tests/test_types.py::test_default_validators[uuid_check-\\x124Vx\\x124Vx\\x124Vx\\x124Vx-result80]", "tests/test_types.py::test_default_validators[uuid_check-ebcdab58-6eb8-46fb-a190--ValidationError]", "tests/test_types.py::test_default_validators[uuid_check-123-ValidationError]", "tests/test_types.py::test_default_validators[decimal_check-42.24-result83]", "tests/test_types.py::test_default_validators[decimal_check-42.24-result84]", "tests/test_types.py::test_default_validators[decimal_check-42.24-result85]", "tests/test_types.py::test_default_validators[decimal_check-", "tests/test_types.py::test_default_validators[decimal_check-value87-result87]", "tests/test_types.py::test_default_validators[decimal_check-not", "tests/test_types.py::test_default_validators[decimal_check-NaN-ValidationError]", "tests/test_types.py::test_string_too_long", "tests/test_types.py::test_string_too_short", "tests/test_types.py::test_datetime_successful", "tests/test_types.py::test_datetime_errors", "tests/test_types.py::test_enum_successful", "tests/test_types.py::test_enum_fails", "tests/test_types.py::test_int_enum_successful_for_str_int", "tests/test_types.py::test_enum_type", "tests/test_types.py::test_int_enum_type", "tests/test_types.py::test_string_success", "tests/test_types.py::test_string_fails", "tests/test_types.py::test_dict", "tests/test_types.py::test_list_success[value0-result0]", "tests/test_types.py::test_list_success[value1-result1]", "tests/test_types.py::test_list_success[value2-result2]", "tests/test_types.py::test_list_success[<genexpr>-result3]", "tests/test_types.py::test_list_success[value4-result4]", "tests/test_types.py::test_list_fails[1230]", "tests/test_types.py::test_list_fails[1231]", "tests/test_types.py::test_ordered_dict", "tests/test_types.py::test_tuple_success[value0-result0]", "tests/test_types.py::test_tuple_success[value1-result1]", "tests/test_types.py::test_tuple_success[value2-result2]", "tests/test_types.py::test_tuple_success[<genexpr>-result3]", "tests/test_types.py::test_tuple_success[value4-result4]", "tests/test_types.py::test_tuple_fails[1230]", "tests/test_types.py::test_tuple_fails[1231]", "tests/test_types.py::test_tuple_variable_len_success[value0-int-result0]", "tests/test_types.py::test_tuple_variable_len_success[value1-int-result1]", "tests/test_types.py::test_tuple_variable_len_success[<genexpr>-int-result2]", "tests/test_types.py::test_tuple_variable_len_success[value3-str-result3]", "tests/test_types.py::test_tuple_variable_len_fails[value0-str-exc0]", "tests/test_types.py::test_tuple_variable_len_fails[value1-str-exc1]", "tests/test_types.py::test_set_success[value0-result0]", "tests/test_types.py::test_set_success[value1-result1]", "tests/test_types.py::test_set_success[value2-result2]", "tests/test_types.py::test_set_success[value3-result3]", "tests/test_types.py::test_set_fails[1230]", "tests/test_types.py::test_set_fails[1231]", "tests/test_types.py::test_list_type_fails", "tests/test_types.py::test_set_type_fails", "tests/test_types.py::test_sequence_success[int-value0-result0]", "tests/test_types.py::test_sequence_success[int-value1-result1]", "tests/test_types.py::test_sequence_success[int-value2-result2]", "tests/test_types.py::test_sequence_success[float-value3-result3]", "tests/test_types.py::test_sequence_success[cls4-value4-result4]", "tests/test_types.py::test_sequence_success[cls5-value5-result5]", "tests/test_types.py::test_sequence_generator_success[int-<genexpr>-result0]", "tests/test_types.py::test_sequence_generator_success[float-<genexpr>-result1]", "tests/test_types.py::test_sequence_generator_success[str-<genexpr>-result2]", "tests/test_types.py::test_infinite_iterable", "tests/test_types.py::test_invalid_iterable", "tests/test_types.py::test_infinite_iterable_validate_first", "tests/test_types.py::test_sequence_generator_fails[int-<genexpr>-errors0]", "tests/test_types.py::test_sequence_generator_fails[float-<genexpr>-errors1]", "tests/test_types.py::test_sequence_fails[int-value0-errors0]", "tests/test_types.py::test_sequence_fails[int-value1-errors1]", "tests/test_types.py::test_sequence_fails[float-value2-errors2]", "tests/test_types.py::test_sequence_fails[float-value3-errors3]", "tests/test_types.py::test_sequence_fails[float-value4-errors4]", "tests/test_types.py::test_sequence_fails[cls5-value5-errors5]", "tests/test_types.py::test_sequence_fails[cls6-value6-errors6]", "tests/test_types.py::test_sequence_fails[cls7-value7-errors7]", "tests/test_types.py::test_int_validation", "tests/test_types.py::test_float_validation", "tests/test_types.py::test_strict_bytes", "tests/test_types.py::test_strict_bytes_subclass", "tests/test_types.py::test_strict_str", "tests/test_types.py::test_strict_str_subclass", "tests/test_types.py::test_strict_bool", "tests/test_types.py::test_strict_int", "tests/test_types.py::test_strict_int_subclass", "tests/test_types.py::test_strict_float", "tests/test_types.py::test_strict_float_subclass", "tests/test_types.py::test_bool_unhashable_fails", "tests/test_types.py::test_uuid_error", "tests/test_types.py::test_uuid_validation", "tests/test_types.py::test_anystr_strip_whitespace[True-", "tests/test_types.py::test_anystr_strip_whitespace[False-", "tests/test_types.py::test_anystr_upper[True-ABCDefG-abCD1Fg-ABCDEFG-ABCD1FG]", "tests/test_types.py::test_anystr_upper[False-ABCDefG-abCD1Fg-ABCDefG-abCD1Fg]", "tests/test_types.py::test_anystr_lower[True-ABCDefG-abCD1Fg-abcdefg-abcd1fg]", "tests/test_types.py::test_anystr_lower[False-ABCDefG-abCD1Fg-ABCDefG-abCD1Fg]", "tests/test_types.py::test_decimal_validation[type_args0-value0-result0]", "tests/test_types.py::test_decimal_validation[type_args1-value1-result1]", "tests/test_types.py::test_decimal_validation[type_args2-value2-result2]", "tests/test_types.py::test_decimal_validation[type_args3-value3-result3]", "tests/test_types.py::test_decimal_validation[type_args4-value4-result4]", "tests/test_types.py::test_decimal_validation[type_args5-value5-result5]", "tests/test_types.py::test_decimal_validation[type_args6-value6-result6]", "tests/test_types.py::test_decimal_validation[type_args7-value7-result7]", "tests/test_types.py::test_decimal_validation[type_args8-value8-result8]", "tests/test_types.py::test_decimal_validation[type_args9-value9-result9]", "tests/test_types.py::test_decimal_validation[type_args10-value10-result10]", "tests/test_types.py::test_decimal_validation[type_args11-value11-result11]", "tests/test_types.py::test_decimal_validation[type_args12-value12-result12]", "tests/test_types.py::test_decimal_validation[type_args13-value13-result13]", "tests/test_types.py::test_decimal_validation[type_args14-value14-result14]", "tests/test_types.py::test_decimal_validation[type_args15-value15-result15]", "tests/test_types.py::test_decimal_validation[type_args16-value16-result16]", "tests/test_types.py::test_decimal_validation[type_args17-value17-result17]", "tests/test_types.py::test_decimal_validation[type_args18-value18-result18]", "tests/test_types.py::test_decimal_validation[type_args19-value19-result19]", "tests/test_types.py::test_decimal_validation[type_args20-value20-result20]", "tests/test_types.py::test_decimal_validation[type_args21-NaN-result21]", "tests/test_types.py::test_decimal_validation[type_args22--NaN-result22]", "tests/test_types.py::test_decimal_validation[type_args23-+NaN-result23]", "tests/test_types.py::test_decimal_validation[type_args24-sNaN-result24]", "tests/test_types.py::test_decimal_validation[type_args25--sNaN-result25]", "tests/test_types.py::test_decimal_validation[type_args26-+sNaN-result26]", "tests/test_types.py::test_decimal_validation[type_args27-Inf-result27]", "tests/test_types.py::test_decimal_validation[type_args28--Inf-result28]", "tests/test_types.py::test_decimal_validation[type_args29-+Inf-result29]", "tests/test_types.py::test_decimal_validation[type_args30-Infinity-result30]", "tests/test_types.py::test_decimal_validation[type_args31--Infinity-result31]", "tests/test_types.py::test_decimal_validation[type_args32--Infinity-result32]", "tests/test_types.py::test_decimal_validation[type_args33-value33-result33]", "tests/test_types.py::test_decimal_validation[type_args34-value34-result34]", "tests/test_types.py::test_decimal_validation[type_args35-value35-result35]", "tests/test_types.py::test_decimal_validation[type_args36-value36-result36]", "tests/test_types.py::test_decimal_validation[type_args37-value37-result37]", "tests/test_types.py::test_decimal_validation[type_args38-value38-result38]", "tests/test_types.py::test_decimal_validation[type_args39-value39-result39]", "tests/test_types.py::test_decimal_validation[type_args40-value40-result40]", "tests/test_types.py::test_decimal_validation[type_args41-value41-result41]", "tests/test_types.py::test_decimal_validation[type_args42-value42-result42]", "tests/test_types.py::test_decimal_validation[type_args43-value43-result43]", "tests/test_types.py::test_decimal_validation[type_args44-value44-result44]", "tests/test_types.py::test_decimal_validation[type_args45-value45-result45]", "tests/test_types.py::test_path_validation_success[/test/path-result0]", "tests/test_types.py::test_path_validation_success[value1-result1]", "tests/test_types.py::test_path_validation_fails", "tests/test_types.py::test_file_path_validation_success[tests/test_types.py-result0]", "tests/test_types.py::test_file_path_validation_success[value1-result1]", "tests/test_types.py::test_file_path_validation_fails[nonexistentfile-errors0]", "tests/test_types.py::test_file_path_validation_fails[value1-errors1]", "tests/test_types.py::test_file_path_validation_fails[tests-errors2]", "tests/test_types.py::test_file_path_validation_fails[value3-errors3]", "tests/test_types.py::test_directory_path_validation_success[tests-result0]", "tests/test_types.py::test_directory_path_validation_success[value1-result1]", "tests/test_types.py::test_directory_path_validation_fails[nonexistentdirectory-errors0]", "tests/test_types.py::test_directory_path_validation_fails[value1-errors1]", "tests/test_types.py::test_directory_path_validation_fails[tests/test_types.py-errors2]", "tests/test_types.py::test_directory_path_validation_fails[value3-errors3]", "tests/test_types.py::test_number_gt", "tests/test_types.py::test_number_ge", "tests/test_types.py::test_number_lt", "tests/test_types.py::test_number_le", "tests/test_types.py::test_number_multiple_of_int_valid[10]", "tests/test_types.py::test_number_multiple_of_int_valid[100]", "tests/test_types.py::test_number_multiple_of_int_valid[20]", "tests/test_types.py::test_number_multiple_of_int_invalid[1337]", "tests/test_types.py::test_number_multiple_of_int_invalid[23]", "tests/test_types.py::test_number_multiple_of_int_invalid[6]", "tests/test_types.py::test_number_multiple_of_int_invalid[14]", "tests/test_types.py::test_number_multiple_of_float_valid[0.2]", "tests/test_types.py::test_number_multiple_of_float_valid[0.3]", "tests/test_types.py::test_number_multiple_of_float_valid[0.4]", "tests/test_types.py::test_number_multiple_of_float_valid[0.5]", "tests/test_types.py::test_number_multiple_of_float_valid[1]", "tests/test_types.py::test_number_multiple_of_float_invalid[0.07]", "tests/test_types.py::test_number_multiple_of_float_invalid[1.27]", "tests/test_types.py::test_number_multiple_of_float_invalid[1.003]", "tests/test_types.py::test_bounds_config_exceptions[conint]", "tests/test_types.py::test_bounds_config_exceptions[confloat]", "tests/test_types.py::test_bounds_config_exceptions[condecimal]", "tests/test_types.py::test_new_type_success", "tests/test_types.py::test_new_type_fails", "tests/test_types.py::test_json_any_is_json", "tests/test_types.py::test_valid_simple_json", "tests/test_types.py::test_valid_simple_json_any", "tests/test_types.py::test_invalid_simple_json", "tests/test_types.py::test_invalid_simple_json_any", "tests/test_types.py::test_valid_simple_json_bytes", "tests/test_types.py::test_valid_detailed_json", "tests/test_types.py::test_invalid_detailed_json_value_error", "tests/test_types.py::test_valid_detailed_json_bytes", "tests/test_types.py::test_valid_model_json", "tests/test_types.py::test_invalid_model_json", "tests/test_types.py::test_invalid_detailed_json_type_error", "tests/test_types.py::test_json_not_str", "tests/test_types.py::test_json_pre_validator", "tests/test_types.py::test_json_optional_simple", "tests/test_types.py::test_json_optional_complex", "tests/test_types.py::test_json_explicitly_required", "tests/test_types.py::test_json_no_default", "tests/test_types.py::test_pattern[Pattern]", "tests/test_types.py::test_pattern[pattern_type1]", "tests/test_types.py::test_pattern_error[Pattern]", "tests/test_types.py::test_pattern_error[pattern_type1]", "tests/test_types.py::test_secretfield", "tests/test_types.py::test_secretstr", "tests/test_types.py::test_secretstr_is_secret_field", "tests/test_types.py::test_secretstr_equality", "tests/test_types.py::test_secretstr_idempotent", "tests/test_types.py::test_secretstr_error", "tests/test_types.py::test_secretstr_min_max_length", "tests/test_types.py::test_secretbytes", "tests/test_types.py::test_secretbytes_is_secret_field", "tests/test_types.py::test_secretbytes_equality", "tests/test_types.py::test_secretbytes_idempotent", "tests/test_types.py::test_secretbytes_error", "tests/test_types.py::test_secretbytes_min_max_length", "tests/test_types.py::test_secrets_schema[no-constrains-SecretStr]", "tests/test_types.py::test_secrets_schema[no-constrains-SecretBytes]", "tests/test_types.py::test_secrets_schema[min-constraint-SecretStr]", "tests/test_types.py::test_secrets_schema[min-constraint-SecretBytes]", "tests/test_types.py::test_secrets_schema[max-constraint-SecretStr]", "tests/test_types.py::test_secrets_schema[max-constraint-SecretBytes]", "tests/test_types.py::test_secrets_schema[min-max-constraints-SecretStr]", "tests/test_types.py::test_secrets_schema[min-max-constraints-SecretBytes]", "tests/test_types.py::test_generic_without_params", "tests/test_types.py::test_generic_without_params_error", "tests/test_types.py::test_literal_single", "tests/test_types.py::test_literal_multiple", "tests/test_types.py::test_unsupported_field_type", "tests/test_types.py::test_frozenset_field", "tests/test_types.py::test_frozenset_field_conversion[value0-result0]", "tests/test_types.py::test_frozenset_field_conversion[value1-result1]", "tests/test_types.py::test_frozenset_field_conversion[value2-result2]", "tests/test_types.py::test_frozenset_field_conversion[value3-result3]", "tests/test_types.py::test_frozenset_field_not_convertible", "tests/test_types.py::test_bytesize_conversions[1-1-1.0B-1.0B]", "tests/test_types.py::test_bytesize_conversions[1.0-1-1.0B-1.0B]", "tests/test_types.py::test_bytesize_conversions[1b-1-1.0B-1.0B]", "tests/test_types.py::test_bytesize_conversions[1.5", "tests/test_types.py::test_bytesize_conversions[5.1kib-5222-5.1KiB-5.2KB]", "tests/test_types.py::test_bytesize_conversions[6.2EiB-7148113328562451456-6.2EiB-7.1EB]", "tests/test_types.py::test_bytesize_to", "tests/test_types.py::test_bytesize_raises", "tests/test_types.py::test_deque_success", "tests/test_types.py::test_deque_generic_success[int-value0-result0]", "tests/test_types.py::test_deque_generic_success[int-value1-result1]", "tests/test_types.py::test_deque_generic_success[int-value2-result2]", "tests/test_types.py::test_deque_generic_success[float-value3-result3]", "tests/test_types.py::test_deque_generic_success[cls4-value4-result4]", "tests/test_types.py::test_deque_generic_success[cls5-value5-result5]", "tests/test_types.py::test_deque_generic_success[str-value6-result6]", "tests/test_types.py::test_deque_generic_success[int-value7-result7]", "tests/test_types.py::test_deque_fails[int-value0-errors0]", "tests/test_types.py::test_deque_fails[int-value1-errors1]", "tests/test_types.py::test_deque_fails[float-value2-errors2]", "tests/test_types.py::test_deque_fails[float-value3-errors3]", "tests/test_types.py::test_deque_fails[float-value4-errors4]", "tests/test_types.py::test_deque_fails[cls5-value5-errors5]", "tests/test_types.py::test_deque_fails[cls6-value6-errors6]", "tests/test_types.py::test_deque_fails[cls7-value7-errors7]", "tests/test_types.py::test_deque_model", "tests/test_types.py::test_deque_json", "tests/test_types.py::test_none[None]", "tests/test_types.py::test_none[NoneType0]", "tests/test_types.py::test_none[NoneType1]", "tests/test_types.py::test_none[value_type3]", "tests/test_types.py::test_default_union_types", "tests/test_types.py::test_smart_union_types", "tests/test_types.py::test_default_union_class", "tests/test_types.py::test_smart_union_class", "tests/test_types.py::test_default_union_subclass", "tests/test_types.py::test_smart_union_subclass", "tests/test_types.py::test_default_union_compound_types", "tests/test_types.py::test_smart_union_compound_types", "tests/test_types.py::test_smart_union_compouned_types_edge_case", "tests/test_types.py::test_smart_union_typeddict", "tests/test_types.py::test_past_date_validation_success[1996-01-22-result0]", "tests/test_types.py::test_past_date_validation_success[value1-result1]", "tests/test_types.py::test_past_date_validation_fails[value0]", "tests/test_types.py::test_past_date_validation_fails[value1]", "tests/test_types.py::test_past_date_validation_fails[value2]", "tests/test_types.py::test_past_date_validation_fails[value3]", "tests/test_types.py::test_past_date_validation_fails[2064-06-01]", "tests/test_types.py::test_future_date_validation_success[value0-result0]", "tests/test_types.py::test_future_date_validation_success[value1-result1]", "tests/test_types.py::test_future_date_validation_success[2064-06-01-result2]", "tests/test_types.py::test_future_date_validation_fails[value0]", "tests/test_types.py::test_future_date_validation_fails[value1]", "tests/test_types.py::test_future_date_validation_fails[value2]", "tests/test_types.py::test_future_date_validation_fails[value3]", "tests/test_types.py::test_future_date_validation_fails[1996-01-22]" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2022-08-16 13:17:37+00:00
mit
4,874
pydantic__pydantic-4399
diff --git a/pydantic/types.py b/pydantic/types.py --- a/pydantic/types.py +++ b/pydantic/types.py @@ -834,6 +834,9 @@ def __eq__(self, other: Any) -> bool: def __str__(self) -> str: return '**********' if self.get_secret_value() else '' + def __hash__(self) -> int: + return hash(self.get_secret_value()) + @abc.abstractmethod def get_secret_value(self) -> Any: # pragma: no cover ...
pydantic/pydantic
78e84b92c04d6a908fdbf1bcf173151eb48cd344
please give more details on what you're asking for and how it would be useful. Closing but happy to reopen if more details are provided.
diff --git a/tests/test_types.py b/tests/test_types.py --- a/tests/test_types.py +++ b/tests/test_types.py @@ -2650,6 +2650,10 @@ class Foobar(BaseModel): assert m.password.get_secret_value() == '1234' +def test_secretstr_is_hashable(): + assert type(hash(SecretStr('secret'))) is int + + def test_secretstr_error(): class Foobar(BaseModel): password: SecretStr @@ -2742,6 +2746,10 @@ class Foobar(BaseModel): _ = Foobar(password=SecretBytes(b'1234')) +def test_secretbytes_is_hashable(): + assert type(hash(SecretBytes(b'secret'))) is int + + def test_secretbytes_error(): class Foobar(BaseModel): password: SecretBytes
Hashable SecretStr ### Initial Checks - [X] I have searched Google & GitHub for similar requests and couldn't find anything - [X] I have read and followed [the docs](https://pydantic-docs.helpmanual.io) and still think this feature is missing ### Description I'd like to see instances of the pydantic class `SecretStr` to be hashable like instances of the `str` class are hashable. I use it mainly in instances of `BaseSettings` and during startup of a server application, I add settings classes which I can successfully construct in a set. This gives me an indication of missing configuration values. But models containing fields annotated with `SecretStr` currently cannot be added to a set as Python complains about the `SecretStr` type: `TypeError: unhashable type: 'SecretStr'` Example snippet: ```py import pydantic class M(pydantic.BaseModel): s: pydantic.SecretStr = pydantic.SecretStr("secret") def __hash__(self): return hash((type(self),) + tuple(self.__dict__.values())) def test_can_hash(): assert hash(M()) ``` ### Affected Components - [ ] [Compatibility between releases](https://pydantic-docs.helpmanual.io/changelog/) - [ ] [Data validation/parsing](https://pydantic-docs.helpmanual.io/usage/models/#basic-model-usage) - [ ] [Data serialization](https://pydantic-docs.helpmanual.io/usage/exporting_models/) - `.dict()` and `.json()` - [ ] [JSON Schema](https://pydantic-docs.helpmanual.io/usage/schema/) - [ ] [Dataclasses](https://pydantic-docs.helpmanual.io/usage/dataclasses/) - [ ] [Model Config](https://pydantic-docs.helpmanual.io/usage/model_config/) - [ ] [Field Types](https://pydantic-docs.helpmanual.io/usage/types/) - adding or changing a particular data type - [ ] [Function validation decorator](https://pydantic-docs.helpmanual.io/usage/validation_decorator/) - [ ] [Generic Models](https://pydantic-docs.helpmanual.io/usage/models/#generic-models) - [X] [Other Model behaviour](https://pydantic-docs.helpmanual.io/usage/models/) - `construct()`, pickling, private attributes, ORM mode - [ ] [Settings Management](https://pydantic-docs.helpmanual.io/usage/settings/) - [ ] [Plugins](https://pydantic-docs.helpmanual.io/) and integration with other tools - mypy, FastAPI, python-devtools, Hypothesis, VS Code, PyCharm, etc.
0.0
78e84b92c04d6a908fdbf1bcf173151eb48cd344
[ "tests/test_types.py::test_secretstr_is_hashable", "tests/test_types.py::test_secretbytes_is_hashable" ]
[ "tests/test_types.py::test_constrained_bytes_good", "tests/test_types.py::test_constrained_bytes_default", "tests/test_types.py::test_constrained_bytes_too_long", "tests/test_types.py::test_constrained_bytes_upper[True-abcd-ABCD]", "tests/test_types.py::test_constrained_bytes_upper[False-aBcD-aBcD]", "tests/test_types.py::test_constrained_bytes_lower[True-ABCD-abcd]", "tests/test_types.py::test_constrained_bytes_lower[False-ABCD-ABCD]", "tests/test_types.py::test_constrained_bytes_strict_true", "tests/test_types.py::test_constrained_bytes_strict_false", "tests/test_types.py::test_constrained_bytes_strict_default", "tests/test_types.py::test_constrained_list_good", "tests/test_types.py::test_constrained_list_default", "tests/test_types.py::test_constrained_list_too_long", "tests/test_types.py::test_constrained_list_too_short", "tests/test_types.py::test_constrained_list_not_unique_hashable_items", "tests/test_types.py::test_constrained_list_not_unique_unhashable_items", "tests/test_types.py::test_constrained_list_optional", "tests/test_types.py::test_constrained_list_constraints", "tests/test_types.py::test_constrained_list_item_type_fails", "tests/test_types.py::test_conlist", "tests/test_types.py::test_conlist_wrong_type_default", "tests/test_types.py::test_constrained_set_good", "tests/test_types.py::test_constrained_set_default", "tests/test_types.py::test_constrained_set_default_invalid", "tests/test_types.py::test_constrained_set_too_long", "tests/test_types.py::test_constrained_set_too_short", "tests/test_types.py::test_constrained_set_optional", "tests/test_types.py::test_constrained_set_constraints", "tests/test_types.py::test_constrained_set_item_type_fails", "tests/test_types.py::test_conset", "tests/test_types.py::test_conset_not_required", "tests/test_types.py::test_confrozenset", "tests/test_types.py::test_confrozenset_not_required", "tests/test_types.py::test_constrained_frozenset_optional", "tests/test_types.py::test_constrained_str_good", "tests/test_types.py::test_constrained_str_default", "tests/test_types.py::test_constrained_str_too_long", "tests/test_types.py::test_constrained_str_upper[True-abcd-ABCD]", "tests/test_types.py::test_constrained_str_upper[False-aBcD-aBcD]", "tests/test_types.py::test_constrained_str_lower[True-ABCD-abcd]", "tests/test_types.py::test_constrained_str_lower[False-ABCD-ABCD]", "tests/test_types.py::test_constrained_str_max_length_0", "tests/test_types.py::test_module_import", "tests/test_types.py::test_pyobject_none", "tests/test_types.py::test_pyobject_callable", "tests/test_types.py::test_default_validators[bool_check-True-True0]", "tests/test_types.py::test_default_validators[bool_check-1-True0]", "tests/test_types.py::test_default_validators[bool_check-y-True]", "tests/test_types.py::test_default_validators[bool_check-Y-True]", "tests/test_types.py::test_default_validators[bool_check-yes-True]", "tests/test_types.py::test_default_validators[bool_check-Yes-True]", "tests/test_types.py::test_default_validators[bool_check-YES-True]", "tests/test_types.py::test_default_validators[bool_check-true-True]", "tests/test_types.py::test_default_validators[bool_check-True-True1]", "tests/test_types.py::test_default_validators[bool_check-TRUE-True0]", "tests/test_types.py::test_default_validators[bool_check-on-True]", "tests/test_types.py::test_default_validators[bool_check-On-True]", "tests/test_types.py::test_default_validators[bool_check-ON-True]", "tests/test_types.py::test_default_validators[bool_check-1-True1]", "tests/test_types.py::test_default_validators[bool_check-t-True]", "tests/test_types.py::test_default_validators[bool_check-T-True]", "tests/test_types.py::test_default_validators[bool_check-TRUE-True1]", "tests/test_types.py::test_default_validators[bool_check-False-False0]", "tests/test_types.py::test_default_validators[bool_check-0-False0]", "tests/test_types.py::test_default_validators[bool_check-n-False]", "tests/test_types.py::test_default_validators[bool_check-N-False]", "tests/test_types.py::test_default_validators[bool_check-no-False]", "tests/test_types.py::test_default_validators[bool_check-No-False]", "tests/test_types.py::test_default_validators[bool_check-NO-False]", "tests/test_types.py::test_default_validators[bool_check-false-False]", "tests/test_types.py::test_default_validators[bool_check-False-False1]", "tests/test_types.py::test_default_validators[bool_check-FALSE-False0]", "tests/test_types.py::test_default_validators[bool_check-off-False]", "tests/test_types.py::test_default_validators[bool_check-Off-False]", "tests/test_types.py::test_default_validators[bool_check-OFF-False]", "tests/test_types.py::test_default_validators[bool_check-0-False1]", "tests/test_types.py::test_default_validators[bool_check-f-False]", "tests/test_types.py::test_default_validators[bool_check-F-False]", "tests/test_types.py::test_default_validators[bool_check-FALSE-False1]", "tests/test_types.py::test_default_validators[bool_check-None-ValidationError]", "tests/test_types.py::test_default_validators[bool_check--ValidationError]", "tests/test_types.py::test_default_validators[bool_check-value36-ValidationError]", "tests/test_types.py::test_default_validators[bool_check-value37-ValidationError]", "tests/test_types.py::test_default_validators[bool_check-value38-ValidationError]", "tests/test_types.py::test_default_validators[bool_check-value39-ValidationError]", "tests/test_types.py::test_default_validators[bool_check-2-ValidationError0]", "tests/test_types.py::test_default_validators[bool_check-2-ValidationError1]", "tests/test_types.py::test_default_validators[bool_check-2-ValidationError2]", "tests/test_types.py::test_default_validators[bool_check-\\x81-ValidationError]", "tests/test_types.py::test_default_validators[bool_check-value44-ValidationError]", "tests/test_types.py::test_default_validators[str_check-s-s0]", "tests/test_types.py::test_default_validators[str_check-", "tests/test_types.py::test_default_validators[str_check-s-s1]", "tests/test_types.py::test_default_validators[str_check-1-1]", "tests/test_types.py::test_default_validators[str_check-xxxxxxxxxxx-ValidationError0]", "tests/test_types.py::test_default_validators[str_check-xxxxxxxxxxx-ValidationError1]", "tests/test_types.py::test_default_validators[bytes_check-s-s0]", "tests/test_types.py::test_default_validators[bytes_check-", "tests/test_types.py::test_default_validators[bytes_check-s-s1]", "tests/test_types.py::test_default_validators[bytes_check-1-1]", "tests/test_types.py::test_default_validators[bytes_check-value57-xx]", "tests/test_types.py::test_default_validators[bytes_check-True-True]", "tests/test_types.py::test_default_validators[bytes_check-False-False]", "tests/test_types.py::test_default_validators[bytes_check-value60-ValidationError]", "tests/test_types.py::test_default_validators[bytes_check-xxxxxxxxxxx-ValidationError0]", "tests/test_types.py::test_default_validators[bytes_check-xxxxxxxxxxx-ValidationError1]", "tests/test_types.py::test_default_validators[int_check-1-10]", "tests/test_types.py::test_default_validators[int_check-1.9-1]", "tests/test_types.py::test_default_validators[int_check-1-11]", "tests/test_types.py::test_default_validators[int_check-1.9-ValidationError]", "tests/test_types.py::test_default_validators[int_check-1-12]", "tests/test_types.py::test_default_validators[int_check-12-120]", "tests/test_types.py::test_default_validators[int_check-12-121]", "tests/test_types.py::test_default_validators[int_check-12-122]", "tests/test_types.py::test_default_validators[float_check-1-1.00]", "tests/test_types.py::test_default_validators[float_check-1.0-1.00]", "tests/test_types.py::test_default_validators[float_check-1.0-1.01]", "tests/test_types.py::test_default_validators[float_check-1-1.01]", "tests/test_types.py::test_default_validators[float_check-1.0-1.02]", "tests/test_types.py::test_default_validators[float_check-1-1.02]", "tests/test_types.py::test_default_validators[uuid_check-ebcdab58-6eb8-46fb-a190-d07a33e9eac8-result77]", "tests/test_types.py::test_default_validators[uuid_check-value78-result78]", "tests/test_types.py::test_default_validators[uuid_check-ebcdab58-6eb8-46fb-a190-d07a33e9eac8-result79]", "tests/test_types.py::test_default_validators[uuid_check-\\x124Vx\\x124Vx\\x124Vx\\x124Vx-result80]", "tests/test_types.py::test_default_validators[uuid_check-ebcdab58-6eb8-46fb-a190--ValidationError]", "tests/test_types.py::test_default_validators[uuid_check-123-ValidationError]", "tests/test_types.py::test_default_validators[decimal_check-42.24-result83]", "tests/test_types.py::test_default_validators[decimal_check-42.24-result84]", "tests/test_types.py::test_default_validators[decimal_check-42.24-result85]", "tests/test_types.py::test_default_validators[decimal_check-", "tests/test_types.py::test_default_validators[decimal_check-value87-result87]", "tests/test_types.py::test_default_validators[decimal_check-not", "tests/test_types.py::test_default_validators[decimal_check-NaN-ValidationError]", "tests/test_types.py::test_string_too_long", "tests/test_types.py::test_string_too_short", "tests/test_types.py::test_datetime_successful", "tests/test_types.py::test_datetime_errors", "tests/test_types.py::test_enum_successful", "tests/test_types.py::test_enum_fails", "tests/test_types.py::test_int_enum_successful_for_str_int", "tests/test_types.py::test_enum_type", "tests/test_types.py::test_int_enum_type", "tests/test_types.py::test_string_success", "tests/test_types.py::test_string_fails", "tests/test_types.py::test_dict", "tests/test_types.py::test_list_success[value0-result0]", "tests/test_types.py::test_list_success[value1-result1]", "tests/test_types.py::test_list_success[value2-result2]", "tests/test_types.py::test_list_success[<genexpr>-result3]", "tests/test_types.py::test_list_success[value4-result4]", "tests/test_types.py::test_list_fails[1230]", "tests/test_types.py::test_list_fails[1231]", "tests/test_types.py::test_ordered_dict", "tests/test_types.py::test_tuple_success[value0-result0]", "tests/test_types.py::test_tuple_success[value1-result1]", "tests/test_types.py::test_tuple_success[value2-result2]", "tests/test_types.py::test_tuple_success[<genexpr>-result3]", "tests/test_types.py::test_tuple_success[value4-result4]", "tests/test_types.py::test_tuple_fails[1230]", "tests/test_types.py::test_tuple_fails[1231]", "tests/test_types.py::test_tuple_variable_len_success[value0-int-result0]", "tests/test_types.py::test_tuple_variable_len_success[value1-int-result1]", "tests/test_types.py::test_tuple_variable_len_success[<genexpr>-int-result2]", "tests/test_types.py::test_tuple_variable_len_success[value3-str-result3]", "tests/test_types.py::test_tuple_variable_len_fails[value0-str-exc0]", "tests/test_types.py::test_tuple_variable_len_fails[value1-str-exc1]", "tests/test_types.py::test_set_success[value0-result0]", "tests/test_types.py::test_set_success[value1-result1]", "tests/test_types.py::test_set_success[value2-result2]", "tests/test_types.py::test_set_success[value3-result3]", "tests/test_types.py::test_set_fails[1230]", "tests/test_types.py::test_set_fails[1231]", "tests/test_types.py::test_list_type_fails", "tests/test_types.py::test_set_type_fails", "tests/test_types.py::test_sequence_success[int-value0-result0]", "tests/test_types.py::test_sequence_success[int-value1-result1]", "tests/test_types.py::test_sequence_success[int-value2-result2]", "tests/test_types.py::test_sequence_success[float-value3-result3]", "tests/test_types.py::test_sequence_success[cls4-value4-result4]", "tests/test_types.py::test_sequence_success[cls5-value5-result5]", "tests/test_types.py::test_sequence_generator_success[int-<genexpr>-result0]", "tests/test_types.py::test_sequence_generator_success[float-<genexpr>-result1]", "tests/test_types.py::test_sequence_generator_success[str-<genexpr>-result2]", "tests/test_types.py::test_infinite_iterable", "tests/test_types.py::test_invalid_iterable", "tests/test_types.py::test_infinite_iterable_validate_first", "tests/test_types.py::test_sequence_generator_fails[int-<genexpr>-errors0]", "tests/test_types.py::test_sequence_generator_fails[float-<genexpr>-errors1]", "tests/test_types.py::test_sequence_fails[int-value0-errors0]", "tests/test_types.py::test_sequence_fails[int-value1-errors1]", "tests/test_types.py::test_sequence_fails[float-value2-errors2]", "tests/test_types.py::test_sequence_fails[float-value3-errors3]", "tests/test_types.py::test_sequence_fails[float-value4-errors4]", "tests/test_types.py::test_sequence_fails[cls5-value5-errors5]", "tests/test_types.py::test_sequence_fails[cls6-value6-errors6]", "tests/test_types.py::test_sequence_fails[cls7-value7-errors7]", "tests/test_types.py::test_int_validation", "tests/test_types.py::test_float_validation", "tests/test_types.py::test_strict_bytes", "tests/test_types.py::test_strict_bytes_max_length", "tests/test_types.py::test_strict_bytes_subclass", "tests/test_types.py::test_strict_str", "tests/test_types.py::test_strict_str_subclass", "tests/test_types.py::test_strict_bool", "tests/test_types.py::test_strict_int", "tests/test_types.py::test_strict_int_subclass", "tests/test_types.py::test_strict_float", "tests/test_types.py::test_strict_float_subclass", "tests/test_types.py::test_bool_unhashable_fails", "tests/test_types.py::test_uuid_error", "tests/test_types.py::test_uuid_validation", "tests/test_types.py::test_anystr_strip_whitespace[True-", "tests/test_types.py::test_anystr_strip_whitespace[False-", "tests/test_types.py::test_anystr_upper[True-ABCDefG-abCD1Fg-ABCDEFG-ABCD1FG]", "tests/test_types.py::test_anystr_upper[False-ABCDefG-abCD1Fg-ABCDefG-abCD1Fg]", "tests/test_types.py::test_anystr_lower[True-ABCDefG-abCD1Fg-abcdefg-abcd1fg]", "tests/test_types.py::test_anystr_lower[False-ABCDefG-abCD1Fg-ABCDefG-abCD1Fg]", "tests/test_types.py::test_decimal_validation[type_args0-value0-result0]", "tests/test_types.py::test_decimal_validation[type_args1-value1-result1]", "tests/test_types.py::test_decimal_validation[type_args2-value2-result2]", "tests/test_types.py::test_decimal_validation[type_args3-value3-result3]", "tests/test_types.py::test_decimal_validation[type_args4-value4-result4]", "tests/test_types.py::test_decimal_validation[type_args5-value5-result5]", "tests/test_types.py::test_decimal_validation[type_args6-value6-result6]", "tests/test_types.py::test_decimal_validation[type_args7-value7-result7]", "tests/test_types.py::test_decimal_validation[type_args8-value8-result8]", "tests/test_types.py::test_decimal_validation[type_args9-value9-result9]", "tests/test_types.py::test_decimal_validation[type_args10-value10-result10]", "tests/test_types.py::test_decimal_validation[type_args11-value11-result11]", "tests/test_types.py::test_decimal_validation[type_args12-value12-result12]", "tests/test_types.py::test_decimal_validation[type_args13-value13-result13]", "tests/test_types.py::test_decimal_validation[type_args14-value14-result14]", "tests/test_types.py::test_decimal_validation[type_args15-value15-result15]", "tests/test_types.py::test_decimal_validation[type_args16-value16-result16]", "tests/test_types.py::test_decimal_validation[type_args17-value17-result17]", "tests/test_types.py::test_decimal_validation[type_args18-value18-result18]", "tests/test_types.py::test_decimal_validation[type_args19-value19-result19]", "tests/test_types.py::test_decimal_validation[type_args20-value20-result20]", "tests/test_types.py::test_decimal_validation[type_args21-NaN-result21]", "tests/test_types.py::test_decimal_validation[type_args22--NaN-result22]", "tests/test_types.py::test_decimal_validation[type_args23-+NaN-result23]", "tests/test_types.py::test_decimal_validation[type_args24-sNaN-result24]", "tests/test_types.py::test_decimal_validation[type_args25--sNaN-result25]", "tests/test_types.py::test_decimal_validation[type_args26-+sNaN-result26]", "tests/test_types.py::test_decimal_validation[type_args27-Inf-result27]", "tests/test_types.py::test_decimal_validation[type_args28--Inf-result28]", "tests/test_types.py::test_decimal_validation[type_args29-+Inf-result29]", "tests/test_types.py::test_decimal_validation[type_args30-Infinity-result30]", "tests/test_types.py::test_decimal_validation[type_args31--Infinity-result31]", "tests/test_types.py::test_decimal_validation[type_args32--Infinity-result32]", "tests/test_types.py::test_decimal_validation[type_args33-value33-result33]", "tests/test_types.py::test_decimal_validation[type_args34-value34-result34]", "tests/test_types.py::test_decimal_validation[type_args35-value35-result35]", "tests/test_types.py::test_decimal_validation[type_args36-value36-result36]", "tests/test_types.py::test_decimal_validation[type_args37-value37-result37]", "tests/test_types.py::test_decimal_validation[type_args38-value38-result38]", "tests/test_types.py::test_decimal_validation[type_args39-value39-result39]", "tests/test_types.py::test_decimal_validation[type_args40-value40-result40]", "tests/test_types.py::test_decimal_validation[type_args41-value41-result41]", "tests/test_types.py::test_decimal_validation[type_args42-value42-result42]", "tests/test_types.py::test_decimal_validation[type_args43-value43-result43]", "tests/test_types.py::test_decimal_validation[type_args44-value44-result44]", "tests/test_types.py::test_decimal_validation[type_args45-value45-result45]", "tests/test_types.py::test_path_validation_success[/test/path-result0]", "tests/test_types.py::test_path_validation_success[value1-result1]", "tests/test_types.py::test_path_validation_fails", "tests/test_types.py::test_file_path_validation_success[tests/test_types.py-result0]", "tests/test_types.py::test_file_path_validation_success[value1-result1]", "tests/test_types.py::test_file_path_validation_fails[nonexistentfile-errors0]", "tests/test_types.py::test_file_path_validation_fails[value1-errors1]", "tests/test_types.py::test_file_path_validation_fails[tests-errors2]", "tests/test_types.py::test_file_path_validation_fails[value3-errors3]", "tests/test_types.py::test_directory_path_validation_success[tests-result0]", "tests/test_types.py::test_directory_path_validation_success[value1-result1]", "tests/test_types.py::test_directory_path_validation_fails[nonexistentdirectory-errors0]", "tests/test_types.py::test_directory_path_validation_fails[value1-errors1]", "tests/test_types.py::test_directory_path_validation_fails[tests/test_types.py-errors2]", "tests/test_types.py::test_directory_path_validation_fails[value3-errors3]", "tests/test_types.py::test_number_gt", "tests/test_types.py::test_number_ge", "tests/test_types.py::test_number_lt", "tests/test_types.py::test_number_le", "tests/test_types.py::test_number_multiple_of_int_valid[10]", "tests/test_types.py::test_number_multiple_of_int_valid[100]", "tests/test_types.py::test_number_multiple_of_int_valid[20]", "tests/test_types.py::test_number_multiple_of_int_invalid[1337]", "tests/test_types.py::test_number_multiple_of_int_invalid[23]", "tests/test_types.py::test_number_multiple_of_int_invalid[6]", "tests/test_types.py::test_number_multiple_of_int_invalid[14]", "tests/test_types.py::test_number_multiple_of_float_valid[0.2]", "tests/test_types.py::test_number_multiple_of_float_valid[0.3]", "tests/test_types.py::test_number_multiple_of_float_valid[0.4]", "tests/test_types.py::test_number_multiple_of_float_valid[0.5]", "tests/test_types.py::test_number_multiple_of_float_valid[1]", "tests/test_types.py::test_number_multiple_of_float_invalid[0.07]", "tests/test_types.py::test_number_multiple_of_float_invalid[1.27]", "tests/test_types.py::test_number_multiple_of_float_invalid[1.003]", "tests/test_types.py::test_bounds_config_exceptions[conint]", "tests/test_types.py::test_bounds_config_exceptions[confloat]", "tests/test_types.py::test_bounds_config_exceptions[condecimal]", "tests/test_types.py::test_new_type_success", "tests/test_types.py::test_new_type_fails", "tests/test_types.py::test_json_any_is_json", "tests/test_types.py::test_valid_simple_json", "tests/test_types.py::test_valid_simple_json_any", "tests/test_types.py::test_invalid_simple_json", "tests/test_types.py::test_invalid_simple_json_any", "tests/test_types.py::test_valid_simple_json_bytes", "tests/test_types.py::test_valid_detailed_json", "tests/test_types.py::test_invalid_detailed_json_value_error", "tests/test_types.py::test_valid_detailed_json_bytes", "tests/test_types.py::test_valid_model_json", "tests/test_types.py::test_invalid_model_json", "tests/test_types.py::test_invalid_detailed_json_type_error", "tests/test_types.py::test_json_not_str", "tests/test_types.py::test_json_pre_validator", "tests/test_types.py::test_json_optional_simple", "tests/test_types.py::test_json_optional_complex", "tests/test_types.py::test_json_explicitly_required", "tests/test_types.py::test_json_no_default", "tests/test_types.py::test_pattern[Pattern]", "tests/test_types.py::test_pattern[pattern_type1]", "tests/test_types.py::test_pattern_error[Pattern]", "tests/test_types.py::test_pattern_error[pattern_type1]", "tests/test_types.py::test_secretfield", "tests/test_types.py::test_secretstr", "tests/test_types.py::test_secretstr_is_secret_field", "tests/test_types.py::test_secretstr_equality", "tests/test_types.py::test_secretstr_idempotent", "tests/test_types.py::test_secretstr_error", "tests/test_types.py::test_secretstr_min_max_length", "tests/test_types.py::test_secretbytes", "tests/test_types.py::test_secretbytes_is_secret_field", "tests/test_types.py::test_secretbytes_equality", "tests/test_types.py::test_secretbytes_idempotent", "tests/test_types.py::test_secretbytes_error", "tests/test_types.py::test_secretbytes_min_max_length", "tests/test_types.py::test_secrets_schema[no-constrains-SecretStr]", "tests/test_types.py::test_secrets_schema[no-constrains-SecretBytes]", "tests/test_types.py::test_secrets_schema[min-constraint-SecretStr]", "tests/test_types.py::test_secrets_schema[min-constraint-SecretBytes]", "tests/test_types.py::test_secrets_schema[max-constraint-SecretStr]", "tests/test_types.py::test_secrets_schema[max-constraint-SecretBytes]", "tests/test_types.py::test_secrets_schema[min-max-constraints-SecretStr]", "tests/test_types.py::test_secrets_schema[min-max-constraints-SecretBytes]", "tests/test_types.py::test_generic_without_params", "tests/test_types.py::test_generic_without_params_error", "tests/test_types.py::test_literal_single", "tests/test_types.py::test_literal_multiple", "tests/test_types.py::test_unsupported_field_type", "tests/test_types.py::test_frozenset_field", "tests/test_types.py::test_frozenset_field_conversion[value0-result0]", "tests/test_types.py::test_frozenset_field_conversion[value1-result1]", "tests/test_types.py::test_frozenset_field_conversion[value2-result2]", "tests/test_types.py::test_frozenset_field_conversion[value3-result3]", "tests/test_types.py::test_frozenset_field_not_convertible", "tests/test_types.py::test_bytesize_conversions[1-1-1.0B-1.0B]", "tests/test_types.py::test_bytesize_conversions[1.0-1-1.0B-1.0B]", "tests/test_types.py::test_bytesize_conversions[1b-1-1.0B-1.0B]", "tests/test_types.py::test_bytesize_conversions[1.5", "tests/test_types.py::test_bytesize_conversions[5.1kib-5222-5.1KiB-5.2KB]", "tests/test_types.py::test_bytesize_conversions[6.2EiB-7148113328562451456-6.2EiB-7.1EB]", "tests/test_types.py::test_bytesize_to", "tests/test_types.py::test_bytesize_raises", "tests/test_types.py::test_deque_success", "tests/test_types.py::test_deque_generic_success[int-value0-result0]", "tests/test_types.py::test_deque_generic_success[int-value1-result1]", "tests/test_types.py::test_deque_generic_success[int-value2-result2]", "tests/test_types.py::test_deque_generic_success[float-value3-result3]", "tests/test_types.py::test_deque_generic_success[cls4-value4-result4]", "tests/test_types.py::test_deque_generic_success[cls5-value5-result5]", "tests/test_types.py::test_deque_generic_success[str-value6-result6]", "tests/test_types.py::test_deque_generic_success[int-value7-result7]", "tests/test_types.py::test_deque_fails[int-value0-errors0]", "tests/test_types.py::test_deque_fails[int-value1-errors1]", "tests/test_types.py::test_deque_fails[float-value2-errors2]", "tests/test_types.py::test_deque_fails[float-value3-errors3]", "tests/test_types.py::test_deque_fails[float-value4-errors4]", "tests/test_types.py::test_deque_fails[cls5-value5-errors5]", "tests/test_types.py::test_deque_fails[cls6-value6-errors6]", "tests/test_types.py::test_deque_fails[cls7-value7-errors7]", "tests/test_types.py::test_deque_model", "tests/test_types.py::test_deque_json", "tests/test_types.py::test_none[None]", "tests/test_types.py::test_none[NoneType0]", "tests/test_types.py::test_none[NoneType1]", "tests/test_types.py::test_none[value_type3]", "tests/test_types.py::test_default_union_types", "tests/test_types.py::test_smart_union_types", "tests/test_types.py::test_default_union_class", "tests/test_types.py::test_smart_union_class", "tests/test_types.py::test_default_union_subclass", "tests/test_types.py::test_smart_union_subclass", "tests/test_types.py::test_default_union_compound_types", "tests/test_types.py::test_smart_union_compound_types", "tests/test_types.py::test_smart_union_compouned_types_edge_case", "tests/test_types.py::test_smart_union_typeddict", "tests/test_types.py::test_past_date_validation_success[1996-01-22-result0]", "tests/test_types.py::test_past_date_validation_success[value1-result1]", "tests/test_types.py::test_past_date_validation_fails[value0]", "tests/test_types.py::test_past_date_validation_fails[value1]", "tests/test_types.py::test_past_date_validation_fails[value2]", "tests/test_types.py::test_past_date_validation_fails[value3]", "tests/test_types.py::test_past_date_validation_fails[2064-06-01]", "tests/test_types.py::test_future_date_validation_success[value0-result0]", "tests/test_types.py::test_future_date_validation_success[value1-result1]", "tests/test_types.py::test_future_date_validation_success[2064-06-01-result2]", "tests/test_types.py::test_future_date_validation_fails[value0]", "tests/test_types.py::test_future_date_validation_fails[value1]", "tests/test_types.py::test_future_date_validation_fails[value2]", "tests/test_types.py::test_future_date_validation_fails[value3]", "tests/test_types.py::test_future_date_validation_fails[1996-01-22]" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2022-08-19 07:20:12+00:00
mit
4,875
pydantic__pydantic-4406
diff --git a/docs/examples/settings_with_custom_parsing.py b/docs/examples/settings_with_custom_parsing.py new file mode 100644 --- /dev/null +++ b/docs/examples/settings_with_custom_parsing.py @@ -0,0 +1,19 @@ +import os +from typing import Any, List + +from pydantic import BaseSettings + + +class Settings(BaseSettings): + numbers: List[int] + + class Config: + @classmethod + def parse_env_var(cls, field_name: str, raw_val: str) -> Any: + if field_name == 'numbers': + return [int(x) for x in raw_val.split(',')] + return cls.json_loads(raw_val) + + +os.environ['numbers'] = '1,2,3' +print(Settings().dict()) diff --git a/pydantic/env_settings.py b/pydantic/env_settings.py --- a/pydantic/env_settings.py +++ b/pydantic/env_settings.py @@ -126,6 +126,10 @@ def customise_sources( ) -> Tuple[SettingsSourceCallable, ...]: return init_settings, env_settings, file_secret_settings + @classmethod + def parse_env_var(cls, field_name: str, raw_val: str) -> Any: + return cls.json_loads(raw_val) + # populated by the metaclass using the Config class defined above, annotated here to help IDEs only __config__: ClassVar[Type[Config]] @@ -180,7 +184,7 @@ def __call__(self, settings: BaseSettings) -> Dict[str, Any]: # noqa C901 if env_val is not None: break - is_complex, allow_json_failure = self.field_is_complex(field) + is_complex, allow_parse_failure = self.field_is_complex(field) if is_complex: if env_val is None: # field is complex but no value found so far, try explode_env_vars @@ -190,10 +194,10 @@ def __call__(self, settings: BaseSettings) -> Dict[str, Any]: # noqa C901 else: # field is complex and there's a value, decode that as JSON, then add explode_env_vars try: - env_val = settings.__config__.json_loads(env_val) + env_val = settings.__config__.parse_env_var(field.name, env_val) except ValueError as e: - if not allow_json_failure: - raise SettingsError(f'error parsing JSON for "{env_name}"') from e + if not allow_parse_failure: + raise SettingsError(f'error parsing env var "{env_name}"') from e if isinstance(env_val, dict): d[field.alias] = deep_update(env_val, self.explode_env_vars(field, env_vars)) @@ -228,13 +232,13 @@ def field_is_complex(self, field: ModelField) -> Tuple[bool, bool]: Find out if a field is complex, and if so whether JSON errors should be ignored """ if field.is_complex(): - allow_json_failure = False + allow_parse_failure = False elif is_union(get_origin(field.type_)) and field.sub_fields and any(f.is_complex() for f in field.sub_fields): - allow_json_failure = True + allow_parse_failure = True else: return False, False - return True, allow_json_failure + return True, allow_parse_failure def explode_env_vars(self, field: ModelField, env_vars: Mapping[str, Optional[str]]) -> Dict[str, Any]: """ @@ -299,9 +303,9 @@ def __call__(self, settings: BaseSettings) -> Dict[str, Any]: secret_value = path.read_text().strip() if field.is_complex(): try: - secret_value = settings.__config__.json_loads(secret_value) + secret_value = settings.__config__.parse_env_var(field.name, secret_value) except ValueError as e: - raise SettingsError(f'error parsing JSON for "{env_name}"') from e + raise SettingsError(f'error parsing env var "{env_name}"') from e secrets[field.alias] = secret_value else:
pydantic/pydantic
d501c39f2bae9cb0da5f8e1b59dab6f0f64640af
I think we should emove the `if field.is_complex()` bit of `BaseSettings` and replace it with a universal validator `validate('*', pre=True)` which tries decoding JSON, but also in the case of lists supports comma separated lists. That way you could easily override the validator if you so wished. I think this should be backwards compatible so could be done before v2. PR welcome. Hi @samuelcolvin, I took a stab at your suggested implementation of moving the json decoding out of the `_build_environ` method and into a universal validator. Here is what that looks like (before trying to add in any parsing of comma-separated lists): ```python class BaseSettings(BaseModel): ... @validator('*', pre=True) def validate_env_vars(cls, v, config, field): if isinstance(v, str) and field.is_complex(): try: return config.json_loads(v) # type: ignore except ValueError as e: raise SettingsError(f'error parsing JSON for "{field}"') from e return v ``` Unfortunately, this implementation ran into a problem with two tests: [`test_nested_env_with_basemodel`](https://github.com/samuelcolvin/pydantic/blob/5067508eca6222b9315b1e38a30ddc975dee05e7/tests/test_settings.py#L56-L68) and [`test_nested_env_with_dict`](https://github.com/samuelcolvin/pydantic/blob/5067508eca6222b9315b1e38a30ddc975dee05e7/tests/test_settings.py#L71-L79). These two tests have an field `top` that is an inner mapping with fields `apple` and `banana`. These two fields are specified in different places and stitched together: dict `{'apple': 'value'}` is passed into the constructor and the string `'{"banana": "secret_value"}'` is set as an environment variable. In the [previous implementation](https://github.com/samuelcolvin/pydantic/blob/5067508eca6222b9315b1e38a30ddc975dee05e7/pydantic/env_settings.py#L26-L31), everything happens inside `__init__`: `_build_environ` is run first, which decodes the banana json into a dict, and then they are stitched together with the `deep_update` function. Moving the json decoding into a validator breaks this functionality because it runs after `__init__`. Because the banana mapping is still a string when `__init__` runs, `deep_update` isn't able to merge them and instead replaces the banana dict with the apple dict. ## Option A: Drop support for merging nested objects One option would be to drop support for merging nested objects. Complex environment variables seems like an unusual use case to start with, and needing to merge partially specified ones from different sources seems even more unusual. I discussed this with @pjbull and this is what we like the most: it would simplify the code and remove the need for a deep update (a shallow update would be enough). ## Option B: Merging input streams after the universal decoding validator Currently input streams are merged in `__init__` before running the validators. We could try an approach where the universal validator that does decoding runs on each of the input streams first, and then they get merged after. This doesn't really fit into the existing flow very neatly and would involve making some part of the validation flow more complex. ## Option C: Keeping decoding in _build_environ and use a different approach Such as the approaches that @pjbull brainstormed. I faced this issue today, as well. I wanted to parse something like this ``` REDIS_SENTINELS=192.168.0.1 192.168.0.2 ``` using such a settings class: ``` class S(BaseSettings): sentinels: List[str] = Field(..., env='REDIS_SENTINELS') @validator('sentinels', pre=True) def validate(cls, val): return val.split(' ') ``` Ditto, I'd like to validate a string env var and transform it into a valid submodel. For example, `MY_DB=user:pass@server?max_connections=100` -> a settings model containing a DB submodel with valid DSN and other settings. Currently, it seems I can only pass MY_DB as a stringified JSON object. Given the complexity of these potential use cases, I'm kind of liking something like proposal (1) in the first comment in this thread. I may have some time on Friday to implement if that approach is interesting hi all, I'm also faced with this issue today. taking into account [this example](https://github.com/tiangolo/full-stack-fastapi-postgresql/blob/0.5.0/%7B%7Bcookiecutter.project_slug%7D%7D/backend/app/app/core/config.py), after almost a day of digging I realized that validator is not fired in case the class attribute is of List-type. If attribute type is str, for example, the attribute validator works just fine. I used this code: ```python import os from typing import List from pydantic import BaseSettings, validator os.environ['test_var'] = 'test_val' class S1(BaseSettings): test_var: str @validator('test_var', pre=True) def val_func(cls, v): print('this validator is called: {}'.format(v)) return v class S2(BaseSettings): test_var: List[str] @validator('test_var', pre=True) def val_func(cls, v): print('this validator is called: {}'.format(v)) return [v] ``` and then instantiating `s1 = S1()` prints `this validator is called: test_val` while the code `s2 = S2()` throws errors and prints nothing: ``` >>> s2 = S2() Traceback (most recent call last): File "pydantic/env_settings.py", line 118, in pydantic.env_settings.BaseSettings._build_environ File "/home/den/anaconda3/lib/python3.7/json/__init__.py", line 348, in loads return _default_decoder.decode(s) File "/home/den/anaconda3/lib/python3.7/json/decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/home/den/anaconda3/lib/python3.7/json/decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<input>", line 1, in <module> File "pydantic/env_settings.py", line 35, in pydantic.env_settings.BaseSettings.__init__ File "pydantic/env_settings.py", line 48, in pydantic.env_settings.BaseSettings._build_values File "pydantic/env_settings.py", line 120, in pydantic.env_settings.BaseSettings._build_environ pydantic.env_settings.SettingsError: error parsing JSON for "test_var" ``` is there any errors in my example code? @zdens per some of the discussion earlier in the thread (kind of mixed in there with proposed changes), the reason you don't see the validator firing is because the code that is failing is the part that parses the environment variables, and that happens before the validators run. Your variable that is the list needs to be valid JSON, like this: ``` OPTIONS='["a","b","c"]' ``` That's why you see a `JSONDecodeError`. @jayqi , thank you for your reply! now I understood why this thread has been started. As a workaround (until something solid is implemented) I changed the following ```python3 CORS_ORIGINS: List[AnyHttpUrl] = Field(..., env="CORS_ORIGINS") ``` into this: ```python3 CORS_ORIGINS: Union[str, List[AnyHttpUrl]] = Field(..., env="CORS_ORIGINS") ``` Which, admittedly, is not elegant but enables pydantic to fire up the validator function: ```python3 @validator("CORS_ORIGINS", pre=True) def _assemble_cors_origins(cls, cors_origins): if isinstance(cors_origins, str): return [item.strip() for item in cors_origins.split(",")] return cors_origins ``` My `.env` file: ```env # Use comma (,) to separate URLs CORS_ORIGINS=http://localhost:3000,http://localhost:8000 ``` I've just discovered how annoying this can be myself while working on a github action for pydantic 🙈. I'd love someone to fix this, otherwise I will soon. I planned on working on https://github.com/samuelcolvin/pydantic/pull/1848 again soon (re-implement/finish it), but after finishing with https://github.com/samuelcolvin/pydantic/pull/2721 🎉 I think that if #1848 goes in then we can check for those types here: https://github.com/samuelcolvin/pydantic/blob/42395056e18dfaa3ef299373374ab3b12bb196ac/pydantic/env_settings.py#L170-L174 And then we can keep the JSON fallback behavior as well. I suggest that this issue should also consider adding the ability to parse environment variables into dictionaries directly: ```python import os from typing import Optional, Dict from pydantic import BaseSettings, Field, validator os.environ["COLORS"] = "red:#FF0000,blue:#0000FF,green:#00FF00" class Example(BaseSettings): colors: Optional[Dict[str, str]] = Field(None, env="COLORS") # Result would be: colors = {"red": "#FF0000", "blue": "#0000FF", "green": "#00FF00"} ``` It seems with the addition of `SecretsSettingsSource` the parsing code got a little bit duplicate. I think that now it makes more sense to follow Option 1 described by @pjbull, but also to delegate the whole parsing logic to the Field, i.e: `field.parse(value)`, instead of having the following code in all sources ``` if field.is_complex(): try: secret_value = settings.__config__.json_loads(secret_value) except ValueError as e: raise SettingsError(f'error parsing JSON for "{env_name}"') from e ``` I could try this implementation if desired @samuelcolvin.
diff --git a/tests/test_settings.py b/tests/test_settings.py --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -3,7 +3,7 @@ import uuid from datetime import datetime, timezone from pathlib import Path -from typing import Any, Dict, List, Optional, Set, Tuple, Union +from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union import pytest @@ -221,7 +221,7 @@ def test_set_dict_model(env): def test_invalid_json(env): env.set('apples', '["russet", "granny smith",]') - with pytest.raises(SettingsError, match='error parsing JSON for "apples"'): + with pytest.raises(SettingsError, match='error parsing env var "apples"'): ComplexSettings() @@ -1054,7 +1054,7 @@ class Settings(BaseSettings): class Config: secrets_dir = tmp_path - with pytest.raises(SettingsError, match='error parsing JSON for "foo"'): + with pytest.raises(SettingsError, match='error parsing env var "foo"'): Settings() @@ -1215,3 +1215,66 @@ def test_builtins_settings_source_repr(): == "EnvSettingsSource(env_file='.env', env_file_encoding='utf-8', env_nested_delimiter=None)" ) assert repr(SecretsSettingsSource(secrets_dir='/secrets')) == "SecretsSettingsSource(secrets_dir='/secrets')" + + +def _parse_custom_dict(value: str) -> Callable[[str], Dict[int, str]]: + """A custom parsing function passed into env parsing test.""" + res = {} + for part in value.split(','): + k, v = part.split('=') + res[int(k)] = v + return res + + +def test_env_setting_source_custom_env_parse(env): + class Settings(BaseSettings): + top: Dict[int, str] + + class Config: + @classmethod + def parse_env_var(cls, field_name: str, raw_val: str): + if field_name == 'top': + return _parse_custom_dict(raw_val) + return cls.json_loads(raw_val) + + with pytest.raises(ValidationError): + Settings() + env.set('top', '1=apple,2=banana') + s = Settings() + assert s.top == {1: 'apple', 2: 'banana'} + + +def test_env_settings_source_custom_env_parse_is_bad(env): + class Settings(BaseSettings): + top: Dict[int, str] + + class Config: + @classmethod + def parse_env_var(cls, field_name: str, raw_val: str): + if field_name == 'top': + return int(raw_val) + return cls.json_loads(raw_val) + + env.set('top', '1=apple,2=banana') + with pytest.raises(SettingsError, match='error parsing env var "top"'): + Settings() + + +def test_secret_settings_source_custom_env_parse(tmp_path): + p = tmp_path / 'top' + p.write_text('1=apple,2=banana') + + class Settings(BaseSettings): + top: Dict[int, str] + + class Config: + secrets_dir = tmp_path + + @classmethod + def parse_env_var(cls, field_name: str, raw_val: str): + if field_name == 'top': + return _parse_custom_dict(raw_val) + return cls.json_loads(raw_val) + + s = Settings() + assert s.top == {1: 'apple', 2: 'banana'}
Settings: Custom parsing of environment variables (non-JSON) # Settings: Custom parsing of environment variables (non-JSON) Often we want complex environment variables that are not represented as JSON. One example is a list of items. It's not uncommon to comma-delimit lists like this in bash: ```python import os from typing import List from pydantic import BaseSettings os.environ['options'] = "a,b,c" class Settings(BaseSettings): options: List s = Settings() ``` This results in a `JSONDecodeError`. Writing a list of items as valid json is error prone and not human friendly to read in the context of environment variables. ### Workaround One workaround is to store the variable as valid json, which is tricky to type correctly in lots of systems where you have to enter environment variables: ``` OPTIONS='["a","b","c"]' ``` Another (simplified) workaround is to set `json_loads`. but its not very elegant since `json_loads` doesn't know what field its is parsing, which could be error prone: ```python import json import os from typing import List from pydantic import BaseSettings, BaseModel, root_validator os.environ['options'] = "a,b,c" def list_parse_fallback(v): try: return json.loads(v) except Exception as e: return v.split(",") class Settings(BaseSettings): options: List class Config: json_loads = list_parse_fallback s = Settings() ``` I can see a couple options for implementing the fix: ### 1. Store the parsing method in the field info extra: ```python parse_func = lambda x: x.split(",") class Settings(BaseSettings): options: List = Field(..., env_parse=parse_func) ``` If we take this approach, I think that we can update this logic branch: https://github.com/samuelcolvin/pydantic/blob/42395056e18dfaa3ef299373374ab3b12bb196ac/pydantic/env_settings.py#L170-L174 Adding something like the following: ```python if field.is_complex(): if field.extra.get("env_parse", None) is not None: try: env_val = field.extra["env_parse"](env_val) # type: ignore except ValueError as e: raise SettingsError(f'error with custom parsing function for "{env_name}"') from e else: try: env_val = self.__config__.json_loads(env_val) # type: ignore except ValueError as e: raise SettingsError(f'error parsing JSON for "{env_name}"') from e d[field.alias] = env_val ``` ### 2. Add a new config option just for Settings for overriding how env vars are parsed Another implementation option is to add a new property like `Settings.Config.parse_env_var` which takes the `field` and the value so that it can be overridden to handle dispatching to different parsing methods for different names/properties of `field` (currently, just overriding `json_loads` means you are passed a value without knowing where it will be stored so you have to test for and handle all of the possible settings values. ```python class BaseSettings: ... class Config: ... @classmethod def parse_env_var(cls, field, raw_val): return cls.json_loads(raw_val) ``` Then the following line is the only change that is needed: https://github.com/samuelcolvin/pydantic/blob/master/pydantic/env_settings.py#L62 Changes to `self.__config__.parse_env_var(field, env_val)` ### 3. Call field validators on the raw string instead of trying to load from json first Change the same line to: ``` env_val, ee = field.validate(env_val) # collect ee and raise errors ``` Pros: - Adding validators for fields is well documented / understood Cons: - Breaks existing JSON functionality if those fields already have validators - Mixes up the abstractions in that the functions would now do parsing and validation ### 4. Custom (de)serialization Let fields implement custom serialization/deserialization methods. Currently there is `json_encoders` but not an equivalent `json_decoders` for use per-field. There's some discussion of this here: https://github.com/samuelcolvin/pydantic/issues/951 ### 5. Something else Other ideas? Happy to implement a different suggestion. -------------- Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.5.1 pydantic compiled: True install path: /Users/bull/miniconda3/envs/sandbox/lib/python3.7/site-packages/pydantic python version: 3.7.6 (default, Jan 8 2020, 13:42:34) [Clang 4.0.1 (tags/RELEASE_401/final)] platform: Darwin-19.4.0-x86_64-i386-64bit optional deps. installed: [] ```
0.0
d501c39f2bae9cb0da5f8e1b59dab6f0f64640af
[ "tests/test_settings.py::test_invalid_json", "tests/test_settings.py::test_secrets_path_invalid_json", "tests/test_settings.py::test_env_setting_source_custom_env_parse", "tests/test_settings.py::test_env_settings_source_custom_env_parse_is_bad", "tests/test_settings.py::test_secret_settings_source_custom_env_parse" ]
[ "tests/test_settings.py::test_sub_env", "tests/test_settings.py::test_sub_env_override", "tests/test_settings.py::test_sub_env_missing", "tests/test_settings.py::test_other_setting", "tests/test_settings.py::test_with_prefix", "tests/test_settings.py::test_nested_env_with_basemodel", "tests/test_settings.py::test_merge_dict", "tests/test_settings.py::test_nested_env_delimiter", "tests/test_settings.py::test_nested_env_delimiter_with_prefix", "tests/test_settings.py::test_nested_env_delimiter_complex_required", "tests/test_settings.py::test_nested_env_delimiter_aliases", "tests/test_settings.py::test_list", "tests/test_settings.py::test_set_dict_model", "tests/test_settings.py::test_required_sub_model", "tests/test_settings.py::test_non_class", "tests/test_settings.py::test_env_str", "tests/test_settings.py::test_env_list", "tests/test_settings.py::test_env_list_field", "tests/test_settings.py::test_env_list_last", "tests/test_settings.py::test_env_inheritance", "tests/test_settings.py::test_env_inheritance_field", "tests/test_settings.py::test_env_prefix_inheritance_config", "tests/test_settings.py::test_env_inheritance_config", "tests/test_settings.py::test_env_invalid", "tests/test_settings.py::test_env_field", "tests/test_settings.py::test_aliases_warning", "tests/test_settings.py::test_aliases_no_warning", "tests/test_settings.py::test_case_sensitive", "tests/test_settings.py::test_nested_dataclass", "tests/test_settings.py::test_env_takes_precedence", "tests/test_settings.py::test_config_file_settings_nornir", "tests/test_settings.py::test_env_union_with_complex_subfields_parses_json", "tests/test_settings.py::test_env_union_with_complex_subfields_parses_plain_if_json_fails", "tests/test_settings.py::test_env_union_without_complex_subfields_does_not_parse_json", "tests/test_settings.py::test_env_file_config", "tests/test_settings.py::test_env_file_config_case_sensitive", "tests/test_settings.py::test_env_file_export", "tests/test_settings.py::test_env_file_config_custom_encoding", "tests/test_settings.py::test_env_file_home_directory", "tests/test_settings.py::test_env_file_none", "tests/test_settings.py::test_env_file_override_file", "tests/test_settings.py::test_env_file_override_none", "tests/test_settings.py::test_env_file_not_a_file", "tests/test_settings.py::test_read_env_file_cast_sensitive", "tests/test_settings.py::test_read_env_file_syntax_wrong", "tests/test_settings.py::test_env_file_example", "tests/test_settings.py::test_env_file_custom_encoding", "tests/test_settings.py::test_multiple_env_file", "tests/test_settings.py::test_multiple_env_file_encoding", "tests/test_settings.py::test_read_dotenv_vars", "tests/test_settings.py::test_read_dotenv_vars_when_env_file_is_none", "tests/test_settings.py::test_alias_set", "tests/test_settings.py::test_prefix_on_parent", "tests/test_settings.py::test_frozenset", "tests/test_settings.py::test_secrets_path", "tests/test_settings.py::test_secrets_case_sensitive", "tests/test_settings.py::test_secrets_case_insensitive", "tests/test_settings.py::test_secrets_path_url", "tests/test_settings.py::test_secrets_path_json", "tests/test_settings.py::test_secrets_missing", "tests/test_settings.py::test_secrets_invalid_secrets_dir", "tests/test_settings.py::test_secrets_missing_location", "tests/test_settings.py::test_secrets_file_is_a_directory", "tests/test_settings.py::test_secrets_dotenv_precedence", "tests/test_settings.py::test_external_settings_sources_precedence", "tests/test_settings.py::test_external_settings_sources_filter_env_vars", "tests/test_settings.py::test_customise_sources_empty", "tests/test_settings.py::test_builtins_settings_source_repr" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2022-08-19 21:39:34+00:00
mit
4,876
pydantic__pydantic-4455
diff --git a/pydantic/color.py b/pydantic/color.py --- a/pydantic/color.py +++ b/pydantic/color.py @@ -201,6 +201,9 @@ def __repr_args__(self) -> 'ReprArgs': def __eq__(self, other: Any) -> bool: return isinstance(other, Color) and self.as_rgb_tuple() == other.as_rgb_tuple() + def __hash__(self) -> int: + return hash(self.as_rgb_tuple()) + def parse_tuple(value: Tuple[Any, ...]) -> RGBA: """
pydantic/pydantic
64f24726d18db191e6677f2976c076778fdc2364
Thanks so much for reporting, I've added `napari` to #4359. Confirmed. Seems this was an unexpected side effect of #3646 I didn't know that adding `__eq__` brakes hashing. PR welcome to fix this, otherwise I'll do it soon. I just found it here (second paragraph): [`https://docs.python.org/3/reference/datamodel.html#object.__hash__`](https://docs.python.org/3/reference/datamodel.html#object.__hash__), but also do not know earlier.
diff --git a/tests/test_color.py b/tests/test_color.py --- a/tests/test_color.py +++ b/tests/test_color.py @@ -193,3 +193,9 @@ def test_eq(): assert Color('red') == Color((255, 0, 0)) assert Color('red') != Color((0, 0, 255)) + + +def test_color_hashable(): + assert hash(Color('red')) != hash(Color('blue')) + assert hash(Color('red')) == hash(Color((255, 0, 0))) + assert hash(Color('red')) != hash(Color((255, 0, 0, 0.5)))
`pydantic.color.Color` is not hashable in 1.10.0 release ### Initial Checks - [X] I have searched GitHub for a duplicate issue and I'm sure this is something new - [X] I have searched Google & StackOverflow for a solution and couldn't find anything - [X] I have read and followed [the docs](https://pydantic-docs.helpmanual.io) and still think this is a bug - [X] I am confident that the issue is with pydantic (not my code, or another library in the ecosystem like [FastAPI](https://fastapi.tiangolo.com) or [mypy](https://mypy.readthedocs.io/en/stable)) ### Description In pydantic `1.9.2` (and earlier), the Color class was Hashable. in release 1.10.0 it is not hashable that broke usage color as an argument to function decorated with `@lru_cache` from std lib. (https://github.com/napari/napari/issues/4995) A I do not see public method for mutate such object IO thin that it is deprecation. ### Example Code pydantic 1.9.2 ```Python In [1]: from pydantic.color import Color In [2]: a = Color((0,0,0)) In [3]: hash(a) Out[3]: 8771047785283 ``` pydantic 1.10.0 ```python In [1]: from pydantic.color import Color In [2]: a = Color((0,0,0)) In [3]: hash(a) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-3-57b555d30865> in <module> ----> 1 hash(a) TypeError: unhashable type: 'Color' ``` ``` ### Python, Pydantic & OS Version ```Text pydantic 1.9.2 vs pydantic 1.10.0 tested on ubuntu and macos m1. ``` ### Affected Components - [X] [Compatibility between releases](https://pydantic-docs.helpmanual.io/changelog/) - [ ] [Data validation/parsing](https://pydantic-docs.helpmanual.io/usage/models/#basic-model-usage) - [ ] [Data serialization](https://pydantic-docs.helpmanual.io/usage/exporting_models/) - `.dict()` and `.json()` - [ ] [JSON Schema](https://pydantic-docs.helpmanual.io/usage/schema/) - [ ] [Dataclasses](https://pydantic-docs.helpmanual.io/usage/dataclasses/) - [ ] [Model Config](https://pydantic-docs.helpmanual.io/usage/model_config/) - [x] [Field Types](https://pydantic-docs.helpmanual.io/usage/types/) - adding or changing a particular data type - [ ] [Function validation decorator](https://pydantic-docs.helpmanual.io/usage/validation_decorator/) - [ ] [Generic Models](https://pydantic-docs.helpmanual.io/usage/models/#generic-models) - [X] [Other Model behaviour](https://pydantic-docs.helpmanual.io/usage/models/) - `construct()`, pickling, private attributes, ORM mode - [ ] [Settings Management](https://pydantic-docs.helpmanual.io/usage/settings/) - [ ] [Plugins](https://pydantic-docs.helpmanual.io/) and integration with other tools - mypy, FastAPI, python-devtools, Hypothesis, VS Code, PyCharm, etc.
0.0
64f24726d18db191e6677f2976c076778fdc2364
[ "tests/test_color.py::test_color_hashable" ]
[ "tests/test_color.py::test_color_success[aliceblue-as_tuple0]", "tests/test_color.py::test_color_success[Antiquewhite-as_tuple1]", "tests/test_color.py::test_color_success[#000000-as_tuple2]", "tests/test_color.py::test_color_success[#DAB-as_tuple3]", "tests/test_color.py::test_color_success[#dab-as_tuple4]", "tests/test_color.py::test_color_success[#000-as_tuple5]", "tests/test_color.py::test_color_success[0x797979-as_tuple6]", "tests/test_color.py::test_color_success[0x777-as_tuple7]", "tests/test_color.py::test_color_success[0x777777-as_tuple8]", "tests/test_color.py::test_color_success[0x777777cc-as_tuple9]", "tests/test_color.py::test_color_success[777-as_tuple10]", "tests/test_color.py::test_color_success[777c-as_tuple11]", "tests/test_color.py::test_color_success[", "tests/test_color.py::test_color_success[777", "tests/test_color.py::test_color_success[raw_color15-as_tuple15]", "tests/test_color.py::test_color_success[raw_color16-as_tuple16]", "tests/test_color.py::test_color_success[raw_color17-as_tuple17]", "tests/test_color.py::test_color_success[raw_color18-as_tuple18]", "tests/test_color.py::test_color_success[rgb(0,", "tests/test_color.py::test_color_success[rgba(0,", "tests/test_color.py::test_color_success[rgba(00,0,128,0.6", "tests/test_color.py::test_color_success[hsl(270,", "tests/test_color.py::test_color_success[hsl(180,", "tests/test_color.py::test_color_success[hsl(630,", "tests/test_color.py::test_color_success[hsl(270deg,", "tests/test_color.py::test_color_success[hsl(.75turn,", "tests/test_color.py::test_color_success[hsl(-.25turn,", "tests/test_color.py::test_color_success[hsl(-0.25turn,", "tests/test_color.py::test_color_success[hsl(4.71238rad,", "tests/test_color.py::test_color_success[hsl(10.9955rad,", "tests/test_color.py::test_color_success[hsl(270.00deg,", "tests/test_color.py::test_color_fail[nosuchname]", "tests/test_color.py::test_color_fail[chucknorris]", "tests/test_color.py::test_color_fail[#0000000]", "tests/test_color.py::test_color_fail[x000]", "tests/test_color.py::test_color_fail[color4]", "tests/test_color.py::test_color_fail[color5]", "tests/test_color.py::test_color_fail[color6]", "tests/test_color.py::test_color_fail[color7]", "tests/test_color.py::test_color_fail[color8]", "tests/test_color.py::test_color_fail[color9]", "tests/test_color.py::test_color_fail[color10]", "tests/test_color.py::test_color_fail[color11]", "tests/test_color.py::test_color_fail[color12]", "tests/test_color.py::test_color_fail[color13]", "tests/test_color.py::test_color_fail[rgb(0,", "tests/test_color.py::test_color_fail[rgba(0,", "tests/test_color.py::test_color_fail[hsl(180,", "tests/test_color.py::test_color_fail[color19]", "tests/test_color.py::test_color_fail[object]", "tests/test_color.py::test_color_fail[color21]", "tests/test_color.py::test_model_validation", "tests/test_color.py::test_as_rgb", "tests/test_color.py::test_as_rgb_tuple", "tests/test_color.py::test_as_hsl", "tests/test_color.py::test_as_hsl_tuple", "tests/test_color.py::test_as_hex", "tests/test_color.py::test_as_named", "tests/test_color.py::test_str_repr", "tests/test_color.py::test_eq" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2022-08-31 08:32:34+00:00
mit
4,877
pydantic__pydantic-4471
diff --git a/pydantic/mypy.py b/pydantic/mypy.py --- a/pydantic/mypy.py +++ b/pydantic/mypy.py @@ -82,7 +82,8 @@ def parse_mypy_version(version: str) -> Tuple[int, ...]: return tuple(int(part) for part in version.split('+', 1)[0].split('.')) -BUILTINS_NAME = 'builtins' if parse_mypy_version(mypy_version) >= (0, 930) else '__builtins__' +MYPY_VERSION_TUPLE = parse_mypy_version(mypy_version) +BUILTINS_NAME = 'builtins' if MYPY_VERSION_TUPLE >= (0, 930) else '__builtins__' def plugin(version: str) -> 'TypingType[Plugin]': @@ -162,14 +163,22 @@ def _pydantic_field_callback(self, ctx: FunctionContext) -> 'Type': # Functions which use `ParamSpec` can be overloaded, exposing the callable's types as a parameter # Pydantic calls the default factory without any argument, so we retrieve the first item if isinstance(default_factory_type, Overloaded): - if float(mypy_version) > 0.910: + if MYPY_VERSION_TUPLE > (0, 910): default_factory_type = default_factory_type.items[0] else: # Mypy0.910 exposes the items of overloaded types in a function default_factory_type = default_factory_type.items()[0] # type: ignore[operator] if isinstance(default_factory_type, CallableType): - return default_factory_type.ret_type + ret_type = default_factory_type.ret_type + # mypy doesn't think `ret_type` has `args`, you'd think mypy should know, + # add this check in case it varies by version + args = getattr(ret_type, 'args', None) + if args: + if all(isinstance(arg, TypeVarType) for arg in args): + # Looks like the default factory is a type like `list` or `dict`, replace all args with `Any` + ret_type.args = tuple(default_any_type for _ in args) # type: ignore[attr-defined] + return ret_type return default_any_type
pydantic/pydantic
317bef33b06e05f65f57b1ba009dfd949b462689
Same with dict. ```python parameters: Dict[str, str] = Field(default_factory=dict) ``` error: Incompatible types in assignment (expression has type "Dict[_KT, _VT]", variable has type "Dict[str, str]") Could be related to #4086, @richardxia any idea how this can be fixed? --- By the way, @tapple @Pentusha it would be much easier for you and me if problems like this got caught before releasing v1.10. In future, please consider testing pydantic pre-releases. We had three pre-releases over 2 weeks and i talked about them a lot on twitter. > Could be related to #4086, @richardxia any idea how this can be fixed? I don't think it's related to #4086; that PR should have only affected whether the mypy plugin thinks a given field is required or not. I also tested reverting that commit locally and testing the example code in this ticket, but I still see the same error message show up. I did a git bisect, and it looks like https://github.com/pydantic/pydantic/commit/460f858cc5bc9de792b2c4f6373913a1456488aa (https://github.com/pydantic/pydantic/pull/3430) is the first commit that fails to type check the example code in this ticket. Maybe @klaa97 could take a look? @richardxia Thank you for the tag and sorry for this 🤦 I am pretty sure this comes from my commit, here in particular: https://github.com/klaa97/pydantic/blob/13e0a25cc8c3c8ec5a264f6c9635350ea6b71f3e/pydantic/mypy.py#L165 . In particular, it comes from the `default_factory` mypy check. Mypygives back a CallableType which return is `builtins.list[_T]`, and unfortunately I am not finding an easy way to "block" this behaviour. It works by specifying the type in the factory (for example a function returning `list[int]`, but in this case it fails. I wish we'd find it sooner :(, but I'm afraid I cannot find much more documentation on how to tackle this error therefore I'd say reverting the change might be the easiest fix. Thanks so much for looking into this. Maybe we could comment out that check for now and ask on the mypy repo if there's a work around? I completely agree, it looks like a plan! I could open a PR by end of the day to remove the check on `default_factory`, and proceed with the investigation on the `mypy` repo. Please tag me in the mypy discussion, I'd be interested to see what they say.
diff --git a/tests/mypy/modules/plugin_default_factory.py b/tests/mypy/modules/plugin_default_factory.py new file mode 100644 --- /dev/null +++ b/tests/mypy/modules/plugin_default_factory.py @@ -0,0 +1,21 @@ +""" +See https://github.com/pydantic/pydantic/issues/4457 +""" + +from typing import Dict, List + +from pydantic import BaseModel, Field + + +def new_list() -> List[int]: + return [] + + +class Model(BaseModel): + l1: List[str] = Field(default_factory=list) + l2: List[int] = Field(default_factory=new_list) + l3: List[str] = Field(default_factory=lambda: list()) + l4: Dict[str, str] = Field(default_factory=dict) + l5: int = Field(default_factory=lambda: 123) + l6_error: List[str] = Field(default_factory=new_list) + l7_error: int = Field(default_factory=list) diff --git a/tests/mypy/outputs/plugin-fail-strict.txt b/tests/mypy/outputs/plugin-fail-strict.txt --- a/tests/mypy/outputs/plugin-fail-strict.txt +++ b/tests/mypy/outputs/plugin-fail-strict.txt @@ -36,9 +36,8 @@ 219: error: Property "y" defined in "FrozenModel" is read-only [misc] 240: error: Incompatible types in assignment (expression has type "None", variable has type "int") [assignment] 241: error: Incompatible types in assignment (expression has type "None", variable has type "int") [assignment] -244: error: Incompatible types in assignment (expression has type "Set[_T]", variable has type "str") [assignment] +244: error: Incompatible types in assignment (expression has type "Set[Any]", variable has type "str") [assignment] 245: error: Incompatible types in assignment (expression has type "str", variable has type "int") [assignment] -246: error: Incompatible types in assignment (expression has type "List[_T]", variable has type "List[int]") [assignment] 247: error: Argument "default_factory" to "Field" has incompatible type "int"; expected "Optional[Callable[[], Any]]" [arg-type] 250: error: Field default and default_factory cannot be specified together [pydantic-field] 260: error: Missing positional argument "self" in call to "instance_method" of "ModelWithAnnotatedValidator" [call-arg] diff --git a/tests/mypy/outputs/plugin-fail.txt b/tests/mypy/outputs/plugin-fail.txt --- a/tests/mypy/outputs/plugin-fail.txt +++ b/tests/mypy/outputs/plugin-fail.txt @@ -25,9 +25,8 @@ 219: error: Property "y" defined in "FrozenModel" is read-only [misc] 240: error: Incompatible types in assignment (expression has type "None", variable has type "int") [assignment] 241: error: Incompatible types in assignment (expression has type "None", variable has type "int") [assignment] -244: error: Incompatible types in assignment (expression has type "Set[_T]", variable has type "str") [assignment] +244: error: Incompatible types in assignment (expression has type "Set[Any]", variable has type "str") [assignment] 245: error: Incompatible types in assignment (expression has type "str", variable has type "int") [assignment] -246: error: Incompatible types in assignment (expression has type "List[_T]", variable has type "List[int]") [assignment] 247: error: Argument "default_factory" to "Field" has incompatible type "int"; expected "Optional[Callable[[], Any]]" [arg-type] 250: error: Field default and default_factory cannot be specified together [pydantic-field] 260: error: Missing positional argument "self" in call to "instance_method" of "ModelWithAnnotatedValidator" [call-arg] diff --git a/tests/mypy/outputs/plugin_default_factory.txt b/tests/mypy/outputs/plugin_default_factory.txt new file mode 100644 --- /dev/null +++ b/tests/mypy/outputs/plugin_default_factory.txt @@ -0,0 +1,2 @@ +20: error: Incompatible types in assignment (expression has type "List[int]", variable has type "List[str]") [assignment] +21: error: Incompatible types in assignment (expression has type "List[Any]", variable has type "int") [assignment] diff --git a/tests/mypy/test_mypy.py b/tests/mypy/test_mypy.py --- a/tests/mypy/test_mypy.py +++ b/tests/mypy/test_mypy.py @@ -49,6 +49,7 @@ ('pyproject-plugin-strict.toml', 'plugin_fail.py', 'plugin-fail-strict.txt'), ('pyproject-plugin-strict.toml', 'fail_defaults.py', 'fail_defaults.txt'), ('mypy-plugin-strict.ini', 'settings_config.py', None), + ('mypy-plugin-strict.ini', 'plugin_default_factory.py', 'plugin_default_factory.txt'), ] executable_modules = list({fname[:-3] for _, fname, out_fname in cases if out_fname is None})
mypy error on default_factory=list in pydantic 1.10 ### Initial Checks - [X] I have searched GitHub for a duplicate issue and I'm sure this is something new - [X] I have searched Google & StackOverflow for a solution and couldn't find anything - [X] I have read and followed [the docs](https://pydantic-docs.helpmanual.io) and still think this is a bug - [X] I am confident that the issue is with pydantic (not my code, or another library in the ecosystem like [FastAPI](https://fastapi.tiangolo.com) or [mypy](https://mypy.readthedocs.io/en/stable)) ### Description mypy complains about default_factory = list in pydantic 1.10 But using [] works fine. I think this inconsistency should be fixed ``` $ mypy bug.py bug.py:6: error: Incompatible types in assignment (expression has type "List[_T]", variable has type "List[str]") Found 1 error in 1 file (checked 1 source file) ``` Also, I don't think the documentation indicates that pydantic deep-copies mutable default values. I found that out at https://stackoverflow.com/questions/63793662/how-to-give-a-pydantic-list-field-a-default-value ### Example Code ```Python from typing import List from pydantic import BaseModel, Field class Model(BaseModel): l1: List[str] = Field(default_factory=list) l2: List[str] = Field([]) l3: List[str] = [] ``` ### Python, Pydantic & OS Version ```Text pydantic version: 1.10.1 pydantic compiled: True install path: /home/mfulmer/miniconda3/envs/rk310/lib/python3.10/site-packages/pydantic python version: 3.10.4 (main, Mar 31 2022, 08:41:55) [GCC 7.5.0] platform: Linux-5.4.0-124-generic-x86_64-with-glibc2.31 optional deps. installed: ['dotenv', 'email-validator', 'typing-extensions'] ``` ### Affected Components - [ ] [Compatibility between releases](https://pydantic-docs.helpmanual.io/changelog/) - [ ] [Data validation/parsing](https://pydantic-docs.helpmanual.io/usage/models/#basic-model-usage) - [ ] [Data serialization](https://pydantic-docs.helpmanual.io/usage/exporting_models/) - `.dict()` and `.json()` - [ ] [JSON Schema](https://pydantic-docs.helpmanual.io/usage/schema/) - [ ] [Dataclasses](https://pydantic-docs.helpmanual.io/usage/dataclasses/) - [ ] [Model Config](https://pydantic-docs.helpmanual.io/usage/model_config/) - [ ] [Field Types](https://pydantic-docs.helpmanual.io/usage/types/) - adding or changing a particular data type - [ ] [Function validation decorator](https://pydantic-docs.helpmanual.io/usage/validation_decorator/) - [ ] [Generic Models](https://pydantic-docs.helpmanual.io/usage/models/#generic-models) - [ ] [Other Model behaviour](https://pydantic-docs.helpmanual.io/usage/models/) - `construct()`, pickling, private attributes, ORM mode - [ ] [Settings Management](https://pydantic-docs.helpmanual.io/usage/settings/) - [X] [Plugins](https://pydantic-docs.helpmanual.io/) and integration with other tools - mypy, FastAPI, python-devtools, Hypothesis, VS Code, PyCharm, etc.
0.0
317bef33b06e05f65f57b1ba009dfd949b462689
[ "tests/mypy/test_mypy.py::test_mypy_results[mypy-plugin.ini-plugin_fail.py-plugin-fail.txt]", "tests/mypy/test_mypy.py::test_mypy_results[mypy-plugin-strict.ini-plugin_fail.py-plugin-fail-strict.txt]", "tests/mypy/test_mypy.py::test_mypy_results[pyproject-plugin.toml-plugin_fail.py-plugin-fail.txt]", "tests/mypy/test_mypy.py::test_mypy_results[pyproject-plugin-strict.toml-plugin_fail.py-plugin-fail-strict.txt]", "tests/mypy/test_mypy.py::test_mypy_results[mypy-plugin-strict.ini-plugin_default_factory.py-plugin_default_factory.txt]" ]
[ "tests/mypy/test_mypy.py::test_mypy_results[mypy-plugin.ini-plugin_success.py-None]", "tests/mypy/test_mypy.py::test_mypy_results[mypy-plugin.ini-custom_constructor.py-custom_constructor.txt]", "tests/mypy/test_mypy.py::test_mypy_results[mypy-plugin-strict.ini-plugin_success.py-plugin-success-strict.txt]", "tests/mypy/test_mypy.py::test_mypy_results[mypy-plugin-strict.ini-fail_defaults.py-fail_defaults.txt]", "tests/mypy/test_mypy.py::test_mypy_results[mypy-default.ini-success.py-None]", "tests/mypy/test_mypy.py::test_mypy_results[mypy-default.ini-fail1.py-fail1.txt]", "tests/mypy/test_mypy.py::test_mypy_results[mypy-default.ini-fail2.py-fail2.txt]", "tests/mypy/test_mypy.py::test_mypy_results[mypy-default.ini-fail3.py-fail3.txt]", "tests/mypy/test_mypy.py::test_mypy_results[mypy-default.ini-fail4.py-fail4.txt]", "tests/mypy/test_mypy.py::test_mypy_results[mypy-default.ini-plugin_success.py-plugin_success.txt]", "tests/mypy/test_mypy.py::test_mypy_results[mypy-plugin-strict-no-any.ini-no_any.py-None]", "tests/mypy/test_mypy.py::test_mypy_results[pyproject-default.toml-success.py-None]", "tests/mypy/test_mypy.py::test_mypy_results[pyproject-default.toml-fail1.py-fail1.txt]", "tests/mypy/test_mypy.py::test_mypy_results[pyproject-default.toml-fail2.py-fail2.txt]", "tests/mypy/test_mypy.py::test_mypy_results[pyproject-default.toml-fail3.py-fail3.txt]", "tests/mypy/test_mypy.py::test_mypy_results[pyproject-default.toml-fail4.py-fail4.txt]", "tests/mypy/test_mypy.py::test_mypy_results[pyproject-plugin.toml-plugin_success.py-None]", "tests/mypy/test_mypy.py::test_mypy_results[pyproject-plugin-strict.toml-plugin_success.py-plugin-success-strict.txt]", "tests/mypy/test_mypy.py::test_mypy_results[pyproject-plugin-strict.toml-fail_defaults.py-fail_defaults.txt]", "tests/mypy/test_mypy.py::test_mypy_results[mypy-plugin-strict.ini-settings_config.py-None]", "tests/mypy/test_mypy.py::test_bad_toml_config", "tests/mypy/test_mypy.py::test_success_cases_run[no_any]", "tests/mypy/test_mypy.py::test_success_cases_run[settings_config]", "tests/mypy/test_mypy.py::test_success_cases_run[plugin_success]", "tests/mypy/test_mypy.py::test_success_cases_run[success]", "tests/mypy/test_mypy.py::test_explicit_reexports", "tests/mypy/test_mypy.py::test_explicit_reexports_exist", "tests/mypy/test_mypy.py::test_parse_mypy_version[0-v_tuple0]", "tests/mypy/test_mypy.py::test_parse_mypy_version[0.930-v_tuple1]", "tests/mypy/test_mypy.py::test_parse_mypy_version[0.940+dev.04cac4b5d911c4f9529e6ce86a27b44f28846f5d.dirty-v_tuple2]" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2022-09-02 16:51:16+00:00
mit
4,878
pydantic__pydantic-4482
diff --git a/pydantic/generics.py b/pydantic/generics.py --- a/pydantic/generics.py +++ b/pydantic/generics.py @@ -62,7 +62,11 @@ def __class_getitem__(cls: Type[GenericModelT], params: Union[Type[Any], Tuple[T returned as is. """ - cached = _generic_types_cache.get((cls, params)) + + def _cache_key(_params: Any) -> Tuple[Type[GenericModelT], Any, Tuple[Any, ...]]: + return cls, _params, get_args(_params) + + cached = _generic_types_cache.get(_cache_key(params)) if cached is not None: return cached if cls.__concrete__ and Generic not in cls.__bases__: @@ -128,9 +132,9 @@ def __class_getitem__(cls: Type[GenericModelT], params: Union[Type[Any], Tuple[T # Save created model in cache so we don't end up creating duplicate # models that should be identical. - _generic_types_cache[(cls, params)] = created_model + _generic_types_cache[_cache_key(params)] = created_model if len(params) == 1: - _generic_types_cache[(cls, params[0])] = created_model + _generic_types_cache[_cache_key(params[0])] = created_model # Recursively walk class type hints and replace generic typevars # with concrete types that were passed.
pydantic/pydantic
eccd85e4d012e70ffbd81f379179da900d4621c5
Yep it's a bug. Since for python `Union[int, float] == Union[float, int]`, the key in the cache is the same. I guess we could use `(cls, params, get_args(params))` as key of `_generic_types_cache` instead of `(cls, params)` > Yep it's a bug. Since for python `Union[int, float] == Union[float, int]`, the key in the cache is the same. Good to hear! > I guess we could use `(cls, params, get_args(params))` as key of `_generic_types_cache` instead of `(cls, params)` What about nested models, say `List[Union[float, int]]` and `List[Union[int, float]]`? Wouldn’t these still be considered equal? Is this new in v1.10? > Is this new in v1.10? No, saw it first in 1.9.0 and then updated to check if it was still there in the newest version. It is probably as old as the current specification of the key in `_generic_types_cache`. Humm, can't remember if that was new in 1.9 or 1.8. The question is whether we should fix this in a patch release of 1.10 or wait for V2? > The question is whether we should fix this in a patch release of 1.10 or wait for V2? That’s obviously not for me to say, but personally I think it would have been nice with a patch of at least the basic (non-nested) case, as the bug is breaking several of my tests. This gets more complicated, as the more-or-less exact same issue is present in the `typing` library itself, e.g. ```python from typing import get_args, List, Union print(get_args(Union[int, float])) print(get_args(Union[float, int])) print(get_args(List[Union[float, int]])) print(get_args(List[Union[int, float]])) ``` Prints: ``` (<class 'int'>, <class 'float'>) (<class 'float'>, <class 'int'>) (typing.Union[float, int],) (typing.Union[float, int],) ``` This is discussed in [this CPython issue](https://github.com/python/cpython/issues/86483), which include comments by Guido, and which resulted in the following documentation change: > If X is a union or [Literal](https://docs.python.org/3/library/typing.html#typing.Literal) contained in another generic type, the order of (Y, Z, ...) may be different from the order of the original arguments [Y, Z, ...] due to type caching. (from the [current Python docs](https://docs.python.org/3/library/typing.html#typing.get_args)) This at least rules out a recursive solution using `get_args` for nested models (which I was toying around with). If I understand this correctly, I believe it also means that the difference between e.g. `List[Union[float, int]]` and `List[Union[int, float]]` would be inaccessible in Python itself, which is a problem. Thinking from the perspective of a downstream library depending on `pydantic` I suppose one could implement a workaround for the nested problem(i.e. `List[Union[int, float]] == List[Union[float, int]]`) by replacing `Union` with a custom model, say `OrderedUnion`, which overrides `__eq__`. Such a model could even be included in `pydantic` if there is great enough need for this. However, all of this does not disqualify the simple `get_args` fix suggested by @PrettyWood. It would still work for the top level `Union` case, as in my example code, which is really the only thing I need for my code anyway. Also, I suppose the fact that a solution to the nested problem would be dependent on the above-mentioned "feature" in Python is really an argument for only solving the simple non-nested issue now. So, in a sense, I would argue that this complication might actually make this issue simpler to manage, at least for now. Confirmed, I think we should fix this in V1.10. PR welcome, it'll need to be pretty quick to make it into the next patch release #4472, but otherwise it can be included in the (inevitable) next patch release. I can give it a try. great, thanks. I'm getting the following mypy errors: ``` pydantic/generics.py:65: error: Argument 1 to "get_args" has incompatible type "Union[Type[Any], Tuple[Type[Any], ...]]"; expected "Type[Any]" [arg-type] pydantic/generics.py:131: error: Argument 1 to "get_args" has incompatible type "Tuple[Type[Any], ...]"; expected "Type[Any]" [arg-type] ``` Which seems to be a bug in mypy: https://github.com/python/mypy/issues/4625 Any thoughts on how to handle this? hard without seeing the change, create the PR so I can see it. Basically, the type of the `params` parameter specified in `GenericModel.__class_getitem__` is incompatible with the `Type[Any]` in the `get_args` method, according to `mypy`. As far as I can understand, `Type[Any]` is supposed to allow any type, including `Union` and `Tuple`. It makes sense to me that this is a mypy bug, but I might have misread the mypy issue, as the issue is not exactly the same. Anyway, I'll add a test and submit the PR for you to see. I'd love to include this fix in v1.10.2, any chance you can submit the PR asap so I can review and merge it?
diff --git a/tests/test_generics.py b/tests/test_generics.py --- a/tests/test_generics.py +++ b/tests/test_generics.py @@ -688,6 +688,52 @@ class Model(BaseModel): # same name, but type different, so it's not in cache assert globals()['MyGeneric[Model]__'] is third_concrete +def test_generic_model_caching_detect_order_of_union_args_basic(create_module): + # Basic variant of https://github.com/pydantic/pydantic/issues/4474 + @create_module + def module(): + from typing import Generic, TypeVar, Union + + from pydantic.generics import GenericModel + + t = TypeVar('t') + + class Model(GenericModel, Generic[t]): + data: t + + int_or_float_model = Model[Union[int, float]] + float_or_int_model = Model[Union[float, int]] + + assert type(int_or_float_model(data='1').data) is int + assert type(float_or_int_model(data='1').data) is float + + [email protected]( + reason=""" +Depends on similar issue in CPython itself: https://github.com/python/cpython/issues/86483 +Documented and skipped for possible fix later. +""" +) +def test_generic_model_caching_detect_order_of_union_args_nested(create_module): + # Nested variant of https://github.com/pydantic/pydantic/issues/4474 + @create_module + def module(): + from typing import Generic, List, TypeVar, Union + + from pydantic.generics import GenericModel + + t = TypeVar('t') + + class Model(GenericModel, Generic[t]): + data: t + + int_or_float_model = Model[List[Union[int, float]]] + float_or_int_model = Model[List[Union[float, int]]] + + assert type(int_or_float_model(data=['1']).data[0]) is int + assert type(float_or_int_model(data=['1']).data[0]) is float + + def test_get_caller_frame_info(create_module): @create_module def module():
First instantiation of generic Union model defines type coercion of models instantiated later ### Initial Checks - [X] I have searched GitHub for a duplicate issue and I'm sure this is something new - [X] I have searched Google & StackOverflow for a solution and couldn't find anything - [X] I have read and followed [the docs](https://pydantic-docs.helpmanual.io) and still think this is a bug - [X] I am confident that the issue is with pydantic (not my code, or another library in the ecosystem like [FastAPI](https://fastapi.tiangolo.com) or [mypy](https://mypy.readthedocs.io/en/stable)) ### Description When pydantic generic models are instantiated with Unions, the order of a particular set of types are fixed by the first instantiation, e.g.: ```python from typing import Generic, TypeVar, Union from pydantic.generics import GenericModel NumberT = TypeVar('NumberT') class NumberModel(GenericModel, Generic[NumberT]): data: NumberT FloatOrIntModel = NumberModel[Union[float, int]] print(FloatOrIntModel(data='1').data) IntOrFloatModel = NumberModel[Union[int, float]] print(IntOrFloatModel(data='1').data) ``` prints ``` 1.0 1.0 ``` While changing the order of the instantiations changes type coercion of both models: ``` 1 1 ``` In pydantic, type coercion of Union models depends on the order of the types. However, as explained in the documentation on [Unions](https://pydantic-docs.helpmanual.io/usage/types/#unions): > typing.Union also ignores order when [defined](https://docs.python.org/3/library/typing.html#typing.Union), so Union[int, float] == Union[float, int] which can lead to unexpected behaviour when combined with matching based on the Union type order inside other type definitions I think this should be considered a bug in pydantic, even though the user is warned against 'unexpected behaviour' combined with other code that depend on Union type equality. The unexpected behaviour in this case is caused by pydantic itself, there is no "matching based on the Union type order inside other type definitions" in the example code, nor are any third-party code imported. It is not difficult to envision situations where this dependency could cause very hard-to-find bugs. It seems the cause of the error is the `_generic_types_cache` in `generics.py`, which caches the first Union model and uses this as the blueprint of later matching models (i.e. with the same set of types). Setting `smart_union` to `True` has no impact. Related to https://github.com/pydantic/pydantic/issues/2835. ### Example Code _No response_ ### Python, Pydantic & OS Version ```Text pydantic version: 1.10.1 pydantic compiled: True install path: /Users/sveinugu/Library/Caches/pypoetry/virtualenvs/unifair-myuXak-6-py3.10/lib/python3.10/site-packages/pydantic python version: 3.10.4 | packaged by conda-forge | (main, Mar 24 2022, 17:42:03) [Clang 12.0.1 ] platform: macOS-11.2.3-arm64-arm-64bit optional deps. installed: ['typing-extensions'] ``` ### Affected Components - [ ] [Compatibility between releases](https://pydantic-docs.helpmanual.io/changelog/) - [X] [Data validation/parsing](https://pydantic-docs.helpmanual.io/usage/models/#basic-model-usage) - [ ] [Data serialization](https://pydantic-docs.helpmanual.io/usage/exporting_models/) - `.dict()` and `.json()` - [ ] [JSON Schema](https://pydantic-docs.helpmanual.io/usage/schema/) - [ ] [Dataclasses](https://pydantic-docs.helpmanual.io/usage/dataclasses/) - [ ] [Model Config](https://pydantic-docs.helpmanual.io/usage/model_config/) - [X] [Field Types](https://pydantic-docs.helpmanual.io/usage/types/) - adding or changing a particular data type - [ ] [Function validation decorator](https://pydantic-docs.helpmanual.io/usage/validation_decorator/) - [X] [Generic Models](https://pydantic-docs.helpmanual.io/usage/models/#generic-models) - [ ] [Other Model behaviour](https://pydantic-docs.helpmanual.io/usage/models/) - `construct()`, pickling, private attributes, ORM mode - [ ] [Settings Management](https://pydantic-docs.helpmanual.io/usage/settings/) - [ ] [Plugins](https://pydantic-docs.helpmanual.io/) and integration with other tools - mypy, FastAPI, python-devtools, Hypothesis, VS Code, PyCharm, etc.
0.0
eccd85e4d012e70ffbd81f379179da900d4621c5
[ "tests/test_generics.py::test_generic_model_caching_detect_order_of_union_args_basic" ]
[ "tests/test_generics.py::test_generic_name", "tests/test_generics.py::test_double_parameterize_error", "tests/test_generics.py::test_value_validation", "tests/test_generics.py::test_methods_are_inherited", "tests/test_generics.py::test_config_is_inherited", "tests/test_generics.py::test_default_argument", "tests/test_generics.py::test_default_argument_for_typevar", "tests/test_generics.py::test_classvar", "tests/test_generics.py::test_non_annotated_field", "tests/test_generics.py::test_must_inherit_from_generic", "tests/test_generics.py::test_parameters_placed_on_generic", "tests/test_generics.py::test_parameters_must_be_typevar", "tests/test_generics.py::test_subclass_can_be_genericized", "tests/test_generics.py::test_parameter_count", "tests/test_generics.py::test_cover_cache", "tests/test_generics.py::test_generic_config", "tests/test_generics.py::test_enum_generic", "tests/test_generics.py::test_generic", "tests/test_generics.py::test_alongside_concrete_generics", "tests/test_generics.py::test_complex_nesting", "tests/test_generics.py::test_required_value", "tests/test_generics.py::test_optional_value", "tests/test_generics.py::test_custom_schema", "tests/test_generics.py::test_child_schema", "tests/test_generics.py::test_custom_generic_naming", "tests/test_generics.py::test_nested", "tests/test_generics.py::test_partial_specification", "tests/test_generics.py::test_partial_specification_with_inner_typevar", "tests/test_generics.py::test_partial_specification_name", "tests/test_generics.py::test_partial_specification_instantiation", "tests/test_generics.py::test_partial_specification_instantiation_bounded", "tests/test_generics.py::test_typevar_parametrization", "tests/test_generics.py::test_multiple_specification", "tests/test_generics.py::test_generic_subclass_of_concrete_generic", "tests/test_generics.py::test_generic_model_pickle", "tests/test_generics.py::test_generic_model_from_function_pickle_fail", "tests/test_generics.py::test_generic_model_redefined_without_cache_fail", "tests/test_generics.py::test_get_caller_frame_info", "tests/test_generics.py::test_get_caller_frame_info_called_from_module", "tests/test_generics.py::test_get_caller_frame_info_when_sys_getframe_undefined", "tests/test_generics.py::test_iter_contained_typevars", "tests/test_generics.py::test_nested_identity_parameterization", "tests/test_generics.py::test_replace_types", "tests/test_generics.py::test_replace_types_with_user_defined_generic_type_field", "tests/test_generics.py::test_replace_types_identity_on_unchanged", "tests/test_generics.py::test_deep_generic", "tests/test_generics.py::test_deep_generic_with_inner_typevar", "tests/test_generics.py::test_deep_generic_with_referenced_generic", "tests/test_generics.py::test_deep_generic_with_referenced_inner_generic", "tests/test_generics.py::test_deep_generic_with_multiple_typevars", "tests/test_generics.py::test_deep_generic_with_multiple_inheritance", "tests/test_generics.py::test_generic_with_referenced_generic_type_1", "tests/test_generics.py::test_generic_with_referenced_nested_typevar", "tests/test_generics.py::test_generic_with_callable", "tests/test_generics.py::test_generic_with_partial_callable", "tests/test_generics.py::test_generic_recursive_models", "tests/test_generics.py::test_generic_enum", "tests/test_generics.py::test_generic_literal", "tests/test_generics.py::test_generic_enums", "tests/test_generics.py::test_generic_with_user_defined_generic_field", "tests/test_generics.py::test_generic_annotated", "tests/test_generics.py::test_generic_subclass", "tests/test_generics.py::test_generic_subclass_with_partial_application", "tests/test_generics.py::test_multilevel_generic_binding", "tests/test_generics.py::test_generic_subclass_with_extra_type", "tests/test_generics.py::test_multi_inheritance_generic_binding", "tests/test_generics.py::test_parse_generic_json" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2022-09-05 12:38:55+00:00
mit
4,879
pydantic__pydantic-4484
diff --git a/pydantic/dataclasses.py b/pydantic/dataclasses.py --- a/pydantic/dataclasses.py +++ b/pydantic/dataclasses.py @@ -34,7 +34,20 @@ class M: import sys from contextlib import contextmanager from functools import wraps -from typing import TYPE_CHECKING, Any, Callable, ClassVar, Dict, Generator, Optional, Type, TypeVar, Union, overload +from typing import ( + TYPE_CHECKING, + Any, + Callable, + ClassVar, + Dict, + Generator, + Optional, + Set, + Type, + TypeVar, + Union, + overload, +) from typing_extensions import dataclass_transform @@ -184,7 +197,7 @@ def dataclass( def wrap(cls: Type[Any]) -> 'DataclassClassOrWrapper': import dataclasses - if is_builtin_dataclass(cls): + if is_builtin_dataclass(cls) and _extra_dc_args(_cls) == _extra_dc_args(_cls.__bases__[0]): # type: ignore dc_cls_doc = '' dc_cls = DataclassProxy(cls) default_validate_on_init = False @@ -418,6 +431,14 @@ def _dataclass_validate_assignment_setattr(self: 'Dataclass', name: str, value: object.__setattr__(self, name, value) +def _extra_dc_args(cls: Type[Any]) -> Set[str]: + return { + x + for x in dir(cls) + if x not in getattr(cls, '__dataclass_fields__', {}) and not (x.startswith('__') and x.endswith('__')) + } + + def is_builtin_dataclass(_cls: Type[Any]) -> bool: """ Whether a class is a stdlib dataclass
pydantic/pydantic
91bb8d44822a6dfff87ff8881531e894a89692a8
I can confirm the behaviour, @PrettyWood can you look at this?
diff --git a/tests/test_dataclasses.py b/tests/test_dataclasses.py --- a/tests/test_dataclasses.py +++ b/tests/test_dataclasses.py @@ -1395,3 +1395,80 @@ class Bar: @pydantic.dataclasses.dataclass class Foo: a: List[Bar(a=1)] + + +def test_parent_post_init(): + @dataclasses.dataclass + class A: + a: float = 1 + + def __post_init__(self): + self.a *= 2 + + @pydantic.dataclasses.dataclass + class B(A): + @validator('a') + def validate_a(cls, value): + value += 3 + return value + + assert B().a == 5 # 1 * 2 + 3 + + +def test_subclass_post_init_post_parse(): + @dataclasses.dataclass + class A: + a: float = 1 + + @pydantic.dataclasses.dataclass + class B(A): + def __post_init_post_parse__(self): + self.a *= 2 + + @validator('a') + def validate_a(cls, value): + value += 3 + return value + + assert B().a == 8 # (1 + 3) * 2 + + +def test_subclass_post_init(): + @dataclasses.dataclass + class A: + a: int = 1 + + @pydantic.dataclasses.dataclass + class B(A): + def __post_init__(self): + self.a *= 2 + + @validator('a') + def validate_a(cls, value): + value += 3 + return value + + assert B().a == 5 # 1 * 2 + 3 + + +def test_subclass_post_init_inheritance(): + @dataclasses.dataclass + class A: + a: int = 1 + + @pydantic.dataclasses.dataclass + class B(A): + def __post_init__(self): + self.a *= 2 + + @validator('a') + def validate_a(cls, value): + value += 3 + return value + + @pydantic.dataclasses.dataclass + class C(B): + def __post_init__(self): + self.a *= 3 + + assert C().a == 6 # 1 * 3 + 3
__post_init__ and validators are not triggered in class inherited from stdlib dataclass in 1.10.1 ### Initial Checks - [X] I have searched GitHub for a duplicate issue and I'm sure this is something new - [X] I have searched Google & StackOverflow for a solution and couldn't find anything - [X] I have read and followed [the docs](https://pydantic-docs.helpmanual.io) and still think this is a bug - [X] I am confident that the issue is with pydantic (not my code, or another library in the ecosystem like [FastAPI](https://fastapi.tiangolo.com) or [mypy](https://mypy.readthedocs.io/en/stable)) ### Description __post_init__ and validator are not triggered in the following code. However, uncommenting any of the lines: `py_dataclass(D_C_Base)` or `b: str = "string"` solves the issue. Versions 1.9.x could trigger both __post_init__ and validators without these lines. ### Example Code ```Python from dataclasses import dataclass from pydantic.dataclasses import dataclass as py_dataclass from pydantic import validator @dataclass class D_C_Base: a: float = 1.0 # py_dataclass(D_C_Base) @py_dataclass class D_C_Child(D_C_Base): # b: str = "string" def __post_init__(self): print('POST_INIT') @validator('a') def validate_a(cls, value): print(f'Validating "a" is {value}') d_c_class = D_C_Child() ``` ### Python, Pydantic & OS Version ```Text pydantic version: 1.10.1 pydantic compiled: True install path: C:\Users\TestUser\.conda\envs\py38\Lib\site-packages\pydantic python version: 3.8.13 (default, Mar 28 2022, 06:59:08) [MSC v.1916 64 bit (AMD64)] platform: Windows-10-10.0.22000-SP0 optional deps. installed: ['typing-extensions'] Also, pydantic version: 1.10.1 pydantic compiled: True install path: /local/envs/py39_test/lib/python3.9/site-packages/pydantic python version: 3.9.1 (default, Dec 11 2020, 14:32:07) [GCC 7.3.0] platform: Linux-3.10.0-1160.66.1.el7.x86_64-x86_64-with-glibc2.17 optional deps. installed: ['typing-extensions'] ``` ### Affected Components - [X] [Compatibility between releases](https://pydantic-docs.helpmanual.io/changelog/) - [X] [Data validation/parsing](https://pydantic-docs.helpmanual.io/usage/models/#basic-model-usage) - [ ] [Data serialization](https://pydantic-docs.helpmanual.io/usage/exporting_models/) - `.dict()` and `.json()` - [ ] [JSON Schema](https://pydantic-docs.helpmanual.io/usage/schema/) - [x] [Dataclasses](https://pydantic-docs.helpmanual.io/usage/dataclasses/) - [ ] [Model Config](https://pydantic-docs.helpmanual.io/usage/model_config/) - [ ] [Field Types](https://pydantic-docs.helpmanual.io/usage/types/) - adding or changing a particular data type - [ ] [Function validation decorator](https://pydantic-docs.helpmanual.io/usage/validation_decorator/) - [ ] [Generic Models](https://pydantic-docs.helpmanual.io/usage/models/#generic-models) - [ ] [Other Model behaviour](https://pydantic-docs.helpmanual.io/usage/models/) - `construct()`, pickling, private attributes, ORM mode - [ ] [Settings Management](https://pydantic-docs.helpmanual.io/usage/settings/) - [ ] [Plugins](https://pydantic-docs.helpmanual.io/) and integration with other tools - mypy, FastAPI, python-devtools, Hypothesis, VS Code, PyCharm, etc.
0.0
91bb8d44822a6dfff87ff8881531e894a89692a8
[ "tests/test_dataclasses.py::test_subclass_post_init", "tests/test_dataclasses.py::test_subclass_post_init_inheritance" ]
[ "tests/test_dataclasses.py::test_simple", "tests/test_dataclasses.py::test_model_name", "tests/test_dataclasses.py::test_value_error", "tests/test_dataclasses.py::test_frozen", "tests/test_dataclasses.py::test_validate_assignment", "tests/test_dataclasses.py::test_validate_assignment_error", "tests/test_dataclasses.py::test_not_validate_assignment", "tests/test_dataclasses.py::test_validate_assignment_value_change", "tests/test_dataclasses.py::test_validate_assignment_extra", "tests/test_dataclasses.py::test_post_init", "tests/test_dataclasses.py::test_post_init_validation", "tests/test_dataclasses.py::test_post_init_inheritance_chain", "tests/test_dataclasses.py::test_post_init_post_parse", "tests/test_dataclasses.py::test_post_init_post_parse_types", "tests/test_dataclasses.py::test_post_init_assignment", "tests/test_dataclasses.py::test_inheritance", "tests/test_dataclasses.py::test_validate_long_string_error", "tests/test_dataclasses.py::test_validate_assigment_long_string_error", "tests/test_dataclasses.py::test_no_validate_assigment_long_string_error", "tests/test_dataclasses.py::test_nested_dataclass", "tests/test_dataclasses.py::test_arbitrary_types_allowed", "tests/test_dataclasses.py::test_nested_dataclass_model", "tests/test_dataclasses.py::test_fields", "tests/test_dataclasses.py::test_default_factory_field", "tests/test_dataclasses.py::test_default_factory_singleton_field", "tests/test_dataclasses.py::test_schema", "tests/test_dataclasses.py::test_nested_schema", "tests/test_dataclasses.py::test_initvar", "tests/test_dataclasses.py::test_derived_field_from_initvar", "tests/test_dataclasses.py::test_initvars_post_init", "tests/test_dataclasses.py::test_initvars_post_init_post_parse", "tests/test_dataclasses.py::test_post_init_post_parse_without_initvars", "tests/test_dataclasses.py::test_classvar", "tests/test_dataclasses.py::test_frozenset_field", "tests/test_dataclasses.py::test_inheritance_post_init", "tests/test_dataclasses.py::test_hashable_required", "tests/test_dataclasses.py::test_hashable_optional[1]", "tests/test_dataclasses.py::test_hashable_optional[None]", "tests/test_dataclasses.py::test_hashable_optional[default2]", "tests/test_dataclasses.py::test_override_builtin_dataclass", "tests/test_dataclasses.py::test_override_builtin_dataclass_2", "tests/test_dataclasses.py::test_override_builtin_dataclass_nested", "tests/test_dataclasses.py::test_override_builtin_dataclass_nested_schema", "tests/test_dataclasses.py::test_inherit_builtin_dataclass", "tests/test_dataclasses.py::test_dataclass_arbitrary", "tests/test_dataclasses.py::test_forward_stdlib_dataclass_params", "tests/test_dataclasses.py::test_pydantic_callable_field", "tests/test_dataclasses.py::test_pickle_overriden_builtin_dataclass", "tests/test_dataclasses.py::test_config_field_info_create_model", "tests/test_dataclasses.py::test_issue_2162[foo0-bar0]", "tests/test_dataclasses.py::test_issue_2162[foo1-bar1]", "tests/test_dataclasses.py::test_issue_2162[foo2-bar2]", "tests/test_dataclasses.py::test_issue_2162[foo3-bar3]", "tests/test_dataclasses.py::test_issue_2383", "tests/test_dataclasses.py::test_issue_2398", "tests/test_dataclasses.py::test_issue_2424", "tests/test_dataclasses.py::test_issue_2541", "tests/test_dataclasses.py::test_issue_2555", "tests/test_dataclasses.py::test_issue_2594", "tests/test_dataclasses.py::test_schema_description_unset", "tests/test_dataclasses.py::test_schema_description_set", "tests/test_dataclasses.py::test_issue_3011", "tests/test_dataclasses.py::test_issue_3162", "tests/test_dataclasses.py::test_discriminated_union_basemodel_instance_value", "tests/test_dataclasses.py::test_post_init_after_validation", "tests/test_dataclasses.py::test_keeps_custom_properties", "tests/test_dataclasses.py::test_ignore_extra", "tests/test_dataclasses.py::test_ignore_extra_subclass", "tests/test_dataclasses.py::test_allow_extra", "tests/test_dataclasses.py::test_allow_extra_subclass", "tests/test_dataclasses.py::test_forbid_extra", "tests/test_dataclasses.py::test_post_init_allow_extra", "tests/test_dataclasses.py::test_self_reference_dataclass", "tests/test_dataclasses.py::test_extra_forbid_list_no_error", "tests/test_dataclasses.py::test_extra_forbid_list_error", "tests/test_dataclasses.py::test_parent_post_init", "tests/test_dataclasses.py::test_subclass_post_init_post_parse" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2022-09-05 13:14:44+00:00
mit
4,880
pydantic__pydantic-4493
diff --git a/pydantic/dataclasses.py b/pydantic/dataclasses.py --- a/pydantic/dataclasses.py +++ b/pydantic/dataclasses.py @@ -288,7 +288,10 @@ def handle_extra_init(self: 'Dataclass', *args: Any, **kwargs: Any) -> None: init(self, *args, **kwargs) if hasattr(dc_cls, '__post_init__'): - post_init = dc_cls.__post_init__ + try: + post_init = dc_cls.__post_init__.__wrapped__ # type: ignore[attr-defined] + except AttributeError: + post_init = dc_cls.__post_init__ @wraps(post_init) def new_post_init(self: 'Dataclass', *args: Any, **kwargs: Any) -> None:
pydantic/pydantic
c04923ca97b511c1a961cb018e0a5df3dd501ea2
See #4484. @PrettyWood, any ideas? I'll check
diff --git a/tests/test_dataclasses.py b/tests/test_dataclasses.py --- a/tests/test_dataclasses.py +++ b/tests/test_dataclasses.py @@ -1474,6 +1474,31 @@ def __post_init__(self): assert C().a == 6 # 1 * 3 + 3 +def test_inheritance_post_init_2(): + post_init_calls = 0 + post_init_post_parse_calls = 0 + + @pydantic.dataclasses.dataclass + class BaseClass: + def __post_init__(self): + nonlocal post_init_calls + post_init_calls += 1 + + @pydantic.dataclasses.dataclass + class AbstractClass(BaseClass): + pass + + @pydantic.dataclasses.dataclass + class ConcreteClass(AbstractClass): + def __post_init_post_parse__(self): + nonlocal post_init_post_parse_calls + post_init_post_parse_calls += 1 + + ConcreteClass() + assert post_init_calls == 1 + assert post_init_post_parse_calls == 1 + + def test_dataclass_setattr(): class Foo: bar: str = 'cat'
Dataclass post_init_post_parse called multiple times. ### Initial Checks - [X] I have searched GitHub for a duplicate issue and I'm sure this is something new - [X] I have searched Google & StackOverflow for a solution and couldn't find anything - [X] I have read and followed [the docs](https://pydantic-docs.helpmanual.io) and still think this is a bug - [X] I am confident that the issue is with pydantic (not my code, or another library in the ecosystem like [FastAPI](https://fastapi.tiangolo.com) or [mypy](https://mypy.readthedocs.io/en/stable)) ### Description When using inheritance with `pydantic.dataclasses.dataclass` based objects with `pydantic>=1.10` I seem to have encountered a bug that calls `__post_init_post_parse__` methods multiple times if a `__post_init__` method is called further down an inheritance chain. Running the below code snippet outputs the print statement three times, whereas if `__post_init__` is placed in `AbstractClass` the `"post init post parse called"` statement is called twice. The exact same code snippet on `pydantic<1.10` works as expected with the print statement only printed the once. Including an overridden `__post_init__` method in `ConcreteClass` only prints the statement once - but of course if there is more useful logic contained in `BaseClass.__post_init__` (as would be the case for this pattern) then this is ignored. Removing the `@dataclass` decorators from the base classes works fine however, except **if** we didn't have access to the code for those underlying base classes. EDIT: It appears its due to these lines: https://github.com/pydantic/pydantic/blob/v1.10.2/pydantic/dataclasses.py#L290-L304 ### Example Code ```Python from pydantic.dataclasses import dataclass @dataclass class BaseClass: def __post_init__(self): pass @dataclass class AbstractClass(BaseClass): pass @dataclass class ConcreteClass(AbstractClass): def __post_init_post_parse__(self): print("post init post parse called") ConcreteClass() # prints: # post init post parse called # post init post parse called # post init post parse called # Example of nested dataclasses from docs: https://pydantic-docs.helpmanual.io/usage/dataclasses/#convert-stdlib-dataclasses-into-pydantic-dataclasses from datetime import datetime from typing import Optional @dataclass class Meta: modified_date: Optional[datetime] seen_count: int def __post_init__(self): print("POST INIT") @dataclass class File(Meta): filename: str def __post_init_post_parse__(self): print("POST INIT POST PARSE") File(filename="file.txt", modified_date=datetime.now(), seen_count=1) # prints: # POST INIT # POST INIT POST PARSE # POST INIT POST PARSE ``` ### Python, Pydantic & OS Version ```Text pydantic version: 1.10.2 pydantic compiled: True install path: ***** python version: 3.8.13 (default, Mar 28 2022, 06:16:26) [Clang 12.0.0 ] platform: macOS-10.16-x86_64-i386-64bit optional deps. installed: ['dotenv', 'typing-extensions'] ``` ### Affected Components - [X] [Compatibility between releases](https://pydantic-docs.helpmanual.io/changelog/) - [X] [Data validation/parsing](https://pydantic-docs.helpmanual.io/usage/models/#basic-model-usage) - [ ] [Data serialization](https://pydantic-docs.helpmanual.io/usage/exporting_models/) - `.dict()` and `.json()` - [ ] [JSON Schema](https://pydantic-docs.helpmanual.io/usage/schema/) - [X] [Dataclasses](https://pydantic-docs.helpmanual.io/usage/dataclasses/) - [ ] [Model Config](https://pydantic-docs.helpmanual.io/usage/model_config/) - [ ] [Field Types](https://pydantic-docs.helpmanual.io/usage/types/) - adding or changing a particular data type - [ ] [Function validation decorator](https://pydantic-docs.helpmanual.io/usage/validation_decorator/) - [ ] [Generic Models](https://pydantic-docs.helpmanual.io/usage/models/#generic-models) - [ ] [Other Model behaviour](https://pydantic-docs.helpmanual.io/usage/models/) - `construct()`, pickling, private attributes, ORM mode - [ ] [Settings Management](https://pydantic-docs.helpmanual.io/usage/settings/) - [ ] [Plugins](https://pydantic-docs.helpmanual.io/) and integration with other tools - mypy, FastAPI, python-devtools, Hypothesis, VS Code, PyCharm, etc.
0.0
c04923ca97b511c1a961cb018e0a5df3dd501ea2
[ "tests/test_dataclasses.py::test_inheritance_post_init_2" ]
[ "tests/test_dataclasses.py::test_simple", "tests/test_dataclasses.py::test_model_name", "tests/test_dataclasses.py::test_value_error", "tests/test_dataclasses.py::test_frozen", "tests/test_dataclasses.py::test_validate_assignment", "tests/test_dataclasses.py::test_validate_assignment_error", "tests/test_dataclasses.py::test_not_validate_assignment", "tests/test_dataclasses.py::test_validate_assignment_value_change", "tests/test_dataclasses.py::test_validate_assignment_extra", "tests/test_dataclasses.py::test_post_init", "tests/test_dataclasses.py::test_post_init_validation", "tests/test_dataclasses.py::test_post_init_inheritance_chain", "tests/test_dataclasses.py::test_post_init_post_parse", "tests/test_dataclasses.py::test_post_init_post_parse_types", "tests/test_dataclasses.py::test_post_init_assignment", "tests/test_dataclasses.py::test_inheritance", "tests/test_dataclasses.py::test_validate_long_string_error", "tests/test_dataclasses.py::test_validate_assigment_long_string_error", "tests/test_dataclasses.py::test_no_validate_assigment_long_string_error", "tests/test_dataclasses.py::test_nested_dataclass", "tests/test_dataclasses.py::test_arbitrary_types_allowed", "tests/test_dataclasses.py::test_nested_dataclass_model", "tests/test_dataclasses.py::test_fields", "tests/test_dataclasses.py::test_default_factory_field", "tests/test_dataclasses.py::test_default_factory_singleton_field", "tests/test_dataclasses.py::test_schema", "tests/test_dataclasses.py::test_nested_schema", "tests/test_dataclasses.py::test_initvar", "tests/test_dataclasses.py::test_derived_field_from_initvar", "tests/test_dataclasses.py::test_initvars_post_init", "tests/test_dataclasses.py::test_initvars_post_init_post_parse", "tests/test_dataclasses.py::test_post_init_post_parse_without_initvars", "tests/test_dataclasses.py::test_classvar", "tests/test_dataclasses.py::test_frozenset_field", "tests/test_dataclasses.py::test_inheritance_post_init", "tests/test_dataclasses.py::test_hashable_required", "tests/test_dataclasses.py::test_hashable_optional[1]", "tests/test_dataclasses.py::test_hashable_optional[None]", "tests/test_dataclasses.py::test_hashable_optional[default2]", "tests/test_dataclasses.py::test_override_builtin_dataclass", "tests/test_dataclasses.py::test_override_builtin_dataclass_2", "tests/test_dataclasses.py::test_override_builtin_dataclass_nested", "tests/test_dataclasses.py::test_override_builtin_dataclass_nested_schema", "tests/test_dataclasses.py::test_inherit_builtin_dataclass", "tests/test_dataclasses.py::test_dataclass_arbitrary", "tests/test_dataclasses.py::test_forward_stdlib_dataclass_params", "tests/test_dataclasses.py::test_pydantic_callable_field", "tests/test_dataclasses.py::test_pickle_overriden_builtin_dataclass", "tests/test_dataclasses.py::test_config_field_info_create_model", "tests/test_dataclasses.py::test_issue_2162[foo0-bar0]", "tests/test_dataclasses.py::test_issue_2162[foo1-bar1]", "tests/test_dataclasses.py::test_issue_2162[foo2-bar2]", "tests/test_dataclasses.py::test_issue_2162[foo3-bar3]", "tests/test_dataclasses.py::test_issue_2383", "tests/test_dataclasses.py::test_issue_2398", "tests/test_dataclasses.py::test_issue_2424", "tests/test_dataclasses.py::test_issue_2541", "tests/test_dataclasses.py::test_issue_2555", "tests/test_dataclasses.py::test_issue_2594", "tests/test_dataclasses.py::test_schema_description_unset", "tests/test_dataclasses.py::test_schema_description_set", "tests/test_dataclasses.py::test_issue_3011", "tests/test_dataclasses.py::test_issue_3162", "tests/test_dataclasses.py::test_discriminated_union_basemodel_instance_value", "tests/test_dataclasses.py::test_post_init_after_validation", "tests/test_dataclasses.py::test_keeps_custom_properties", "tests/test_dataclasses.py::test_ignore_extra", "tests/test_dataclasses.py::test_ignore_extra_subclass", "tests/test_dataclasses.py::test_allow_extra", "tests/test_dataclasses.py::test_allow_extra_subclass", "tests/test_dataclasses.py::test_forbid_extra", "tests/test_dataclasses.py::test_post_init_allow_extra", "tests/test_dataclasses.py::test_self_reference_dataclass", "tests/test_dataclasses.py::test_extra_forbid_list_no_error", "tests/test_dataclasses.py::test_extra_forbid_list_error", "tests/test_dataclasses.py::test_parent_post_init", "tests/test_dataclasses.py::test_subclass_post_init_post_parse", "tests/test_dataclasses.py::test_subclass_post_init", "tests/test_dataclasses.py::test_subclass_post_init_inheritance", "tests/test_dataclasses.py::test_dataclass_setattr" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2022-09-06 17:24:56+00:00
mit
4,881
pydantic__pydantic-4568
diff --git a/pydantic/types.py b/pydantic/types.py --- a/pydantic/types.py +++ b/pydantic/types.py @@ -599,7 +599,10 @@ def list_length_validator(cls, v: 'Optional[List[T]]') -> 'Optional[List[T]]': return v @classmethod - def unique_items_validator(cls, v: 'List[T]') -> 'List[T]': + def unique_items_validator(cls, v: 'Optional[List[T]]') -> 'Optional[List[T]]': + if v is None: + return None + for i, value in enumerate(v, start=1): if value in v[i:]: raise errors.ListUniqueItemsError()
pydantic/pydantic
da0b756e523ddb3db63f22d90ac34dc2fcf9f55f
Shall I raise one PR to [1.9.X-fixes](https://github.com/samuelcolvin/pydantic/tree/1.9.X-fixes) What happens on 1.8.2? There is no support for `unique_items` in pydantic version 1.8.2 ``` py class Model(BaseModel): foo: Optional[List[str]] = Field(None, unique_items=True) Model(foo=['a','a','a'], bar=None) ``` Won't raise any issues (duplicate items are there in the list) and ``` py class Model(BaseModel): bar: conlist(str, unique_items=True) = Field(None) Model(bar=['a','a','a']) ``` Will raise an issue ``` Traceback (most recent call last): File "/Users/developer/test.py", line 1, in <module> class Model(BaseModel): File "/Users/developer/test.py", line 2, in Model bar: conlist(str, unique_items=True) = Field(None) File "pydantic/types.py", line 509, in pydantic.types.conlist TypeError: conlist() got an unexpected keyword argument 'unique_items' ``` ps: I need the support for `unique_items`. Sorry, my bad. 🙈 Yes, pr against that branch please. Did this PR ever get made? If not, I'd be happy to create it.
diff --git a/tests/test_validators.py b/tests/test_validators.py --- a/tests/test_validators.py +++ b/tests/test_validators.py @@ -7,7 +7,7 @@ import pytest from typing_extensions import Literal -from pydantic import BaseModel, ConfigError, Extra, Field, ValidationError, errors, validator +from pydantic import BaseModel, ConfigError, Extra, Field, ValidationError, conlist, errors, validator from pydantic.class_validators import make_generic_validator, root_validator @@ -1329,3 +1329,19 @@ def post_root(cls, values): B(x='pika') assert validate_stub.call_args_list == [mocker.call('B', 'pre'), mocker.call('B', 'post')] + + +def test_list_unique_items_with_optional(): + class Model(BaseModel): + foo: Optional[List[str]] = Field(None, unique_items=True) + bar: conlist(str, unique_items=True) = Field(None) + + assert Model().dict() == {'foo': None, 'bar': None} + assert Model(foo=None, bar=None).dict() == {'foo': None, 'bar': None} + assert Model(foo=['k1'], bar=['k1']).dict() == {'foo': ['k1'], 'bar': ['k1']} + with pytest.raises(ValidationError) as exc_info: + Model(foo=['k1', 'k1'], bar=['k1', 'k1']) + assert exc_info.value.errors() == [ + {'loc': ('foo',), 'msg': 'the list has duplicated items', 'type': 'value_error.list.unique_items'}, + {'loc': ('bar',), 'msg': 'the list has duplicated items', 'type': 'value_error.list.unique_items'}, + ]
Optional[conlist(..., unique_items=True)] raises exception if value is None ### Checks * [x] I added a descriptive title to this issue * [x] I have searched (google, github) for similar issues and couldn't find anything * [x] I have read and followed [the docs](https://pydantic-docs.helpmanual.io/) and still think this is a bug <!-- Sorry to sound so draconian, but every second saved replying to issues is time spend improving pydantic :-) --> # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.9.0 pydantic compiled: True install path: /Users/.../code/venvs/.../lib/python3.9/site-packages/pydantic python version: 3.9.9 (v3.9.9:ccb0e6a345, Nov 15 2021, 13:06:05) [Clang 13.0.0 (clang-1300.0.29.3)] platform: macOS-12.0.1-arm64-arm-64bit optional deps. installed: ['dotenv', 'email-validator', 'typing-extensions'] ``` <!-- or if you're using pydantic prior to v1.3, manually include: OS, python version and pydantic version --> <!-- Please read the [docs](https://pydantic-docs.helpmanual.io/) and search through issues to confirm your bug hasn't already been reported. --> <!-- Where possible please include a self-contained code snippet describing your bug: --> ```py from typing import Optional from pydantic import BaseModel, conlist class Model(BaseModel): fuel_types: Optional[conlist(str, min_items=1, unique_items=True)] Model(fuel_types=None) ``` ``` Traceback (most recent call last): File "/Users/.../code/python/.../ttt.py", line 10, in <module> Model(fuel_types=None) File "pydantic/main.py", line 331, in pydantic.main.BaseModel.__init__ pydantic.error_wrappers.ValidationError: 1 validation error for Model fuel_types 'NoneType' object is not iterable (type=type_error) ``` This snippet above shouldn't lead to exception, but it does. Probably quick fix is replacing this code https://github.com/samuelcolvin/pydantic/blob/91ecfd651e2f6f0820b5f12f79b9c33163d309d8/pydantic/types.py#L572-L578 with this one ```python @classmethod def unique_items_validator(cls, v: 'Optional[List[T]]') -> 'Optional[List[T]]': if v is None: return None for i, value in enumerate(v, start=1): if value in v[i:]: raise errors.ListUniqueItemsError() return v ``` Unexpected validation error with optional list field with unique_items check ### Checks * [x] I added a descriptive title to this issue * [x] I have searched (google, GitHub) for similar issues and couldn't find anything * [x] I have read and followed [the docs](https://pydantic-docs.helpmanual.io/) and still think this is a bug # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.9.0 pydantic compiled: True install path: /home/foo/lib/python3.8/site-packages/pydantic python version: 3.8.5 (default, Dec 29 2021, 04:21:09) [GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] platform: Linux-3.10.0-1160.49.1.el7.x86_64-x86_64-with-glibc2.17 optional deps. installed: ['dotenv', 'email-validator', 'typing-extensions'] ``` Related discussion: https://github.com/samuelcolvin/pydantic/discussions/4050 ```py from typing import Optional, List from pydantic import BaseModel, Field, conlist, ValidationError class Model(BaseModel): foo: Optional[List[str]] = Field(None, unique_items=True) bar: conlist(str, unique_items=True) = Field(None) try: Model(foo=None, bar=None) except ValidationError as exc_info: assert exc_info.errors() == [ { 'loc': ('foo',), 'msg': "'NoneType' object is not iterable", 'type': 'type_error' }, { 'loc': ('bar',), 'msg': "'NoneType' object is not iterable", 'type': 'type_error' } ] ``` ### Test case ``` py def test_list_unique_items_with_optional(): class Model(BaseModel): foo: Optional[List[str]] = Field(None, unique_items=True) bar: conlist(str, unique_items=True) = Field(None) assert Model().dict() == {'foo':None, 'bar': None} assert Model(foo=None, bar=None).dict() == {'foo':None, 'bar': None} assert Model(foo=["k1"], bar=["k1"]).dict() == {'foo': ["k1"], 'bar': ["k1"]} with pytest.raises(ValidationError) as exc_info: Model(foo=["k1", "k1"], bar=["k1", "k1"]) assert exc_info.value.errors() == [ { 'loc': ('foo',), 'msg': 'the list has duplicated items', 'type': 'value_error.list.unique_items' }, { 'loc': ('bar',), 'msg': 'the list has duplicated items', 'type': 'value_error.list.unique_items' } ] ``` ### Fix Update the `unique_items_validator` function code to. ``` py @classmethod def unique_items_validator(cls, v: 'Optional[List[T]]') -> 'Optional[List[T]]': if v is None: return v for i, value in enumerate(v, start=1): if value in v[i:]: raise errors.ListUniqueItemsError() return v ``` `Tested this and ran all test cases and successfully passed.` Please verify. Cc: @samuelcolvin
0.0
da0b756e523ddb3db63f22d90ac34dc2fcf9f55f
[ "tests/test_validators.py::test_list_unique_items_with_optional" ]
[ "tests/test_validators.py::test_simple", "tests/test_validators.py::test_int_validation", "tests/test_validators.py::test_int_overflow_validation[inf0]", "tests/test_validators.py::test_int_overflow_validation[nan]", "tests/test_validators.py::test_int_overflow_validation[inf1]", "tests/test_validators.py::test_frozenset_validation", "tests/test_validators.py::test_deque_validation", "tests/test_validators.py::test_validate_whole", "tests/test_validators.py::test_validate_kwargs", "tests/test_validators.py::test_validate_pre_error", "tests/test_validators.py::test_validating_assignment_ok", "tests/test_validators.py::test_validating_assignment_fail", "tests/test_validators.py::test_validating_assignment_value_change", "tests/test_validators.py::test_validating_assignment_extra", "tests/test_validators.py::test_validating_assignment_dict", "tests/test_validators.py::test_validating_assignment_values_dict", "tests/test_validators.py::test_validate_multiple", "tests/test_validators.py::test_classmethod", "tests/test_validators.py::test_duplicates", "tests/test_validators.py::test_use_bare", "tests/test_validators.py::test_use_no_fields", "tests/test_validators.py::test_validate_always", "tests/test_validators.py::test_validate_always_on_inheritance", "tests/test_validators.py::test_validate_not_always", "tests/test_validators.py::test_wildcard_validators", "tests/test_validators.py::test_wildcard_validator_error", "tests/test_validators.py::test_invalid_field", "tests/test_validators.py::test_validate_child", "tests/test_validators.py::test_validate_child_extra", "tests/test_validators.py::test_validate_child_all", "tests/test_validators.py::test_validate_parent", "tests/test_validators.py::test_validate_parent_all", "tests/test_validators.py::test_inheritance_keep", "tests/test_validators.py::test_inheritance_replace", "tests/test_validators.py::test_inheritance_new", "tests/test_validators.py::test_validation_each_item", "tests/test_validators.py::test_validation_each_item_one_sublevel", "tests/test_validators.py::test_key_validation", "tests/test_validators.py::test_validator_always_optional", "tests/test_validators.py::test_validator_always_pre", "tests/test_validators.py::test_validator_always_post", "tests/test_validators.py::test_validator_always_post_optional", "tests/test_validators.py::test_validator_bad_fields_throws_configerror", "tests/test_validators.py::test_datetime_validator", "tests/test_validators.py::test_pre_called_once", "tests/test_validators.py::test_make_generic_validator[fields0-_v_]", "tests/test_validators.py::test_make_generic_validator[fields1-_v_]", "tests/test_validators.py::test_make_generic_validator[fields2-_v_,_field_]", "tests/test_validators.py::test_make_generic_validator[fields3-_v_,_config_]", "tests/test_validators.py::test_make_generic_validator[fields4-_v_,_values_]", "tests/test_validators.py::test_make_generic_validator[fields5-_v_,_field_,_config_]", "tests/test_validators.py::test_make_generic_validator[fields6-_v_,_field_,_values_]", "tests/test_validators.py::test_make_generic_validator[fields7-_v_,_config_,_values_]", "tests/test_validators.py::test_make_generic_validator[fields8-_v_,_field_,_values_,_config_]", "tests/test_validators.py::test_make_generic_validator[fields9-_cls_,_v_]", "tests/test_validators.py::test_make_generic_validator[fields10-_cls_,_v_]", "tests/test_validators.py::test_make_generic_validator[fields11-_cls_,_v_,_field_]", "tests/test_validators.py::test_make_generic_validator[fields12-_cls_,_v_,_config_]", "tests/test_validators.py::test_make_generic_validator[fields13-_cls_,_v_,_values_]", "tests/test_validators.py::test_make_generic_validator[fields14-_cls_,_v_,_field_,_config_]", "tests/test_validators.py::test_make_generic_validator[fields15-_cls_,_v_,_field_,_values_]", "tests/test_validators.py::test_make_generic_validator[fields16-_cls_,_v_,_config_,_values_]", "tests/test_validators.py::test_make_generic_validator[fields17-_cls_,_v_,_field_,_values_,_config_]", "tests/test_validators.py::test_make_generic_validator_kwargs", "tests/test_validators.py::test_make_generic_validator_invalid", "tests/test_validators.py::test_make_generic_validator_cls_kwargs", "tests/test_validators.py::test_make_generic_validator_cls_invalid", "tests/test_validators.py::test_make_generic_validator_self", "tests/test_validators.py::test_assert_raises_validation_error", "tests/test_validators.py::test_whole", "tests/test_validators.py::test_root_validator", "tests/test_validators.py::test_root_validator_pre", "tests/test_validators.py::test_root_validator_repeat", "tests/test_validators.py::test_root_validator_repeat2", "tests/test_validators.py::test_root_validator_self", "tests/test_validators.py::test_root_validator_extra", "tests/test_validators.py::test_root_validator_types", "tests/test_validators.py::test_root_validator_inheritance", "tests/test_validators.py::test_root_validator_returns_none_exception", "tests/test_validators.py::test_reuse_global_validators", "tests/test_validators.py::test_allow_reuse[True-True-True-True]", "tests/test_validators.py::test_allow_reuse[True-True-True-False]", "tests/test_validators.py::test_allow_reuse[True-True-False-True]", "tests/test_validators.py::test_allow_reuse[True-True-False-False]", "tests/test_validators.py::test_allow_reuse[True-False-True-True]", "tests/test_validators.py::test_allow_reuse[True-False-True-False]", "tests/test_validators.py::test_allow_reuse[True-False-False-True]", "tests/test_validators.py::test_allow_reuse[True-False-False-False]", "tests/test_validators.py::test_allow_reuse[False-True-True-True]", "tests/test_validators.py::test_allow_reuse[False-True-True-False]", "tests/test_validators.py::test_allow_reuse[False-True-False-True]", "tests/test_validators.py::test_allow_reuse[False-True-False-False]", "tests/test_validators.py::test_allow_reuse[False-False-True-True]", "tests/test_validators.py::test_allow_reuse[False-False-True-False]", "tests/test_validators.py::test_allow_reuse[False-False-False-True]", "tests/test_validators.py::test_allow_reuse[False-False-False-False]", "tests/test_validators.py::test_root_validator_classmethod[True-True]", "tests/test_validators.py::test_root_validator_classmethod[True-False]", "tests/test_validators.py::test_root_validator_classmethod[False-True]", "tests/test_validators.py::test_root_validator_classmethod[False-False]", "tests/test_validators.py::test_root_validator_skip_on_failure", "tests/test_validators.py::test_assignment_validator_cls", "tests/test_validators.py::test_literal_validator", "tests/test_validators.py::test_literal_validator_str_enum", "tests/test_validators.py::test_nested_literal_validator", "tests/test_validators.py::test_union_literal_with_constraints", "tests/test_validators.py::test_field_that_is_being_validated_is_excluded_from_validator_values", "tests/test_validators.py::test_exceptions_in_field_validators_restore_original_field_value", "tests/test_validators.py::test_overridden_root_validators" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2022-09-26 20:01:58+00:00
mit
4,882
pydantic__pydantic-4653
diff --git a/pydantic/generics.py b/pydantic/generics.py --- a/pydantic/generics.py +++ b/pydantic/generics.py @@ -64,7 +64,11 @@ def __class_getitem__(cls: Type[GenericModelT], params: Union[Type[Any], Tuple[T """ def _cache_key(_params: Any) -> Tuple[Type[GenericModelT], Any, Tuple[Any, ...]]: - return cls, _params, get_args(_params) + args = get_args(_params) + # python returns a list for Callables, which is not hashable + if len(args) == 2 and isinstance(args[0], list): + args = (tuple(args[0]), args[1]) + return cls, _params, args cached = _generic_types_cache.get(_cache_key(params)) if cached is not None:
pydantic/pydantic
b516de7f5333b17290059b9ae7b5e76259ec2898
diff --git a/tests/test_generics.py b/tests/test_generics.py --- a/tests/test_generics.py +++ b/tests/test_generics.py @@ -7,6 +7,7 @@ ClassVar, Dict, Generic, + Iterable, List, Mapping, Optional, @@ -234,6 +235,32 @@ class Model(GenericModel, Generic[T]): assert len(_generic_types_cache) == cache_size + 2 +def test_cache_keys_are_hashable(): + cache_size = len(_generic_types_cache) + T = TypeVar('T') + C = Callable[[str, Dict[str, Any]], Iterable[str]] + + class MyGenericModel(GenericModel, Generic[T]): + t: T + + # Callable's first params get converted to a list, which is not hashable. + # Make sure we can handle that special case + Simple = MyGenericModel[Callable[[int], str]] + assert len(_generic_types_cache) == cache_size + 2 + # Nested Callables + MyGenericModel[Callable[[C], Iterable[str]]] + assert len(_generic_types_cache) == cache_size + 4 + MyGenericModel[Callable[[Simple], Iterable[int]]] + assert len(_generic_types_cache) == cache_size + 6 + MyGenericModel[Callable[[MyGenericModel[C]], Iterable[int]]] + assert len(_generic_types_cache) == cache_size + 10 + + class Model(BaseModel): + x: MyGenericModel[Callable[[C], Iterable[str]]] = Field(...) + + assert len(_generic_types_cache) == cache_size + 10 + + def test_generic_config(): data_type = TypeVar('data_type')
`GenericModel` calling `get_args()` which is not hashable See https://github.com/pydantic/pydantic/pull/4482#issuecomment-1253289404 From @pepastach > We recently bumped Pydantic from 1.10.1 to 1.10.2 and our tests started failing. After some lengthy investigation I found this change to be the root cause. I'd like to ask you for your opinions. > > We have a Pydantic model with a field such as > > ```python > f: MyGenericModel[Callable[[Task, Dict[str, Any]], Iterable[Result]]] = Field(...) > ``` > > Just importing Python module with this code gives me: > > ``` > cls = <class 'foo.MyGenericModel'> > params = typing.Callable[[foo.Task, typing.Dict[str, typing.Any]], typing.Iterable[foo.Result]] > > def __class_getitem__(cls: Type[GenericModelT], params: Union[Type[Any], Tuple[Type[Any], ...]]) -> Type[Any]: > """Instantiates a new class from a generic class `cls` and type variables `params`. > > :param params: Tuple of types the class . Given a generic class > `Model` with 2 type variables and a concrete model `Model[str, int]`, > the value `(str, int)` would be passed to `params`. > :return: New model class inheriting from `cls` with instantiated > types described by `params`. If no parameters are given, `cls` is > returned as is. > > """ > > def _cache_key(_params: Any) -> Tuple[Type[GenericModelT], Any, Tuple[Any, ...]]: > return cls, _params, get_args(_params) > > > cached = _generic_types_cache.get(_cache_key(params)) > E TypeError: unhashable type: 'list' > ``` > > The problem seems to be that the function `GenericModel._cache_key()` now calls `get_args()` which in turns calls Python's `typing.get_args()` -> and this function returns a tuple with a list in it. And that makes it unhashable. > > ```python > def get_args(tp): > """Get type arguments with all substitutions performed. > > For unions, basic simplifications used by Union constructor are performed. > Examples:: > get_args(Dict[str, int]) == (str, int) > get_args(int) == () > get_args(Union[int, Union[T, int], str][int]) == (int, str) > get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int]) > get_args(Callable[[], T][int]) == ([], int) > """ > if isinstance(tp, _GenericAlias) and not tp._special: > res = tp.__args__ > if get_origin(tp) is collections.abc.Callable and res[0] is not Ellipsis: > res = (list(res[:-1]), res[-1]) # <======== this list is a problem > return res > return () > ``` > > If I skip the callable typing and only define the field as > > ```python > f: MyGenericModel[Callable] = Field(...) > ``` > > then it runs okay. > > Thanks in advance! --- Reply from @sveinugu > @pepastach Hmm... Seems we did not think of that. Surprised that typing uses lists and not tuples for Callable arguments, but there is probably a good reason for this (or it might be just that it would be too much a nuisance to switch between brackets and parentheses...). In any case, there might be other examples of unhashable return values from `get_params`, so a simple solution could be to just catch `TypeError` and in that case default to the previous _cache_key generation. > > I am new as contributor to pydantic, but I assume it would be cleanest if you could create another issue for this.
0.0
b516de7f5333b17290059b9ae7b5e76259ec2898
[ "tests/test_generics.py::test_cache_keys_are_hashable" ]
[ "tests/test_generics.py::test_generic_name", "tests/test_generics.py::test_double_parameterize_error", "tests/test_generics.py::test_value_validation", "tests/test_generics.py::test_methods_are_inherited", "tests/test_generics.py::test_config_is_inherited", "tests/test_generics.py::test_default_argument", "tests/test_generics.py::test_default_argument_for_typevar", "tests/test_generics.py::test_classvar", "tests/test_generics.py::test_non_annotated_field", "tests/test_generics.py::test_must_inherit_from_generic", "tests/test_generics.py::test_parameters_placed_on_generic", "tests/test_generics.py::test_parameters_must_be_typevar", "tests/test_generics.py::test_subclass_can_be_genericized", "tests/test_generics.py::test_parameter_count", "tests/test_generics.py::test_cover_cache", "tests/test_generics.py::test_generic_config", "tests/test_generics.py::test_enum_generic", "tests/test_generics.py::test_generic", "tests/test_generics.py::test_alongside_concrete_generics", "tests/test_generics.py::test_complex_nesting", "tests/test_generics.py::test_required_value", "tests/test_generics.py::test_optional_value", "tests/test_generics.py::test_custom_schema", "tests/test_generics.py::test_child_schema", "tests/test_generics.py::test_custom_generic_naming", "tests/test_generics.py::test_nested", "tests/test_generics.py::test_partial_specification", "tests/test_generics.py::test_partial_specification_with_inner_typevar", "tests/test_generics.py::test_partial_specification_name", "tests/test_generics.py::test_partial_specification_instantiation", "tests/test_generics.py::test_partial_specification_instantiation_bounded", "tests/test_generics.py::test_typevar_parametrization", "tests/test_generics.py::test_multiple_specification", "tests/test_generics.py::test_generic_subclass_of_concrete_generic", "tests/test_generics.py::test_generic_model_pickle", "tests/test_generics.py::test_generic_model_from_function_pickle_fail", "tests/test_generics.py::test_generic_model_redefined_without_cache_fail", "tests/test_generics.py::test_generic_model_caching_detect_order_of_union_args_basic", "tests/test_generics.py::test_get_caller_frame_info", "tests/test_generics.py::test_get_caller_frame_info_called_from_module", "tests/test_generics.py::test_get_caller_frame_info_when_sys_getframe_undefined", "tests/test_generics.py::test_iter_contained_typevars", "tests/test_generics.py::test_nested_identity_parameterization", "tests/test_generics.py::test_replace_types", "tests/test_generics.py::test_replace_types_with_user_defined_generic_type_field", "tests/test_generics.py::test_replace_types_identity_on_unchanged", "tests/test_generics.py::test_deep_generic", "tests/test_generics.py::test_deep_generic_with_inner_typevar", "tests/test_generics.py::test_deep_generic_with_referenced_generic", "tests/test_generics.py::test_deep_generic_with_referenced_inner_generic", "tests/test_generics.py::test_deep_generic_with_multiple_typevars", "tests/test_generics.py::test_deep_generic_with_multiple_inheritance", "tests/test_generics.py::test_generic_with_referenced_generic_type_1", "tests/test_generics.py::test_generic_with_referenced_nested_typevar", "tests/test_generics.py::test_generic_with_callable", "tests/test_generics.py::test_generic_with_partial_callable", "tests/test_generics.py::test_generic_recursive_models", "tests/test_generics.py::test_generic_enum", "tests/test_generics.py::test_generic_literal", "tests/test_generics.py::test_generic_enums", "tests/test_generics.py::test_generic_with_user_defined_generic_field", "tests/test_generics.py::test_generic_annotated", "tests/test_generics.py::test_generic_subclass", "tests/test_generics.py::test_generic_subclass_with_partial_application", "tests/test_generics.py::test_multilevel_generic_binding", "tests/test_generics.py::test_generic_subclass_with_extra_type", "tests/test_generics.py::test_multi_inheritance_generic_binding", "tests/test_generics.py::test_parse_generic_json" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2022-10-24 20:28:50+00:00
mit
4,883
pydantic__pydantic-4781
diff --git a/pydantic/schema.py b/pydantic/schema.py --- a/pydantic/schema.py +++ b/pydantic/schema.py @@ -1,6 +1,7 @@ import re import warnings from collections import defaultdict +from dataclasses import is_dataclass from datetime import date, datetime, time, timedelta from decimal import Decimal from enum import Enum @@ -971,7 +972,14 @@ def multitypes_literal_field_for_schema(values: Tuple[Any, ...], field: ModelFie def encode_default(dft: Any) -> Any: - if isinstance(dft, Enum): + from .main import BaseModel + + if isinstance(dft, BaseModel) or is_dataclass(dft): + dft = cast('dict[str, Any]', pydantic_encoder(dft)) + + if isinstance(dft, dict): + return {encode_default(k): encode_default(v) for k, v in dft.items()} + elif isinstance(dft, Enum): return dft.value elif isinstance(dft, (int, float, str)): return dft @@ -979,8 +987,6 @@ def encode_default(dft: Any) -> Any: t = dft.__class__ seq_args = (encode_default(v) for v in dft) return t(*seq_args) if is_namedtuple(t) else t(seq_args) - elif isinstance(dft, dict): - return {encode_default(k): encode_default(v) for k, v in dft.items()} elif dft is None: return None else:
pydantic/pydantic
78ca710fe769552d91c12adf972a9c88a2a1a90f
Thanks for reporting, if there's an easy fix, happy to accept a PR for 1.10.3. Otherwise, let's make sure we get this right in v2. Tbh, there are lots of types that currently break JsonSchema.
diff --git a/tests/test_schema.py b/tests/test_schema.py --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -1523,6 +1523,38 @@ class UserModel(BaseModel): } +def test_model_default(): + """Make sure inner model types are encoded properly""" + + class Inner(BaseModel): + a: Dict[Path, str] = {Path(): ''} + + class Outer(BaseModel): + inner: Inner = Inner() + + assert Outer.schema() == { + 'definitions': { + 'Inner': { + 'properties': { + 'a': { + 'additionalProperties': {'type': 'string'}, + 'default': {'.': ''}, + 'title': 'A', + 'type': 'object', + } + }, + 'title': 'Inner', + 'type': 'object', + } + }, + 'properties': { + 'inner': {'allOf': [{'$ref': '#/definitions/Inner'}], 'default': {'a': {'.': ''}}, 'title': 'Inner'} + }, + 'title': 'Outer', + 'type': 'object', + } + + @pytest.mark.parametrize( 'kwargs,type_,expected_extra', [
`schema_json` can't encode default value of`dict[UUID, Any]` and raises `TypeError` ### Initial Checks - [X] I have searched GitHub for a duplicate issue and I'm sure this is something new - [X] I have searched Google & StackOverflow for a solution and couldn't find anything - [X] I have read and followed [the docs](https://pydantic-docs.helpmanual.io) and still think this is a bug - [X] I am confident that the issue is with pydantic (not my code, or another library in the ecosystem like [FastAPI](https://fastapi.tiangolo.com) or [mypy](https://mypy.readthedocs.io/en/stable)) ### Description When a model has default value of `{uuid4(): "..."}`, and being a dafault value of another model, `json_schema` fails to generate schema with an error. ### Example Code ```Python from uuid import uuid4 from pydantic import BaseModel from pydantic import UUID4 class Service(BaseModel): urls: dict[UUID4, str] = {uuid4(): "https://example.com"} class Settings(BaseModel): service: Service = Service() print(Settings.schema_json(indent=4, ensure_ascii=False)) ``` ```py Traceback (most recent call last): File "/Users/bobronium/Library/Application Support/JetBrains/PyCharm2022.3/scratches/scratch_131.py", line 15, in <module> print(Settings.schema_json(indent=4, ensure_ascii=False)) File "pydantic/main.py", line 674, in pydantic.main.BaseModel.schema_json File "/Users/bobronium/.pyenv/versions/3.10.1/lib/python3.10/json/__init__.py", line 238, in dumps **kw).encode(obj) File "/Users/bobronium/.pyenv/versions/3.10.1/lib/python3.10/json/encoder.py", line 201, in encode chunks = list(chunks) File "/Users/bobronium/.pyenv/versions/3.10.1/lib/python3.10/json/encoder.py", line 431, in _iterencode yield from _iterencode_dict(o, _current_indent_level) File "/Users/bobronium/.pyenv/versions/3.10.1/lib/python3.10/json/encoder.py", line 405, in _iterencode_dict yield from chunks File "/Users/bobronium/.pyenv/versions/3.10.1/lib/python3.10/json/encoder.py", line 405, in _iterencode_dict yield from chunks File "/Users/bobronium/.pyenv/versions/3.10.1/lib/python3.10/json/encoder.py", line 405, in _iterencode_dict yield from chunks [Previous line repeated 1 more time] File "/Users/bobronium/.pyenv/versions/3.10.1/lib/python3.10/json/encoder.py", line 376, in _iterencode_dict raise TypeError(f'keys must be str, int, float, bool or None, ' TypeError: keys must be str, int, float, bool or None, not UUID ``` ### This works, though ```py from uuid import uuid4 from pydantic import BaseModel from pydantic import UUID4 class Service(BaseModel): urls: dict[UUID4, str] = {uuid4(): "https://example.com"} class Settings(BaseModel): service: Service # <--------- Notice no default value here print(Settings.schema_json(indent=4, ensure_ascii=False)) ``` <details> ```json { "title": "Settings", "type": "object", "properties": { "service": { "$ref": "#/definitions/Service" } }, "required": [ "service" ], "definitions": { "Service": { "title": "Service", "type": "object", "properties": { "urls": { "title": "Urls", "default": { "ac762f77-1e77-4ff8-906a-fd63ca622938": "https://example.com" }, "type": "object", "additionalProperties": { "type": "string" } } } } } } ``` </details> ### Python, Pydantic & OS Version ```Text pydantic version: 1.10.2 pydantic compiled: True install path: .venv/lib/python3.10/site-packages/pydantic python version: 3.10.1 (main, Jan 31 2022, 09:16:52) [Clang 13.0.0 (clang-1300.0.29.3)] platform: macOS-12.4-arm64-arm-64bit optional deps. installed: ['dotenv', 'typing-extensions'] ``` ### Affected Components - [ ] [Compatibility between releases](https://pydantic-docs.helpmanual.io/changelog/) - [ ] [Data validation/parsing](https://pydantic-docs.helpmanual.io/usage/models/#basic-model-usage) - [ ] [Data serialization](https://pydantic-docs.helpmanual.io/usage/exporting_models/) - `.dict()` and `.json()` - [X] [JSON Schema](https://pydantic-docs.helpmanual.io/usage/schema/) - [ ] [Dataclasses](https://pydantic-docs.helpmanual.io/usage/dataclasses/) - [ ] [Model Config](https://pydantic-docs.helpmanual.io/usage/model_config/) - [ ] [Field Types](https://pydantic-docs.helpmanual.io/usage/types/) - adding or changing a particular data type - [ ] [Function validation decorator](https://pydantic-docs.helpmanual.io/usage/validation_decorator/) - [ ] [Generic Models](https://pydantic-docs.helpmanual.io/usage/models/#generic-models) - [ ] [Other Model behaviour](https://pydantic-docs.helpmanual.io/usage/models/) - `construct()`, pickling, private attributes, ORM mode - [ ] [Plugins](https://pydantic-docs.helpmanual.io/) and integration with other tools - mypy, FastAPI, python-devtools, Hypothesis, VS Code, PyCharm, etc.
0.0
78ca710fe769552d91c12adf972a9c88a2a1a90f
[ "tests/test_schema.py::test_model_default" ]
[ "tests/test_schema.py::test_key", "tests/test_schema.py::test_by_alias", "tests/test_schema.py::test_ref_template", "tests/test_schema.py::test_by_alias_generator", "tests/test_schema.py::test_sub_model", "tests/test_schema.py::test_schema_class", "tests/test_schema.py::test_schema_repr", "tests/test_schema.py::test_schema_class_by_alias", "tests/test_schema.py::test_choices", "tests/test_schema.py::test_enum_modify_schema", "tests/test_schema.py::test_enum_schema_custom_field", "tests/test_schema.py::test_enum_and_model_have_same_behaviour", "tests/test_schema.py::test_enum_includes_extra_without_other_params", "tests/test_schema.py::test_list_enum_schema_extras", "tests/test_schema.py::test_enum_schema_cleandoc", "tests/test_schema.py::test_json_schema", "tests/test_schema.py::test_list_sub_model", "tests/test_schema.py::test_optional", "tests/test_schema.py::test_any", "tests/test_schema.py::test_set", "tests/test_schema.py::test_const_str", "tests/test_schema.py::test_const_false", "tests/test_schema.py::test_tuple[tuple-extra_props0]", "tests/test_schema.py::test_tuple[field_type1-extra_props1]", "tests/test_schema.py::test_tuple[field_type2-extra_props2]", "tests/test_schema.py::test_tuple[field_type3-extra_props3]", "tests/test_schema.py::test_deque", "tests/test_schema.py::test_bool", "tests/test_schema.py::test_strict_bool", "tests/test_schema.py::test_dict", "tests/test_schema.py::test_list", "tests/test_schema.py::test_list_union_dict[field_type0-expected_schema0]", "tests/test_schema.py::test_list_union_dict[field_type1-expected_schema1]", "tests/test_schema.py::test_list_union_dict[field_type2-expected_schema2]", "tests/test_schema.py::test_list_union_dict[field_type3-expected_schema3]", "tests/test_schema.py::test_list_union_dict[field_type4-expected_schema4]", "tests/test_schema.py::test_date_types[datetime-expected_schema0]", "tests/test_schema.py::test_date_types[date-expected_schema1]", "tests/test_schema.py::test_date_types[time-expected_schema2]", "tests/test_schema.py::test_date_types[timedelta-expected_schema3]", "tests/test_schema.py::test_date_constrained_types[ConstrainedDate-expected_schema0]", "tests/test_schema.py::test_date_constrained_types[ConstrainedDateValue-expected_schema1]", "tests/test_schema.py::test_date_constrained_types[ConstrainedDateValue-expected_schema2]", "tests/test_schema.py::test_date_constrained_types[ConstrainedDateValue-expected_schema3]", "tests/test_schema.py::test_str_basic_types[field_type0-expected_schema0]", "tests/test_schema.py::test_str_basic_types[field_type1-expected_schema1]", "tests/test_schema.py::test_str_basic_types[field_type2-expected_schema2]", "tests/test_schema.py::test_str_basic_types[field_type3-expected_schema3]", "tests/test_schema.py::test_str_constrained_types[StrictStr-expected_schema0]", "tests/test_schema.py::test_str_constrained_types[ConstrainedStr-expected_schema1]", "tests/test_schema.py::test_str_constrained_types[ConstrainedStrValue-expected_schema2]", "tests/test_schema.py::test_special_str_types[AnyUrl-expected_schema0]", "tests/test_schema.py::test_special_str_types[UrlValue-expected_schema1]", "tests/test_schema.py::test_email_str_types[EmailStr-email]", "tests/test_schema.py::test_email_str_types[NameEmail-name-email]", "tests/test_schema.py::test_secret_types[SecretBytes-string]", "tests/test_schema.py::test_secret_types[SecretStr-string]", "tests/test_schema.py::test_special_int_types[ConstrainedInt-expected_schema0]", "tests/test_schema.py::test_special_int_types[ConstrainedIntValue-expected_schema1]", "tests/test_schema.py::test_special_int_types[ConstrainedIntValue-expected_schema2]", "tests/test_schema.py::test_special_int_types[ConstrainedIntValue-expected_schema3]", "tests/test_schema.py::test_special_int_types[PositiveInt-expected_schema4]", "tests/test_schema.py::test_special_int_types[NegativeInt-expected_schema5]", "tests/test_schema.py::test_special_int_types[NonNegativeInt-expected_schema6]", "tests/test_schema.py::test_special_int_types[NonPositiveInt-expected_schema7]", "tests/test_schema.py::test_special_float_types[ConstrainedFloat-expected_schema0]", "tests/test_schema.py::test_special_float_types[ConstrainedFloatValue-expected_schema1]", "tests/test_schema.py::test_special_float_types[ConstrainedFloatValue-expected_schema2]", "tests/test_schema.py::test_special_float_types[ConstrainedFloatValue-expected_schema3]", "tests/test_schema.py::test_special_float_types[PositiveFloat-expected_schema4]", "tests/test_schema.py::test_special_float_types[NegativeFloat-expected_schema5]", "tests/test_schema.py::test_special_float_types[NonNegativeFloat-expected_schema6]", "tests/test_schema.py::test_special_float_types[NonPositiveFloat-expected_schema7]", "tests/test_schema.py::test_special_float_types[ConstrainedDecimal-expected_schema8]", "tests/test_schema.py::test_special_float_types[ConstrainedDecimalValue-expected_schema9]", "tests/test_schema.py::test_special_float_types[ConstrainedDecimalValue-expected_schema10]", "tests/test_schema.py::test_special_float_types[ConstrainedDecimalValue-expected_schema11]", "tests/test_schema.py::test_uuid_types[UUID-uuid]", "tests/test_schema.py::test_uuid_types[UUID1-uuid1]", "tests/test_schema.py::test_uuid_types[UUID3-uuid3]", "tests/test_schema.py::test_uuid_types[UUID4-uuid4]", "tests/test_schema.py::test_uuid_types[UUID5-uuid5]", "tests/test_schema.py::test_path_types[FilePath-file-path]", "tests/test_schema.py::test_path_types[DirectoryPath-directory-path]", "tests/test_schema.py::test_path_types[Path-path]", "tests/test_schema.py::test_json_type", "tests/test_schema.py::test_ipv4address_type", "tests/test_schema.py::test_ipv6address_type", "tests/test_schema.py::test_ipvanyaddress_type", "tests/test_schema.py::test_ipv4interface_type", "tests/test_schema.py::test_ipv6interface_type", "tests/test_schema.py::test_ipvanyinterface_type", "tests/test_schema.py::test_ipv4network_type", "tests/test_schema.py::test_ipv6network_type", "tests/test_schema.py::test_ipvanynetwork_type", "tests/test_schema.py::test_callable_type[type_0-default_value0]", "tests/test_schema.py::test_callable_type[type_1-<lambda>]", "tests/test_schema.py::test_callable_type[type_2-default_value2]", "tests/test_schema.py::test_callable_type[type_3-<lambda>]", "tests/test_schema.py::test_error_non_supported_types", "tests/test_schema.py::test_flat_models_unique_models", "tests/test_schema.py::test_flat_models_with_submodels", "tests/test_schema.py::test_flat_models_with_submodels_from_sequence", "tests/test_schema.py::test_model_name_maps", "tests/test_schema.py::test_schema_overrides", "tests/test_schema.py::test_schema_overrides_w_union", "tests/test_schema.py::test_schema_from_models", "tests/test_schema.py::test_schema_with_refs[#/components/schemas/-None]", "tests/test_schema.py::test_schema_with_refs[None-#/components/schemas/{model}]", "tests/test_schema.py::test_schema_with_refs[#/components/schemas/-#/{model}/schemas/]", "tests/test_schema.py::test_schema_with_custom_ref_template", "tests/test_schema.py::test_schema_ref_template_key_error", "tests/test_schema.py::test_schema_no_definitions", "tests/test_schema.py::test_list_default", "tests/test_schema.py::test_enum_str_default", "tests/test_schema.py::test_enum_int_default", "tests/test_schema.py::test_dict_default", "tests/test_schema.py::test_constraints_schema[kwargs0-str-expected_extra0]", "tests/test_schema.py::test_constraints_schema[kwargs1-ConstrainedStrValue-expected_extra1]", "tests/test_schema.py::test_constraints_schema[kwargs2-str-expected_extra2]", "tests/test_schema.py::test_constraints_schema[kwargs3-bytes-expected_extra3]", "tests/test_schema.py::test_constraints_schema[kwargs4-str-expected_extra4]", "tests/test_schema.py::test_constraints_schema[kwargs5-int-expected_extra5]", "tests/test_schema.py::test_constraints_schema[kwargs6-int-expected_extra6]", "tests/test_schema.py::test_constraints_schema[kwargs7-int-expected_extra7]", "tests/test_schema.py::test_constraints_schema[kwargs8-int-expected_extra8]", "tests/test_schema.py::test_constraints_schema[kwargs9-int-expected_extra9]", "tests/test_schema.py::test_constraints_schema[kwargs10-float-expected_extra10]", "tests/test_schema.py::test_constraints_schema[kwargs11-float-expected_extra11]", "tests/test_schema.py::test_constraints_schema[kwargs12-float-expected_extra12]", "tests/test_schema.py::test_constraints_schema[kwargs13-float-expected_extra13]", "tests/test_schema.py::test_constraints_schema[kwargs14-float-expected_extra14]", "tests/test_schema.py::test_constraints_schema[kwargs15-float-expected_extra15]", "tests/test_schema.py::test_constraints_schema[kwargs16-float-expected_extra16]", "tests/test_schema.py::test_constraints_schema[kwargs17-float-expected_extra17]", "tests/test_schema.py::test_constraints_schema[kwargs18-float-expected_extra18]", "tests/test_schema.py::test_constraints_schema[kwargs19-Decimal-expected_extra19]", "tests/test_schema.py::test_constraints_schema[kwargs20-Decimal-expected_extra20]", "tests/test_schema.py::test_constraints_schema[kwargs21-Decimal-expected_extra21]", "tests/test_schema.py::test_constraints_schema[kwargs22-Decimal-expected_extra22]", "tests/test_schema.py::test_constraints_schema[kwargs23-Decimal-expected_extra23]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs0-int]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs1-float]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs2-Decimal]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs3-bool]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs4-int]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs5-str]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs6-bytes]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs7-str]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs8-bool]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs9-type_9]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs10-type_10]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs11-ConstrainedListValue]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs12-ConstrainedSetValue]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs13-ConstrainedFrozenSetValue]", "tests/test_schema.py::test_constraints_schema_validation[kwargs0-str-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs1-str-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs2-bytes-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs3-str-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs4-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs5-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs6-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs7-int-2]", "tests/test_schema.py::test_constraints_schema_validation[kwargs8-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs9-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs10-int-5]", "tests/test_schema.py::test_constraints_schema_validation[kwargs11-float-3.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs12-float-2.1]", "tests/test_schema.py::test_constraints_schema_validation[kwargs13-float-3.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs14-float-4.9]", "tests/test_schema.py::test_constraints_schema_validation[kwargs15-float-3.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs16-float-2.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs17-float-3.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs18-float-5.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs19-float-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs20-float-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs21-Decimal-value21]", "tests/test_schema.py::test_constraints_schema_validation[kwargs22-Decimal-value22]", "tests/test_schema.py::test_constraints_schema_validation[kwargs23-Decimal-value23]", "tests/test_schema.py::test_constraints_schema_validation[kwargs24-Decimal-value24]", "tests/test_schema.py::test_constraints_schema_validation[kwargs25-Decimal-value25]", "tests/test_schema.py::test_constraints_schema_validation[kwargs26-Decimal-value26]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs0-str-foobar]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs1-str-f]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs2-str-bar]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs3-int-2]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs4-int-5]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs5-int-1]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs6-int-6]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs7-float-2.0]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs8-float-5.0]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs9-float-1.9]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs10-float-5.1]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs11-Decimal-value11]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs12-Decimal-value12]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs13-Decimal-value13]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs14-Decimal-value14]", "tests/test_schema.py::test_schema_kwargs", "tests/test_schema.py::test_schema_dict_constr", "tests/test_schema.py::test_bytes_constrained_types[ConstrainedBytes-expected_schema0]", "tests/test_schema.py::test_bytes_constrained_types[ConstrainedBytesValue-expected_schema1]", "tests/test_schema.py::test_optional_dict", "tests/test_schema.py::test_optional_validator", "tests/test_schema.py::test_field_with_validator", "tests/test_schema.py::test_unparameterized_schema_generation", "tests/test_schema.py::test_known_model_optimization", "tests/test_schema.py::test_root", "tests/test_schema.py::test_root_list", "tests/test_schema.py::test_root_nested_model", "tests/test_schema.py::test_new_type_schema", "tests/test_schema.py::test_literal_schema", "tests/test_schema.py::test_literal_enum", "tests/test_schema.py::test_color_type", "tests/test_schema.py::test_model_with_schema_extra", "tests/test_schema.py::test_model_with_schema_extra_callable", "tests/test_schema.py::test_model_with_schema_extra_callable_no_model_class", "tests/test_schema.py::test_model_with_schema_extra_callable_classmethod", "tests/test_schema.py::test_model_with_schema_extra_callable_instance_method", "tests/test_schema.py::test_model_with_extra_forbidden", "tests/test_schema.py::test_enforced_constraints[int-kwargs0-field_schema0]", "tests/test_schema.py::test_enforced_constraints[annotation1-kwargs1-field_schema1]", "tests/test_schema.py::test_enforced_constraints[annotation2-kwargs2-field_schema2]", "tests/test_schema.py::test_enforced_constraints[annotation3-kwargs3-field_schema3]", "tests/test_schema.py::test_enforced_constraints[annotation4-kwargs4-field_schema4]", "tests/test_schema.py::test_enforced_constraints[annotation5-kwargs5-field_schema5]", "tests/test_schema.py::test_enforced_constraints[annotation6-kwargs6-field_schema6]", "tests/test_schema.py::test_enforced_constraints[annotation7-kwargs7-field_schema7]", "tests/test_schema.py::test_real_vs_phony_constraints", "tests/test_schema.py::test_subfield_field_info", "tests/test_schema.py::test_dataclass", "tests/test_schema.py::test_schema_attributes", "tests/test_schema.py::test_model_process_schema_enum", "tests/test_schema.py::test_path_modify_schema", "tests/test_schema.py::test_frozen_set", "tests/test_schema.py::test_iterable", "tests/test_schema.py::test_new_type", "tests/test_schema.py::test_multiple_models_with_same_name", "tests/test_schema.py::test_multiple_enums_with_same_name", "tests/test_schema.py::test_schema_for_generic_field", "tests/test_schema.py::test_namedtuple_default", "tests/test_schema.py::test_advanced_generic_schema", "tests/test_schema.py::test_nested_generic", "tests/test_schema.py::test_nested_generic_model", "tests/test_schema.py::test_complex_nested_generic", "tests/test_schema.py::test_schema_with_field_parameter", "tests/test_schema.py::test_discriminated_union", "tests/test_schema.py::test_discriminated_annotated_union", "tests/test_schema.py::test_alias_same", "tests/test_schema.py::test_nested_python_dataclasses", "tests/test_schema.py::test_discriminated_union_in_list", "tests/test_schema.py::test_extra_inheritance", "tests/test_schema.py::test_model_with_type_attributes" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2022-11-24 10:57:40+00:00
mit
4,884
pydantic__pydantic-4884
diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -508,6 +508,7 @@ def json( def _enforce_dict_if_root(cls, obj: Any) -> Any: if cls.__custom_root_type__ and ( not (isinstance(obj, dict) and obj.keys() == {ROOT_KEY}) + and not (isinstance(obj, BaseModel) and obj.__fields__.keys() == {ROOT_KEY}) or cls.__fields__[ROOT_KEY].shape in MAPPING_LIKE_SHAPES ): return {ROOT_KEY: obj}
pydantic/pydantic
c04923ca97b511c1a961cb018e0a5df3dd501ea2
diff --git a/tests/test_parse.py b/tests/test_parse.py --- a/tests/test_parse.py +++ b/tests/test_parse.py @@ -46,6 +46,7 @@ class MyModel(BaseModel): m = MyModel.parse_obj('a') assert m.dict() == {'__root__': 'a'} assert m.__root__ == 'a' + assert MyModel.parse_obj(m) == m def test_parse_root_list():
Pydantic doesn't properly parses models with custom root into custom root models ### Initial Checks - [X] I have searched GitHub for a duplicate issue and I'm sure this is something new - [X] I have searched Google & StackOverflow for a solution and couldn't find anything - [X] I have read and followed [the docs](https://pydantic-docs.helpmanual.io) and still think this is a bug - [X] I am confident that the issue is with pydantic (not my code, or another library in the ecosystem like [FastAPI](https://fastapi.tiangolo.com) or [mypy](https://mypy.readthedocs.io/en/stable)) ### Description This is because [_enforce_dict_if_root()](https://github.com/pydantic/pydantic/blob/1.10.X-fixes/pydantic/main.py#L510) checks only for **dicts** with root key but not for **models** with root key. ### Example Code ```Python from pydantic import BaseModel class Test(BaseModel): __root__: int Test.parse_obj(dict(Test.parse_obj(1))) # works fine Test.parse_obj(Test.parse_obj(1)) # Expected: Test(__root__=1) # Actual: pydantic.error_wrappers.ValidationError: 1 validation error for Test # __root__ # value is not a valid integer (type=type_error.integer) ``` ### Python, Pydantic & OS Version ```Text pydantic version: 1.10.2 pydantic compiled: True install path: C:\Users\gou17\AppData\Local\Programs\Python\Python310\Lib\site-packages\pydantic python version: 3.10.4 (tags/v3.10.4:9d38120, Mar 23 2022, 23:13:41) [MSC v.1929 64 bit (AMD64)] platform: Windows-10-10.0.22621-SP0 optional deps. installed: ['dotenv', 'email-validator', 'typing-extensions'] ``` ### Affected Components - [ ] [Compatibility between releases](https://pydantic-docs.helpmanual.io/changelog/) - [X] [Data validation/parsing](https://pydantic-docs.helpmanual.io/usage/models/#basic-model-usage) - [ ] [Data serialization](https://pydantic-docs.helpmanual.io/usage/exporting_models/) - `.dict()` and `.json()` - [ ] [JSON Schema](https://pydantic-docs.helpmanual.io/usage/schema/) - [ ] [Dataclasses](https://pydantic-docs.helpmanual.io/usage/dataclasses/) - [ ] [Model Config](https://pydantic-docs.helpmanual.io/usage/model_config/) - [ ] [Field Types](https://pydantic-docs.helpmanual.io/usage/types/) - adding or changing a particular data type - [ ] [Function validation decorator](https://pydantic-docs.helpmanual.io/usage/validation_decorator/) - [ ] [Generic Models](https://pydantic-docs.helpmanual.io/usage/models/#generic-models) - [ ] [Other Model behaviour](https://pydantic-docs.helpmanual.io/usage/models/) - `construct()`, pickling, private attributes, ORM mode - [ ] [Plugins](https://pydantic-docs.helpmanual.io/) and integration with other tools - mypy, FastAPI, python-devtools, Hypothesis, VS Code, PyCharm, etc.
0.0
c04923ca97b511c1a961cb018e0a5df3dd501ea2
[ "tests/test_parse.py::test_parse_obj_root" ]
[ "tests/test_parse.py::test_obj", "tests/test_parse.py::test_parse_obj_fails", "tests/test_parse.py::test_parse_obj_submodel", "tests/test_parse.py::test_parse_obj_wrong_model", "tests/test_parse.py::test_parse_root_list", "tests/test_parse.py::test_parse_nested_root_list", "tests/test_parse.py::test_parse_nested_root_tuple", "tests/test_parse.py::test_parse_nested_custom_root", "tests/test_parse.py::test_json", "tests/test_parse.py::test_json_ct", "tests/test_parse.py::test_pickle_ct", "tests/test_parse.py::test_pickle_proto", "tests/test_parse.py::test_pickle_not_allowed", "tests/test_parse.py::test_bad_ct", "tests/test_parse.py::test_bad_proto", "tests/test_parse.py::test_file_json", "tests/test_parse.py::test_file_json_no_ext", "tests/test_parse.py::test_file_json_loads", "tests/test_parse.py::test_file_pickle", "tests/test_parse.py::test_file_pickle_no_ext", "tests/test_parse.py::test_const_differentiates_union" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2022-12-29 03:56:21+00:00
mit
4,885
pydantic__pydantic-4963
diff --git a/pydantic/dataclasses.py b/pydantic/dataclasses.py --- a/pydantic/dataclasses.py +++ b/pydantic/dataclasses.py @@ -31,6 +31,7 @@ class M: The trick is to create a wrapper around `M` that will act as a proxy to trigger validation without altering default `M` behaviour. """ +import copy import sys from contextlib import contextmanager from functools import wraps @@ -260,6 +261,12 @@ def __setattr__(self, __name: str, __value: Any) -> None: def __instancecheck__(self, instance: Any) -> bool: return isinstance(instance, self.__dataclass__) + def __copy__(self) -> 'DataclassProxy': + return DataclassProxy(copy.copy(self.__dataclass__)) + + def __deepcopy__(self, memo: Any) -> 'DataclassProxy': + return DataclassProxy(copy.deepcopy(self.__dataclass__, memo)) + def _add_pydantic_validation_attributes( # noqa: C901 (ignore complexity) dc_cls: Type['Dataclass'],
pydantic/pydantic
0bc7cd39a90fa46c23ca9ef9d19c51ecb8e1145c
You can resolve this by removing the extra `@dataclasses.dataclass`. Might have similar origin to #4907. I applied both decorators to shorten the example. In my actual code I can't remove the extra `dataclass` because I have the following situation: ``` # can't change this definition @dataclasses.dataclass class ValueObj: name: str # IO module ValueObj = pydantic.dataclasses.dataclass(domain.ValueObj) ``` P.S. Your response time is impressive! That was luck, often it's not so good. :-) As mentioned on the linked issue, the current dataclass support is very involved, most of our bug fixes have been related to trying to patch dataclass edge cases. I'd strongly prefer not to change dataclass support again in v1, but hopefully we can fix this properly in v2. Unless we can find a trivial solution. On Fri, 13 Jan 2023, 16:34 mbillingr, ***@***.***> wrote: > I applied both decorators to shorten the example. In my actual code I > can't remove the extra dataclass because I have the following situation: > > # can't change this definition > @dataclasses.dataclass > class ValueObj: > name: str > > > # IO module > ValueObj = pydantic.dataclasses.dataclass(domain.ValueObj) > > P.S. Your response time is impressive! > > — > Reply to this email directly, view it on GitHub > <https://github.com/pydantic/pydantic/issues/4949#issuecomment-1382095014>, > or unsubscribe > <https://github.com/notifications/unsubscribe-auth/AA62GGN3EVBLS5NK3MWUXSDWSF7XPANCNFSM6AAAAAAT2SPHYU> > . > You are receiving this because you commented.Message ID: > ***@***.***> > I can understand that you don't feel the urge to touch the dataclass support in v1. For me it's already a win to know that this is really a bug and not just me misusing your API. If it can't be fixed upstream I'll find a workaround. (Even though I'm not particularly fond of the idea, it should be easy to just duplicate the `ValueObj` definition.) Starting Monday, I could free some time to look into this in more detail. Would you accept a pull request if I managed to find a simple fix? (I don't expect to, but you never know... :)) Possibly, it's really up to @PrettyWood who is the "master of dataclasses". I dug deeper and found that the recursion occurs while deep-copying a `DataclassProxy`. At some point Python's `copy._reconstruct` function creates a new uninitialized `DataclassProxy`, then checks if this has a `__setstate__` attribute. `DataclassProxy.__getattr__` wants to delegate the attribute access to it's `__dataclass__` field, but being uninitialized, this field does not exist and looking it up invokes `DataclassProxy.__getattr__` again... I think this problem could be solved by adding a `__deepcopy__` method to `DataclassProxy`: ```python class DataclassProxy: # ... def __deepcopy__(self, memo: Any) -> "DataclassProxy": return DataclassProxy(deepcopy(self.__dataclass__, memo)) ``` This seems to fix my example above (I did not check if it breaks anything else, though). Yup @mbillingr ! Seems like the right fix 👍
diff --git a/tests/test_dataclasses.py b/tests/test_dataclasses.py --- a/tests/test_dataclasses.py +++ b/tests/test_dataclasses.py @@ -1,3 +1,4 @@ +import copy import dataclasses import pickle import re @@ -1608,3 +1609,25 @@ def check_b(cls, v): assert m1.a == m2.a == 3 assert m1.b == m2.b == 'b' assert m1.c == m2.c == 3.0 + + +def test_can_copy_wrapped_dataclass_type(): + @pydantic.dataclasses.dataclass + @dataclasses.dataclass + class A: + name: int + + B = copy.copy(A) + assert B is not A + assert B(1) == A(1) + + +def test_can_deepcopy_wrapped_dataclass_type(): + @pydantic.dataclasses.dataclass + @dataclasses.dataclass + class A: + name: int + + B = copy.deepcopy(A) + assert B is not A + assert B(1) == A(1)
RecursionError in combination with Dataclasses and create_model ### Initial Checks - [X] I have searched GitHub for a duplicate issue and I'm sure this is something new - [X] I have searched Google & StackOverflow for a solution and couldn't find anything - [X] I have read and followed [the docs](https://pydantic-docs.helpmanual.io) and still think this is a bug - [X] I am confident that the issue is with pydantic (not my code, or another library in the ecosystem like [FastAPI](https://fastapi.tiangolo.com) or [mypy](https://mypy.readthedocs.io/en/stable)) ### Description I'm getting a `RecursionError` when calling `pydantic.create_model` with a `__base__` class that contains fields which are *both* pydantic and vanilla dataclasses. Most of the recursion related problems I could find were related to recursive data types (such as #1370). There is no (obvious) recursion in the data structures I use. ``` Traceback (most recent call last): File "/home/martin/.config/JetBrains/PyCharm2022.3/scratches/scratch_26.py", line 15, in <module> pydantic.create_model("ArbitraryName", __base__=ResponseSchema) File "pydantic/main.py", line 1027, in pydantic.main.create_model File "pydantic/main.py", line 139, in pydantic.main.ModelMetaclass.__new__ File "pydantic/utils.py", line 695, in pydantic.utils.smart_deepcopy File "/home/martin/.pyenv/versions/3.11.0/lib/python3.11/copy.py", line 146, in deepcopy y = copier(x, memo) ^^^^^^^^^^^^^^^ [ whole bunch of deepcopy-related lines omitted ] File "/home/martin/.pyenv/versions/3.11.0/lib/python3.11/copy.py", line 272, in _reconstruct if hasattr(y, '__setstate__'): ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "pydantic/dataclasses.py", line 255, in pydantic.dataclasses.DataclassProxy.__getattr__ 'type', [Previous line repeated 979 more times] RecursionError: maximum recursion depth exceeded while calling a Python object ``` There is an easy workaround: Don't use both decorators. Unfortunately, I need both because the class is defined in another module and I need to wrap it with pydantic for I/O validation. Originally, I ran into this problem using FastAPI, but managed to reproduce it using pydantic alone. So I hope this is the correct place to ask. ### Example Code ```Python import dataclasses import pydantic @pydantic.dataclasses.dataclass @dataclasses.dataclass class ValueObj: name: str class ResponseSchema(pydantic.BaseModel): value: ValueObj pydantic.create_model("ArbitraryName", __base__=ResponseSchema) ``` ### Python, Pydantic & OS Version ```Text pydantic version: 1.10.4 pydantic compiled: True install path: /home/martin/.cache/pypoetry/virtualenvs/private/lib/python3.11/site-packages/pydantic python version: 3.11.0 (main, Nov 7 2022, 07:51:46) [GCC 12.2.0] platform: Linux-6.1.4-arch1-1-x86_64-with-glibc2.36 optional deps. installed: ['typing-extensions'] Also reproducible with slightly older versions: pydantic version: 1.10.2 pydantic compiled: True install path: /home/martin/.cache/pypoetry/virtualenvs/private/lib/python3.9/site-packages/pydantic python version: 3.9.7 (default, Nov 7 2022, 07:48:33) [GCC 12.2.0] platform: Linux-6.1.4-arch1-1-x86_64-with-glibc2.36 optional deps. installed: ['typing-extensions'] ``` ### Affected Components - [ ] [Compatibility between releases](https://pydantic-docs.helpmanual.io/changelog/) - [ ] [Data validation/parsing](https://pydantic-docs.helpmanual.io/usage/models/#basic-model-usage) - [ ] [Data serialization](https://pydantic-docs.helpmanual.io/usage/exporting_models/) - `.model_dump()` and `.model_dump_json()` - [ ] [JSON Schema](https://pydantic-docs.helpmanual.io/usage/schema/) - [X] [Dataclasses](https://pydantic-docs.helpmanual.io/usage/dataclasses/) - [ ] [Model Config](https://pydantic-docs.helpmanual.io/usage/model_config/) - [x] [Field Types](https://pydantic-docs.helpmanual.io/usage/types/) - adding or changing a particular data type - [ ] [Function validation decorator](https://pydantic-docs.helpmanual.io/usage/validation_decorator/) - [ ] [Generic Models](https://pydantic-docs.helpmanual.io/usage/models/#generic-models) - [X] [Other Model behaviour](https://pydantic-docs.helpmanual.io/usage/models/) - `model_construct()`, pickling, private attributes, ORM mode - [ ] [Plugins](https://pydantic-docs.helpmanual.io/) and integration with other tools - mypy, FastAPI, python-devtools, Hypothesis, VS Code, PyCharm, etc.
0.0
0bc7cd39a90fa46c23ca9ef9d19c51ecb8e1145c
[ "tests/test_dataclasses.py::test_can_copy_wrapped_dataclass_type", "tests/test_dataclasses.py::test_can_deepcopy_wrapped_dataclass_type" ]
[ "tests/test_dataclasses.py::test_simple", "tests/test_dataclasses.py::test_model_name", "tests/test_dataclasses.py::test_value_error", "tests/test_dataclasses.py::test_frozen", "tests/test_dataclasses.py::test_validate_assignment", "tests/test_dataclasses.py::test_validate_assignment_error", "tests/test_dataclasses.py::test_not_validate_assignment", "tests/test_dataclasses.py::test_validate_assignment_value_change", "tests/test_dataclasses.py::test_validate_assignment_extra", "tests/test_dataclasses.py::test_post_init", "tests/test_dataclasses.py::test_post_init_validation", "tests/test_dataclasses.py::test_post_init_inheritance_chain", "tests/test_dataclasses.py::test_post_init_post_parse", "tests/test_dataclasses.py::test_post_init_post_parse_types", "tests/test_dataclasses.py::test_post_init_assignment", "tests/test_dataclasses.py::test_inheritance", "tests/test_dataclasses.py::test_validate_long_string_error", "tests/test_dataclasses.py::test_validate_assigment_long_string_error", "tests/test_dataclasses.py::test_no_validate_assigment_long_string_error", "tests/test_dataclasses.py::test_nested_dataclass", "tests/test_dataclasses.py::test_arbitrary_types_allowed", "tests/test_dataclasses.py::test_nested_dataclass_model", "tests/test_dataclasses.py::test_fields", "tests/test_dataclasses.py::test_default_factory_field", "tests/test_dataclasses.py::test_default_factory_singleton_field", "tests/test_dataclasses.py::test_schema", "tests/test_dataclasses.py::test_nested_schema", "tests/test_dataclasses.py::test_initvar", "tests/test_dataclasses.py::test_derived_field_from_initvar", "tests/test_dataclasses.py::test_initvars_post_init", "tests/test_dataclasses.py::test_initvars_post_init_post_parse", "tests/test_dataclasses.py::test_post_init_post_parse_without_initvars", "tests/test_dataclasses.py::test_classvar", "tests/test_dataclasses.py::test_frozenset_field", "tests/test_dataclasses.py::test_inheritance_post_init", "tests/test_dataclasses.py::test_hashable_required", "tests/test_dataclasses.py::test_hashable_optional[1]", "tests/test_dataclasses.py::test_hashable_optional[None]", "tests/test_dataclasses.py::test_hashable_optional[default2]", "tests/test_dataclasses.py::test_override_builtin_dataclass", "tests/test_dataclasses.py::test_override_builtin_dataclass_2", "tests/test_dataclasses.py::test_override_builtin_dataclass_nested", "tests/test_dataclasses.py::test_override_builtin_dataclass_nested_schema", "tests/test_dataclasses.py::test_inherit_builtin_dataclass", "tests/test_dataclasses.py::test_dataclass_arbitrary", "tests/test_dataclasses.py::test_forward_stdlib_dataclass_params", "tests/test_dataclasses.py::test_pydantic_callable_field", "tests/test_dataclasses.py::test_pickle_overriden_builtin_dataclass", "tests/test_dataclasses.py::test_config_field_info_create_model", "tests/test_dataclasses.py::test_issue_2162[foo0-bar0]", "tests/test_dataclasses.py::test_issue_2162[foo1-bar1]", "tests/test_dataclasses.py::test_issue_2162[foo2-bar2]", "tests/test_dataclasses.py::test_issue_2162[foo3-bar3]", "tests/test_dataclasses.py::test_issue_2383", "tests/test_dataclasses.py::test_issue_2398", "tests/test_dataclasses.py::test_issue_2424", "tests/test_dataclasses.py::test_issue_2541", "tests/test_dataclasses.py::test_issue_2555", "tests/test_dataclasses.py::test_issue_2594", "tests/test_dataclasses.py::test_schema_description_unset", "tests/test_dataclasses.py::test_schema_description_set", "tests/test_dataclasses.py::test_issue_3011", "tests/test_dataclasses.py::test_issue_3162", "tests/test_dataclasses.py::test_discriminated_union_basemodel_instance_value", "tests/test_dataclasses.py::test_post_init_after_validation", "tests/test_dataclasses.py::test_keeps_custom_properties", "tests/test_dataclasses.py::test_ignore_extra", "tests/test_dataclasses.py::test_ignore_extra_subclass", "tests/test_dataclasses.py::test_allow_extra", "tests/test_dataclasses.py::test_allow_extra_subclass", "tests/test_dataclasses.py::test_forbid_extra", "tests/test_dataclasses.py::test_post_init_allow_extra", "tests/test_dataclasses.py::test_self_reference_dataclass", "tests/test_dataclasses.py::test_extra_forbid_list_no_error", "tests/test_dataclasses.py::test_extra_forbid_list_error", "tests/test_dataclasses.py::test_parent_post_init", "tests/test_dataclasses.py::test_subclass_post_init_post_parse", "tests/test_dataclasses.py::test_subclass_post_init", "tests/test_dataclasses.py::test_subclass_post_init_inheritance", "tests/test_dataclasses.py::test_inheritance_post_init_2", "tests/test_dataclasses.py::test_dataclass_setattr", "tests/test_dataclasses.py::test_frozen_dataclasses", "tests/test_dataclasses.py::test_empty_dataclass", "tests/test_dataclasses.py::test_proxy_dataclass", "tests/test_dataclasses.py::test_proxy_dataclass_2" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2023-01-18 08:54:53+00:00
mit
4,886
pydantic__pydantic-5052
diff --git a/pydantic/generics.py b/pydantic/generics.py --- a/pydantic/generics.py +++ b/pydantic/generics.py @@ -17,6 +17,7 @@ Union, cast, ) +from weakref import WeakKeyDictionary, WeakValueDictionary from typing_extensions import Annotated @@ -25,7 +26,7 @@ from .main import BaseModel, create_model from .types import JsonWrapper from .typing import display_as_type, get_all_type_hints, get_args, get_origin, typing_base -from .utils import LimitedDict, all_identical, lenient_issubclass +from .utils import all_identical, lenient_issubclass if sys.version_info >= (3, 10): from typing import _UnionGenericAlias @@ -33,15 +34,28 @@ GenericModelT = TypeVar('GenericModelT', bound='GenericModel') TypeVarType = Any # since mypy doesn't allow the use of TypeVar as a type +CacheKey = Tuple[Type[Any], Any, Tuple[Any, ...]] Parametrization = Mapping[TypeVarType, Type[Any]] -_generic_types_cache: LimitedDict[Tuple[Type[Any], Union[Any, Tuple[Any, ...]]], Type[BaseModel]] = LimitedDict() +# weak dictionaries allow the dynamically created parametrized versions of generic models to get collected +# once they are no longer referenced by the caller. +if sys.version_info >= (3, 9): # Typing for weak dictionaries available at 3.9 + GenericTypesCache = WeakValueDictionary[CacheKey, Type[BaseModel]] + AssignedParameters = WeakKeyDictionary[Type[BaseModel], Parametrization] +else: + GenericTypesCache = WeakValueDictionary + AssignedParameters = WeakKeyDictionary + +# _generic_types_cache is a Mapping from __class_getitem__ arguments to the parametrized version of generic models. +# This ensures multiple calls of e.g. A[B] return always the same class. +_generic_types_cache = GenericTypesCache() + # _assigned_parameters is a Mapping from parametrized version of generic models to assigned types of parametrizations # as captured during construction of the class (not instances). # E.g., for generic model `Model[A, B]`, when parametrized model `Model[int, str]` is created, # `Model[int, str]`: {A: int, B: str}` will be stored in `_assigned_parameters`. # (This information is only otherwise available after creation from the class name string). -_assigned_parameters: LimitedDict[Type[Any], Parametrization] = LimitedDict() +_assigned_parameters = AssignedParameters() class GenericModel(BaseModel): @@ -67,7 +81,7 @@ def __class_getitem__(cls: Type[GenericModelT], params: Union[Type[Any], Tuple[T """ - def _cache_key(_params: Any) -> Tuple[Type[GenericModelT], Any, Tuple[Any, ...]]: + def _cache_key(_params: Any) -> CacheKey: args = get_args(_params) # python returns a list for Callables, which is not hashable if len(args) == 2 and isinstance(args[0], list): diff --git a/pydantic/utils.py b/pydantic/utils.py --- a/pydantic/utils.py +++ b/pydantic/utils.py @@ -17,7 +17,6 @@ Iterator, List, Mapping, - MutableMapping, NoReturn, Optional, Set, @@ -80,7 +79,6 @@ 'get_unique_discriminator_alias', 'get_discriminator_alias_and_values', 'DUNDER_ATTRIBUTES', - 'LimitedDict', ) ROOT_KEY = '__root__' @@ -803,39 +801,3 @@ def _get_union_alias_and_all_values( # unzip: [('alias_a',('v1', 'v2)), ('alias_b', ('v3',))] => [('alias_a', 'alias_b'), (('v1', 'v2'), ('v3',))] all_aliases, all_values = zip(*zipped_aliases_values) return get_unique_discriminator_alias(all_aliases, discriminator_key), all_values - - -KT = TypeVar('KT') -VT = TypeVar('VT') -if TYPE_CHECKING: - # Annoying inheriting from `MutableMapping` and `dict` breaks cython, hence this work around - class LimitedDict(dict, MutableMapping[KT, VT]): # type: ignore[type-arg] - def __init__(self, size_limit: int = 1000): - ... - -else: - - class LimitedDict(dict): - """ - Limit the size/length of a dict used for caching to avoid unlimited increase in memory usage. - - Since the dict is ordered, and we always remove elements from the beginning, this is effectively a FIFO cache. - - Annoying inheriting from `MutableMapping` breaks cython. - """ - - def __init__(self, size_limit: int = 1000): - self.size_limit = size_limit - super().__init__() - - def __setitem__(self, __key: Any, __value: Any) -> None: - super().__setitem__(__key, __value) - if len(self) > self.size_limit: - excess = len(self) - self.size_limit + self.size_limit // 10 - to_remove = list(self.keys())[:excess] - for key in to_remove: - del self[key] - - def __class_getitem__(cls, *args: Any) -> Any: - # to avoid errors with 3.7 - pass
pydantic/pydantic
ce45f6ebcb60abf54646376ec8bad0dc17df43bc
I was not able to create a short example for reproducibility, but I managed to identify the changes that "broke" our testsuite: #4083 If I revert both changes to [pydantic/generics.py](https://github.com/samuelcolvin/pydantic/blob/master/pydantic/generics.py), the errors in our testsuite disappear. That might explain, why it's not easy to create a simple snippet for reproducibility, right? One needs to manage to exceed the limit... Sorry for slow reply, yes makes sense. I don't want to change the limits, but we should fail in a more transparent way. I also added some debug messages in `pydantic/generics.py` to better understand what's happening. I noticed for my case, that the caches `_generic_types_cache` and `_assigned_parameters` grow with each unittest, when the FastAPI app is re-created (in a fixture explicitly via `create_model`). It looks to me, like the retrieval from these caches is broken for dynamic models and/or `TypeVar`s: The testsuite fixture defines a limited number of distinct models (including static and dynamic ones, in total **23**), but whenever the application is rebuilt for the next test case, the models get rebuilt and added to the cache as the keys do not match. To be exact, `_generic_types_cache` very quickly grows to the specific limit, whereas `_assigned_parameters` goes up only to about 600. To the best of my knowledge, this _cache problem_ (maybe the reason for the leak mentioned in #3829?) was also true for v1.9.0, but for some reasonit did not cause a `KeyError`. > I don't want to change the limits Yes, if my understanding of the observed problem is correct, changing the limit makes no difference. > we should fail in a more transparent way. Given the specific error I observed, I'm wondering if it would make more sense to allow a _margin of error_ when comparing two different `TypeVars` that have the same name? But that would probably only count as a workaround. Maybe I should raise an issue with the developers of fastapi_pagination to not use `TypeVar`s or raise an issue with the developers of Python so that the comparison of `TypeVar`s changes: ``` >>> import typing >>> t = typing.TypeVar("T") >>> s = typing.TypeVar("T") >>> t == s False >>> t is s False ```
diff --git a/tests/requirements-testing.txt b/tests/requirements-testing.txt --- a/tests/requirements-testing.txt +++ b/tests/requirements-testing.txt @@ -3,9 +3,9 @@ hypothesis==6.54.4 # pin importlib-metadata as upper versions need typing-extensions to work if on Python < 3.8 importlib-metadata==3.1.0;python_version<"3.8" mypy==0.971 -pytest==7.1.2 -pytest-cov==3.0.0 -pytest-mock==3.8.2 -pytest-sugar==0.9.5 +pytest==7.2.1 +pytest-cov==4.0.0 +pytest-mock==3.10.0 +pytest-sugar==0.9.6 # pin typing-extensions to minimum requirement - see #4885 typing-extensions==4.2.0 diff --git a/tests/test_edge_cases.py b/tests/test_edge_cases.py --- a/tests/test_edge_cases.py +++ b/tests/test_edge_cases.py @@ -1894,7 +1894,7 @@ def get_double_a(self) -> float: model = Model(a=10.2) assert model.a == 10.2 assert model.b == 10 - return model.get_double_a() == 20.2 + assert model.get_double_a() == 20.2 def test_resolve_annotations_module_missing(tmp_path): diff --git a/tests/test_generics.py b/tests/test_generics.py --- a/tests/test_generics.py +++ b/tests/test_generics.py @@ -1,3 +1,5 @@ +import gc +import itertools import json import sys from enum import Enum @@ -6,12 +8,14 @@ Callable, ClassVar, Dict, + FrozenSet, Generic, Iterable, List, Mapping, Optional, Sequence, + Set, Tuple, Type, TypeVar, @@ -21,8 +25,19 @@ import pytest from typing_extensions import Annotated, Literal -from pydantic import BaseModel, Field, Json, ValidationError, root_validator, validator -from pydantic.generics import GenericModel, _generic_types_cache, iter_contained_typevars, replace_types +from pydantic import BaseModel, Field, Json, ValidationError, create_model, root_validator, validator +from pydantic.generics import ( + GenericModel, + _assigned_parameters, + _generic_types_cache, + iter_contained_typevars, + replace_types, +) + + [email protected](autouse=True) +def clean_cache(): + gc.collect() # cleans up _generic_types_cache for checking item counts in the cache def test_generic_name(): @@ -229,10 +244,13 @@ def test_cover_cache(): class Model(GenericModel, Generic[T]): x: T - Model[int] # adds both with-tuple and without-tuple version to cache + models = [] # keep references to models to get cache size + + models.append(Model[int]) # adds both with-tuple and without-tuple version to cache assert len(_generic_types_cache) == cache_size + 2 - Model[int] # uses the cache + models.append(Model[int]) # uses the cache assert len(_generic_types_cache) == cache_size + 2 + del models def test_cache_keys_are_hashable(): @@ -246,19 +264,66 @@ class MyGenericModel(GenericModel, Generic[T]): # Callable's first params get converted to a list, which is not hashable. # Make sure we can handle that special case Simple = MyGenericModel[Callable[[int], str]] + models = [] # keep references to models to get cache size + models.append(Simple) assert len(_generic_types_cache) == cache_size + 2 # Nested Callables - MyGenericModel[Callable[[C], Iterable[str]]] + models.append(MyGenericModel[Callable[[C], Iterable[str]]]) assert len(_generic_types_cache) == cache_size + 4 - MyGenericModel[Callable[[Simple], Iterable[int]]] + models.append(MyGenericModel[Callable[[Simple], Iterable[int]]]) assert len(_generic_types_cache) == cache_size + 6 - MyGenericModel[Callable[[MyGenericModel[C]], Iterable[int]]] + models.append(MyGenericModel[Callable[[MyGenericModel[C]], Iterable[int]]]) assert len(_generic_types_cache) == cache_size + 10 class Model(BaseModel): x: MyGenericModel[Callable[[C], Iterable[str]]] = Field(...) + models.append(Model) assert len(_generic_types_cache) == cache_size + 10 + del models + + +def test_caches_get_cleaned_up(): + types_cache_size = len(_generic_types_cache) + params_cache_size = len(_assigned_parameters) + T = TypeVar('T') + + class MyGenericModel(GenericModel, Generic[T]): + x: T + + Model = MyGenericModel[int] + assert len(_generic_types_cache) == types_cache_size + 2 + assert len(_assigned_parameters) == params_cache_size + 1 + del Model + gc.collect() + assert len(_generic_types_cache) == types_cache_size + assert len(_assigned_parameters) == params_cache_size + + +def test_generics_work_with_many_parametrized_base_models(): + cache_size = len(_generic_types_cache) + params_size = len(_assigned_parameters) + count_create_models = 1000 + T = TypeVar('T') + C = TypeVar('C') + + class A(GenericModel, Generic[T, C]): + x: T + y: C + + class B(A[int, C], GenericModel, Generic[C]): + pass + + models = [create_model(f'M{i}') for i in range(count_create_models)] + generics = [] + for m in models: + Working = B[m] + generics.append(Working) + + assert len(_generic_types_cache) == cache_size + count_create_models * 5 + 1 + assert len(_assigned_parameters) == params_size + count_create_models * 3 + 1 + del models + del generics def test_generic_config(): @@ -1379,3 +1444,57 @@ class Payload(BaseModel): 'properties': {'payload_field': {'title': 'Payload Field', 'type': 'string'}}, 'required': ['payload_field'], } + + +def memray_limit_memory(limit): + if '--memray' in sys.argv: + return pytest.mark.limit_memory(limit) + else: + return pytest.mark.skip(reason='memray not enabled') + + +@memray_limit_memory('100 MB') +def test_generics_memory_use(): + """See: + - https://github.com/pydantic/pydantic/issues/3829 + - https://github.com/pydantic/pydantic/pull/4083 + - https://github.com/pydantic/pydantic/pull/5052 + """ + + T = TypeVar('T') + U = TypeVar('U') + V = TypeVar('V') + + class MyModel(GenericModel, Generic[T, U, V]): + message: Json[T] + field: Dict[U, V] + + class Outer(GenericModel, Generic[T]): + inner: T + + types = [ + int, + str, + float, + bool, + bytes, + ] + + containers = [ + List, + Tuple, + Set, + FrozenSet, + ] + + all = [*types, *[container[tp] for container in containers for tp in types]] + + total = list(itertools.product(all, all, all)) + + for t1, t2, t3 in total: + + class Foo(MyModel[t1, t2, t3]): + pass + + class _(Outer[Foo]): + pass diff --git a/tests/test_utils.py b/tests/test_utils.py --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -27,7 +27,6 @@ from pydantic.utils import ( BUILTIN_COLLECTIONS, ClassAttribute, - LimitedDict, ValueItems, all_identical, deep_update, @@ -549,43 +548,3 @@ def test_on_lower_camel_one_length(): def test_on_lower_camel_many_length(): assert to_lower_camel('i_like_turtles') == 'iLikeTurtles' - - -def test_limited_dict(): - d = LimitedDict(10) - d[1] = '1' - d[2] = '2' - assert list(d.items()) == [(1, '1'), (2, '2')] - for no in '34567890': - d[int(no)] = no - assert list(d.items()) == [ - (1, '1'), - (2, '2'), - (3, '3'), - (4, '4'), - (5, '5'), - (6, '6'), - (7, '7'), - (8, '8'), - (9, '9'), - (0, '0'), - ] - d[11] = '11' - - # reduce size to 9 after setting 11 - assert len(d) == 9 - assert list(d.items()) == [ - (3, '3'), - (4, '4'), - (5, '5'), - (6, '6'), - (7, '7'), - (8, '8'), - (9, '9'), - (0, '0'), - (11, '11'), - ] - d[12] = '12' - assert len(d) == 10 - d[13] = '13' - assert len(d) == 9
`KeyError` in GenericModel.__parameterized_bases__.build_base_model # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.9.1 pydantic compiled: True install path: /home/andi/virtualenvs/aimaas/lib/python3.9/site-packages/pydantic python version: 3.9.12 (main, Apr 18 2022, 22:40:46) [GCC 9.4.0] platform: Linux-5.4.0-113-generic-x86_64-with-glibc2.31 optional deps. installed: ['dotenv', 'typing-extensions'] ``` I'm afraid reproduction of this _issue_ is a bit tricky as I was not able to reproduce it in a production scenario nor with a small code snippet. So far, I only noticed this in the test suite of this [project](https://github.com/SUSE/aimaas), which contains multiple sub-modules for tests; but only tests in two **can** fail, i.e. when the entire testsuite runs, they fail; if I explicitly only run tests from these modules, they pass. This behavior probably also indicates a problem within the testsuite, which I intend to look for, but the problem does not occur with version 1.9.0 of pydantic. So, I figured it's worth sharing. In the project, we dynamically define API routes for FastAPI for dynamically generated models (i.e. model definitions are stored in DB), i.e. the models and routes get generated/updated at start-up or when something changes in the DB. The callback function used for this looks something like this: ```python def route_get_entities(router: APIRouter, schema: Schema): # this is the callback factory = EntityModelFactory() filter_model = _filters_request_model(schema=schema) @router.get( f'/{schema.slug}', response_model=Page[factory(schema=schema, variant=ModelVariant.GET)], response_model_exclude_unset=True ) def get_entities( filters: filter_model = Depends(), order_by: str = Query('name', description=''), ascending: bool = Query(True, description=''), db: Session = Depends(get_db), params: Params = Depends() ): # the actual API route ... ``` The exception raised in the testsuite looks like this: ``` _____________________________________ ERROR at setup of TestRouteGetEntityChanges.test_raise_on_change_doesnt_exist ______________________________________ dbsession = <sqlalchemy.orm.session.Session object at 0x7fca28575580> @pytest.fixture def client(dbsession): > app = create_app(session=dbsession) backend/tests/conftest.py:338: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ backend/__init__.py:53: in create_app load_dynamic_routes(db=session, app=app) backend/__init__.py:40: in load_dynamic_routes create_dynamic_router(schema=schema, app=app) backend/dynamic_routes.py:341: in create_dynamic_router route_get_entities(router=router, schema=schema) backend/dynamic_routes.py:124: in route_get_entities response_model=Page[factory(schema=schema, variant=ModelVariant.GET)], ../../virtualenvs/aimaas/lib/python3.9/site-packages/pydantic/generics.py:98: in __class_getitem__ __base__=(cls,) + tuple(cls.__parameterized_bases__(typevars_map)), ../../virtualenvs/aimaas/lib/python3.9/site-packages/pydantic/generics.py:224: in __parameterized_bases__ yield from build_base_model(base_model, typevars_map) ../../virtualenvs/aimaas/lib/python3.9/site-packages/pydantic/generics.py:190: in build_base_model parameterized_base = base_model.__class_getitem__(base_parameters) ../../virtualenvs/aimaas/lib/python3.9/site-packages/pydantic/generics.py:98: in __class_getitem__ __base__=(cls,) + tuple(cls.__parameterized_bases__(typevars_map)), ../../virtualenvs/aimaas/lib/python3.9/site-packages/pydantic/generics.py:224: in __parameterized_bases__ yield from build_base_model(base_model, typevars_map) ../../virtualenvs/aimaas/lib/python3.9/site-packages/pydantic/generics.py:185: in build_base_model base_parameters = tuple([mapped_types[param] for param in base_model.__parameters__]) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ .0 = <tuple_iterator object at 0x7fca2344e370> > base_parameters = tuple([mapped_types[param] for param in base_model.__parameters__]) E KeyError: ~T ../../virtualenvs/aimaas/lib/python3.9/site-packages/pydantic/generics.py:185: KeyError ``` I checked the contents of `mapped_types` and `base_model.__parameters__` in the line where the exception gets raised: ``` >>> mapped_types {~T: <class 'pydantic.main.PersonGet'>} >>> a = list(mapped_types.keys())[0] >>> a ~T >>> b = base_model.__parameters__ >>> b[0] ~T >>> a is b[0] False >>> type(a) <class 'typing.TypeVar'> >>> type(b[0]) <class 'typing.TypeVar'> ``` It looks like the `TypeVar`s, which are expected to be identical, no longer are. :thinking:
0.0
ce45f6ebcb60abf54646376ec8bad0dc17df43bc
[ "tests/test_generics.py::test_caches_get_cleaned_up", "tests/test_generics.py::test_generics_work_with_many_parametrized_base_models" ]
[ "tests/test_edge_cases.py::test_str_bytes", "tests/test_edge_cases.py::test_str_bytes_none", "tests/test_edge_cases.py::test_union_int_str", "tests/test_edge_cases.py::test_union_int_any", "tests/test_edge_cases.py::test_union_priority", "tests/test_edge_cases.py::test_typed_list", "tests/test_edge_cases.py::test_typed_set", "tests/test_edge_cases.py::test_dict_dict", "tests/test_edge_cases.py::test_none_list", "tests/test_edge_cases.py::test_typed_dict[value0-result0]", "tests/test_edge_cases.py::test_typed_dict[value1-result1]", "tests/test_edge_cases.py::test_typed_dict[value2-result2]", "tests/test_edge_cases.py::test_typed_dict_error[1-errors0]", "tests/test_edge_cases.py::test_typed_dict_error[value1-errors1]", "tests/test_edge_cases.py::test_typed_dict_error[value2-errors2]", "tests/test_edge_cases.py::test_dict_key_error", "tests/test_edge_cases.py::test_tuple", "tests/test_edge_cases.py::test_tuple_more", "tests/test_edge_cases.py::test_tuple_length_error", "tests/test_edge_cases.py::test_tuple_invalid", "tests/test_edge_cases.py::test_tuple_value_error", "tests/test_edge_cases.py::test_recursive_list", "tests/test_edge_cases.py::test_recursive_list_error", "tests/test_edge_cases.py::test_list_unions", "tests/test_edge_cases.py::test_recursive_lists", "tests/test_edge_cases.py::test_str_enum", "tests/test_edge_cases.py::test_any_dict", "tests/test_edge_cases.py::test_success_values_include", "tests/test_edge_cases.py::test_include_exclude_unset", "tests/test_edge_cases.py::test_include_exclude_defaults", "tests/test_edge_cases.py::test_skip_defaults_deprecated", "tests/test_edge_cases.py::test_advanced_exclude", "tests/test_edge_cases.py::test_advanced_exclude_by_alias", "tests/test_edge_cases.py::test_advanced_value_include", "tests/test_edge_cases.py::test_advanced_value_exclude_include", "tests/test_edge_cases.py::test_advanced_exclude_nested_lists[exclude0-expected0]", "tests/test_edge_cases.py::test_advanced_exclude_nested_lists[exclude1-expected1]", "tests/test_edge_cases.py::test_advanced_exclude_nested_lists[exclude2-expected2]", "tests/test_edge_cases.py::test_advanced_exclude_nested_lists[exclude3-expected3]", "tests/test_edge_cases.py::test_advanced_exclude_nested_lists[exclude4-expected4]", "tests/test_edge_cases.py::test_advanced_exclude_nested_lists[exclude5-expected5]", "tests/test_edge_cases.py::test_advanced_exclude_nested_lists[exclude6-expected6]", "tests/test_edge_cases.py::test_advanced_exclude_nested_lists[exclude7-expected7]", "tests/test_edge_cases.py::test_advanced_exclude_nested_lists[exclude8-expected8]", "tests/test_edge_cases.py::test_advanced_exclude_nested_lists[exclude9-expected9]", "tests/test_edge_cases.py::test_advanced_exclude_nested_lists[exclude10-expected10]", "tests/test_edge_cases.py::test_advanced_exclude_nested_lists[exclude11-expected11]", "tests/test_edge_cases.py::test_advanced_exclude_nested_lists[exclude12-expected12]", "tests/test_edge_cases.py::test_advanced_exclude_nested_lists[exclude13-expected13]", "tests/test_edge_cases.py::test_advanced_exclude_nested_lists[exclude14-expected14]", "tests/test_edge_cases.py::test_advanced_include_nested_lists[include0-expected0]", "tests/test_edge_cases.py::test_advanced_include_nested_lists[include1-expected1]", "tests/test_edge_cases.py::test_advanced_include_nested_lists[include2-expected2]", "tests/test_edge_cases.py::test_advanced_include_nested_lists[include3-expected3]", "tests/test_edge_cases.py::test_advanced_include_nested_lists[include4-expected4]", "tests/test_edge_cases.py::test_advanced_include_nested_lists[include5-expected5]", "tests/test_edge_cases.py::test_advanced_include_nested_lists[include6-expected6]", "tests/test_edge_cases.py::test_advanced_include_nested_lists[include7-expected7]", "tests/test_edge_cases.py::test_advanced_include_nested_lists[include8-expected8]", "tests/test_edge_cases.py::test_advanced_include_nested_lists[include9-expected9]", "tests/test_edge_cases.py::test_advanced_include_nested_lists[include10-expected10]", "tests/test_edge_cases.py::test_advanced_include_nested_lists[include11-expected11]", "tests/test_edge_cases.py::test_advanced_include_nested_lists[include12-expected12]", "tests/test_edge_cases.py::test_advanced_include_nested_lists[include13-expected13]", "tests/test_edge_cases.py::test_advanced_include_nested_lists[include14-expected14]", "tests/test_edge_cases.py::test_field_set_ignore_extra", "tests/test_edge_cases.py::test_field_set_allow_extra", "tests/test_edge_cases.py::test_field_set_field_name", "tests/test_edge_cases.py::test_values_order", "tests/test_edge_cases.py::test_inheritance", "tests/test_edge_cases.py::test_inheritance_subclass_default", "tests/test_edge_cases.py::test_invalid_type", "tests/test_edge_cases.py::test_valid_string_types[a", "tests/test_edge_cases.py::test_valid_string_types[some", "tests/test_edge_cases.py::test_valid_string_types[value2-foobar]", "tests/test_edge_cases.py::test_valid_string_types[123-123]", "tests/test_edge_cases.py::test_valid_string_types[123.45-123.45]", "tests/test_edge_cases.py::test_valid_string_types[value5-12.45]", "tests/test_edge_cases.py::test_valid_string_types[True-True]", "tests/test_edge_cases.py::test_valid_string_types[False-False]", "tests/test_edge_cases.py::test_valid_string_types[a10-a10]", "tests/test_edge_cases.py::test_valid_string_types[whatever-whatever]", "tests/test_edge_cases.py::test_invalid_string_types[value0-errors0]", "tests/test_edge_cases.py::test_invalid_string_types[value1-errors1]", "tests/test_edge_cases.py::test_inheritance_config", "tests/test_edge_cases.py::test_partial_inheritance_config", "tests/test_edge_cases.py::test_annotation_inheritance", "tests/test_edge_cases.py::test_string_none", "tests/test_edge_cases.py::test_return_errors_ok", "tests/test_edge_cases.py::test_return_errors_error", "tests/test_edge_cases.py::test_optional_required", "tests/test_edge_cases.py::test_invalid_validator", "tests/test_edge_cases.py::test_unable_to_infer", "tests/test_edge_cases.py::test_multiple_errors", "tests/test_edge_cases.py::test_validate_all", "tests/test_edge_cases.py::test_force_extra", "tests/test_edge_cases.py::test_illegal_extra_value", "tests/test_edge_cases.py::test_multiple_inheritance_config", "tests/test_edge_cases.py::test_submodel_different_type", "tests/test_edge_cases.py::test_self", "tests/test_edge_cases.py::test_self_recursive[BaseModel]", "tests/test_edge_cases.py::test_self_recursive[BaseSettings]", "tests/test_edge_cases.py::test_nested_init[BaseModel]", "tests/test_edge_cases.py::test_nested_init[BaseSettings]", "tests/test_edge_cases.py::test_init_inspection", "tests/test_edge_cases.py::test_type_on_annotation", "tests/test_edge_cases.py::test_assign_type", "tests/test_edge_cases.py::test_optional_subfields", "tests/test_edge_cases.py::test_not_optional_subfields", "tests/test_edge_cases.py::test_optional_field_constraints", "tests/test_edge_cases.py::test_field_str_shape", "tests/test_edge_cases.py::test_field_type_display[int-int]", "tests/test_edge_cases.py::test_field_type_display[type_1-Optional[int]]", "tests/test_edge_cases.py::test_field_type_display[type_2-Union[NoneType,", "tests/test_edge_cases.py::test_field_type_display[type_3-Union[int,", "tests/test_edge_cases.py::test_field_type_display[type_4-List[int]]", "tests/test_edge_cases.py::test_field_type_display[type_5-Tuple[int,", "tests/test_edge_cases.py::test_field_type_display[type_6-Union[List[int],", "tests/test_edge_cases.py::test_field_type_display[type_7-List[Tuple[int,", "tests/test_edge_cases.py::test_field_type_display[type_8-Mapping[int,", "tests/test_edge_cases.py::test_field_type_display[type_9-FrozenSet[int]]", "tests/test_edge_cases.py::test_field_type_display[type_10-Tuple[int,", "tests/test_edge_cases.py::test_field_type_display[type_11-Optional[List[int]]]", "tests/test_edge_cases.py::test_field_type_display[dict-dict]", "tests/test_edge_cases.py::test_field_type_display[type_13-DisplayGen[bool,", "tests/test_edge_cases.py::test_any_none", "tests/test_edge_cases.py::test_type_var_any", "tests/test_edge_cases.py::test_type_var_constraint", "tests/test_edge_cases.py::test_type_var_bound", "tests/test_edge_cases.py::test_dict_bare", "tests/test_edge_cases.py::test_list_bare", "tests/test_edge_cases.py::test_dict_any", "tests/test_edge_cases.py::test_modify_fields", "tests/test_edge_cases.py::test_exclude_none", "tests/test_edge_cases.py::test_exclude_none_recursive", "tests/test_edge_cases.py::test_exclude_none_with_extra", "tests/test_edge_cases.py::test_str_method_inheritance", "tests/test_edge_cases.py::test_repr_method_inheritance", "tests/test_edge_cases.py::test_optional_validator", "tests/test_edge_cases.py::test_required_optional", "tests/test_edge_cases.py::test_required_any", "tests/test_edge_cases.py::test_custom_generic_validators", "tests/test_edge_cases.py::test_custom_generic_arbitrary_allowed", "tests/test_edge_cases.py::test_custom_generic_disallowed", "tests/test_edge_cases.py::test_hashable_required", "tests/test_edge_cases.py::test_hashable_optional[1]", "tests/test_edge_cases.py::test_hashable_optional[None]", "tests/test_edge_cases.py::test_default_factory_called_once", "tests/test_edge_cases.py::test_default_factory_validator_child", "tests/test_edge_cases.py::test_cython_function_untouched", "tests/test_edge_cases.py::test_resolve_annotations_module_missing", "tests/test_edge_cases.py::test_iter_coverage", "tests/test_edge_cases.py::test_config_field_info", "tests/test_edge_cases.py::test_config_field_info_alias", "tests/test_edge_cases.py::test_config_field_info_merge", "tests/test_edge_cases.py::test_config_field_info_allow_mutation", "tests/test_edge_cases.py::test_arbitrary_types_allowed_custom_eq", "tests/test_edge_cases.py::test_bytes_subclass", "tests/test_edge_cases.py::test_int_subclass", "tests/test_edge_cases.py::test_model_issubclass", "tests/test_edge_cases.py::test_long_int", "tests/test_generics.py::test_generic_name", "tests/test_generics.py::test_double_parameterize_error", "tests/test_generics.py::test_value_validation", "tests/test_generics.py::test_methods_are_inherited", "tests/test_generics.py::test_config_is_inherited", "tests/test_generics.py::test_default_argument", "tests/test_generics.py::test_default_argument_for_typevar", "tests/test_generics.py::test_classvar", "tests/test_generics.py::test_non_annotated_field", "tests/test_generics.py::test_must_inherit_from_generic", "tests/test_generics.py::test_parameters_placed_on_generic", "tests/test_generics.py::test_parameters_must_be_typevar", "tests/test_generics.py::test_subclass_can_be_genericized", "tests/test_generics.py::test_parameter_count", "tests/test_generics.py::test_cover_cache", "tests/test_generics.py::test_cache_keys_are_hashable", "tests/test_generics.py::test_generic_config", "tests/test_generics.py::test_enum_generic", "tests/test_generics.py::test_generic", "tests/test_generics.py::test_alongside_concrete_generics", "tests/test_generics.py::test_complex_nesting", "tests/test_generics.py::test_required_value", "tests/test_generics.py::test_optional_value", "tests/test_generics.py::test_custom_schema", "tests/test_generics.py::test_child_schema", "tests/test_generics.py::test_custom_generic_naming", "tests/test_generics.py::test_nested", "tests/test_generics.py::test_partial_specification", "tests/test_generics.py::test_partial_specification_with_inner_typevar", "tests/test_generics.py::test_partial_specification_name", "tests/test_generics.py::test_partial_specification_instantiation", "tests/test_generics.py::test_partial_specification_instantiation_bounded", "tests/test_generics.py::test_typevar_parametrization", "tests/test_generics.py::test_multiple_specification", "tests/test_generics.py::test_generic_subclass_of_concrete_generic", "tests/test_generics.py::test_generic_model_pickle", "tests/test_generics.py::test_generic_model_from_function_pickle_fail", "tests/test_generics.py::test_generic_model_redefined_without_cache_fail", "tests/test_generics.py::test_generic_model_caching_detect_order_of_union_args_basic", "tests/test_generics.py::test_get_caller_frame_info", "tests/test_generics.py::test_get_caller_frame_info_called_from_module", "tests/test_generics.py::test_get_caller_frame_info_when_sys_getframe_undefined", "tests/test_generics.py::test_iter_contained_typevars", "tests/test_generics.py::test_nested_identity_parameterization", "tests/test_generics.py::test_replace_types", "tests/test_generics.py::test_replace_types_with_user_defined_generic_type_field", "tests/test_generics.py::test_replace_types_identity_on_unchanged", "tests/test_generics.py::test_deep_generic", "tests/test_generics.py::test_deep_generic_with_inner_typevar", "tests/test_generics.py::test_deep_generic_with_referenced_generic", "tests/test_generics.py::test_deep_generic_with_referenced_inner_generic", "tests/test_generics.py::test_deep_generic_with_multiple_typevars", "tests/test_generics.py::test_deep_generic_with_multiple_inheritance", "tests/test_generics.py::test_generic_with_referenced_generic_type_1", "tests/test_generics.py::test_generic_with_referenced_nested_typevar", "tests/test_generics.py::test_generic_with_callable", "tests/test_generics.py::test_generic_with_partial_callable", "tests/test_generics.py::test_generic_recursive_models", "tests/test_generics.py::test_generic_enum", "tests/test_generics.py::test_generic_literal", "tests/test_generics.py::test_generic_enums", "tests/test_generics.py::test_generic_with_user_defined_generic_field", "tests/test_generics.py::test_generic_annotated", "tests/test_generics.py::test_generic_subclass", "tests/test_generics.py::test_generic_subclass_with_partial_application", "tests/test_generics.py::test_multilevel_generic_binding", "tests/test_generics.py::test_generic_subclass_with_extra_type", "tests/test_generics.py::test_multi_inheritance_generic_binding", "tests/test_generics.py::test_parse_generic_json", "tests/test_utils.py::test_import_module", "tests/test_utils.py::test_import_module_invalid", "tests/test_utils.py::test_import_no_attr", "tests/test_utils.py::test_display_as_type[str-str]", "tests/test_utils.py::test_display_as_type[string-str]", "tests/test_utils.py::test_display_as_type[value2-Union[str,", "tests/test_utils.py::test_display_as_type[list-list]", "tests/test_utils.py::test_lenient_issubclass", "tests/test_utils.py::test_lenient_issubclass_is_lenient", "tests/test_utils.py::test_truncate[object-<class", "tests/test_utils.py::test_truncate[abcdefghijklmnopqrstuvwxyz-'abcdefghijklmnopq\\u2026']", "tests/test_utils.py::test_truncate[input_value2-[0,", "tests/test_utils.py::test_unique_list[input_value0-output0]", "tests/test_utils.py::test_unique_list[input_value1-output1]", "tests/test_utils.py::test_unique_list[input_value2-output2]", "tests/test_utils.py::test_value_items", "tests/test_utils.py::test_value_items_merge[base0-override0-False-expected0]", "tests/test_utils.py::test_value_items_merge[None-None-False-None]", "tests/test_utils.py::test_value_items_merge[base2-override2-False-expected2]", "tests/test_utils.py::test_value_items_merge[base3-None-False-expected3]", "tests/test_utils.py::test_value_items_merge[None-override4-False-expected4]", "tests/test_utils.py::test_value_items_merge[None-override5-False-expected5]", "tests/test_utils.py::test_value_items_merge[base6-None-False-expected6]", "tests/test_utils.py::test_value_items_merge[base7-override7-False-expected7]", "tests/test_utils.py::test_value_items_merge[base8-override8-False-expected8]", "tests/test_utils.py::test_value_items_merge[base9-override9-False-expected9]", "tests/test_utils.py::test_value_items_merge[base10-override10-False-expected10]", "tests/test_utils.py::test_value_items_merge[base11-override11-False-expected11]", "tests/test_utils.py::test_value_items_merge[base12-override12-False-expected12]", "tests/test_utils.py::test_value_items_merge[base13-override13-False-expected13]", "tests/test_utils.py::test_value_items_merge[base14-override14-False-expected14]", "tests/test_utils.py::test_value_items_merge[base15-override15-False-expected15]", "tests/test_utils.py::test_value_items_merge[base16-override16-True-expected16]", "tests/test_utils.py::test_value_items_merge[None-None-True-None]", "tests/test_utils.py::test_value_items_merge[base18-override18-True-expected18]", "tests/test_utils.py::test_value_items_merge[base19-None-True-expected19]", "tests/test_utils.py::test_value_items_merge[None-override20-True-expected20]", "tests/test_utils.py::test_value_items_merge[None-override21-True-expected21]", "tests/test_utils.py::test_value_items_merge[base22-None-True-expected22]", "tests/test_utils.py::test_value_items_merge[base23-override23-True-expected23]", "tests/test_utils.py::test_value_items_merge[base24-override24-True-expected24]", "tests/test_utils.py::test_value_items_merge[base25-override25-True-expected25]", "tests/test_utils.py::test_value_items_merge[base26-override26-True-expected26]", "tests/test_utils.py::test_value_items_merge[base27-override27-True-expected27]", "tests/test_utils.py::test_value_items_merge[base28-override28-True-expected28]", "tests/test_utils.py::test_value_items_merge[base29-override29-True-expected29]", "tests/test_utils.py::test_value_items_merge[base30-override30-True-expected30]", "tests/test_utils.py::test_value_items_merge[base31-override31-True-expected31]", "tests/test_utils.py::test_value_items_merge[base32-True-False-True]", "tests/test_utils.py::test_value_items_merge[True-override33-False-expected33]", "tests/test_utils.py::test_value_items_merge[True-None-False-True]", "tests/test_utils.py::test_value_items_merge[base35-override35-False-expected35]", "tests/test_utils.py::test_value_items_error", "tests/test_utils.py::test_is_new_type", "tests/test_utils.py::test_new_type_supertype", "tests/test_utils.py::test_pretty", "tests/test_utils.py::test_pretty_color", "tests/test_utils.py::test_devtools_output", "tests/test_utils.py::test_devtools_output_validation_error", "tests/test_utils.py::test_deep_update[mapping0-updating_mapping0-expected_mapping0-extra", "tests/test_utils.py::test_deep_update[mapping1-updating_mapping1-expected_mapping1-values", "tests/test_utils.py::test_deep_update[mapping2-updating_mapping2-expected_mapping2-values", "tests/test_utils.py::test_deep_update[mapping3-updating_mapping3-expected_mapping3-deeply", "tests/test_utils.py::test_deep_update_is_not_mutating", "tests/test_utils.py::test_undefined_repr", "tests/test_utils.py::test_undefined_copy", "tests/test_utils.py::test_get_model", "tests/test_utils.py::test_version_info", "tests/test_utils.py::test_standard_version", "tests/test_utils.py::test_class_attribute", "tests/test_utils.py::test_all_literal_values", "tests/test_utils.py::test_path_type", "tests/test_utils.py::test_path_type_unknown", "tests/test_utils.py::test_smart_deepcopy_immutable_non_sequence[10]", "tests/test_utils.py::test_smart_deepcopy_immutable_non_sequence[1.0]", "tests/test_utils.py::test_smart_deepcopy_immutable_non_sequence[11]", "tests/test_utils.py::test_smart_deepcopy_immutable_non_sequence[12]", "tests/test_utils.py::test_smart_deepcopy_immutable_non_sequence[int]", "tests/test_utils.py::test_smart_deepcopy_immutable_non_sequence[None]", "tests/test_utils.py::test_smart_deepcopy_immutable_non_sequence[test_all_literal_values]", "tests/test_utils.py::test_smart_deepcopy_immutable_non_sequence[len]", "tests/test_utils.py::test_smart_deepcopy_immutable_non_sequence[obj8]", "tests/test_utils.py::test_smart_deepcopy_immutable_non_sequence[<lambda>]", "tests/test_utils.py::test_smart_deepcopy_immutable_non_sequence[obj10]", "tests/test_utils.py::test_smart_deepcopy_empty_collection[empty_collection0]", "tests/test_utils.py::test_smart_deepcopy_empty_collection[empty_collection1]", "tests/test_utils.py::test_smart_deepcopy_empty_collection[empty_collection2]", "tests/test_utils.py::test_smart_deepcopy_empty_collection[empty_collection3]", "tests/test_utils.py::test_smart_deepcopy_empty_collection[empty_collection4]", "tests/test_utils.py::test_smart_deepcopy_empty_collection[empty_collection5]", "tests/test_utils.py::test_smart_deepcopy_empty_collection[empty_collection6]", "tests/test_utils.py::test_smart_deepcopy_empty_collection[empty_collection7]", "tests/test_utils.py::test_smart_deepcopy_collection[collection0]", "tests/test_utils.py::test_smart_deepcopy_collection[collection1]", "tests/test_utils.py::test_smart_deepcopy_collection[collection2]", "tests/test_utils.py::test_smart_deepcopy_collection[collection3]", "tests/test_utils.py::test_smart_deepcopy_collection[collection4]", "tests/test_utils.py::test_smart_deepcopy_collection[collection5]", "tests/test_utils.py::test_smart_deepcopy_collection[collection6]", "tests/test_utils.py::test_smart_deepcopy_collection[collection7]", "tests/test_utils.py::test_smart_deepcopy_error[TypeError]", "tests/test_utils.py::test_smart_deepcopy_error[ValueError]", "tests/test_utils.py::test_smart_deepcopy_error[RuntimeError]", "tests/test_utils.py::test_get_origin[input_value0-Annotated]", "tests/test_utils.py::test_get_origin[input_value1-Callable]", "tests/test_utils.py::test_get_origin[input_value2-dict]", "tests/test_utils.py::test_get_origin[input_value3-list]", "tests/test_utils.py::test_get_origin[input_value4-output_value4]", "tests/test_utils.py::test_get_origin[int-None]", "tests/test_utils.py::test_resolve_annotations_no_module", "tests/test_utils.py::test_all_identical", "tests/test_utils.py::test_undefined_pickle", "tests/test_utils.py::test_on_lower_camel_zero_length", "tests/test_utils.py::test_on_lower_camel_one_length", "tests/test_utils.py::test_on_lower_camel_many_length" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-02-14 07:28:59+00:00
mit
4,887
pydantic__pydantic-5126
diff --git a/pydantic/class_validators.py b/pydantic/class_validators.py --- a/pydantic/class_validators.py +++ b/pydantic/class_validators.py @@ -1,6 +1,6 @@ import warnings from collections import ChainMap -from functools import wraps +from functools import partial, partialmethod, wraps from itertools import chain from types import FunctionType from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Optional, Set, Tuple, Type, Union, overload @@ -147,7 +147,11 @@ def _prepare_validator(function: AnyCallable, allow_reuse: bool) -> 'AnyClassMet """ f_cls = function if isinstance(function, classmethod) else classmethod(function) if not in_ipython() and not allow_reuse: - ref = f_cls.__func__.__module__ + '.' + f_cls.__func__.__qualname__ + ref = ( + getattr(f_cls.__func__, '__module__', '<No __module__>') + + '.' + + getattr(f_cls.__func__, '__qualname__', f'<No __qualname__: id:{id(f_cls.__func__)}>') + ) if ref in _FUNCS: raise ConfigError(f'duplicate validator function "{ref}"; if this is intended, set `allow_reuse=True`') _FUNCS.add(ref) @@ -165,14 +169,18 @@ def get_validators(self, name: str) -> Optional[Dict[str, Validator]]: if name != ROOT_KEY: validators += self.validators.get('*', []) if validators: - return {v.func.__name__: v for v in validators} + return {getattr(v.func, '__name__', f'<No __name__: id:{id(v.func)}>'): v for v in validators} else: return None def check_for_unused(self) -> None: unused_validators = set( chain.from_iterable( - (v.func.__name__ for v in self.validators[f] if v.check_fields) + ( + getattr(v.func, '__name__', f'<No __name__: id:{id(v.func)}>') + for v in self.validators[f] + if v.check_fields + ) for f in (self.validators.keys() - self.used_validators) ) ) @@ -243,8 +251,19 @@ def make_generic_validator(validator: AnyCallable) -> 'ValidatorCallable': """ from inspect import signature - sig = signature(validator) - args = list(sig.parameters.keys()) + if not isinstance(validator, (partial, partialmethod)): + # This should be the default case, so overhead is reduced + sig = signature(validator) + args = list(sig.parameters.keys()) + else: + # Fix the generated argument lists of partial methods + sig = signature(validator.func) + args = [ + k + for k in signature(validator.func).parameters.keys() + if k not in validator.args | validator.keywords.keys() + ] + first_arg = args.pop(0) if first_arg == 'self': raise ConfigError(
pydantic/pydantic
9d0edbe4846373c4154ad9aaf79ffa5238c1b7ea
Thanks @JensHeinrich for reporting this issue. I can confirm the issue. `partial()` returns an instance, not a class or function. it may fix by accessing the function in the following line. I mean replacing `f_cls.__func__.__qualname__` with `f_cls.__func__.func.__qualname__` in case of `partial` https://github.com/pydantic/pydantic/blob/73373c3e08fe5fe23e4b05f549ea34e0da6a16b7/pydantic/_internal/_decorators.py#L204 Would you like to open a PR? I am already working on a PR, but at the moment I just add a better error Even if the `ref` is created in a better way (or the check just skipped by using `allow_reuse=True`) another `AttributeError` is raised [here](https://github.com/pydantic/pydantic/blob/10b8ec7dde62f5e4948a09b9114c5ac64d786ded/pydantic/class_validators.py#L170) Also signature creation doesn't work on it > Even if the `ref` is created in a better way (or the check just skipped by using `allow_reuse=True`) another `AttributeError` is raised [here](https://github.com/pydantic/pydantic/blob/10b8ec7dde62f5e4948a09b9114c5ac64d786ded/pydantic/class_validators.py#L170) This one also can be fixed by the same change that I mentioned before. > I am already working on a PR, but at the moment I just add a better error I think we can make it work at least on `1.10.x` but I am not sure about `V2`. @samuelcolvin Do you think we should prevent using `functools.partial` as a validator? TBH I feel `functools` is broken here and we are just adding a workaround. Even a `lambda` gets an `__qualname__` > TBH I feel `functools` is broken here and we are just adding a workaround. Even a `lambda` gets an `__qualname__` agreed. Feel free to create an issue on cpython and copy me into it, I'd be interest to see what they say. Also, can you create a PR against main to see if this is working there? This one can be related https://bugs.python.org/issue34475 I created an issue python/cpython#102323 I personally find the responses in the links from the last two comments reasonable; it seems we should just not assume that `__qualname__` definitely exists. I'm good with using a default value instead, too. I am working on a PR for v1.10 already I would only allow those with `reuse=True`. Would you support that @samuelcolvin @dmontagu ?
diff --git a/tests/test_validators.py b/tests/test_validators.py --- a/tests/test_validators.py +++ b/tests/test_validators.py @@ -1,8 +1,9 @@ from collections import deque from datetime import datetime from enum import Enum +from functools import partial, partialmethod from itertools import product -from typing import Dict, List, Optional, Tuple, Union +from typing import Any, Callable, Dict, List, Optional, Tuple, Union import pytest from typing_extensions import Literal @@ -1345,3 +1346,32 @@ class Model(BaseModel): {'loc': ('foo',), 'msg': 'the list has duplicated items', 'type': 'value_error.list.unique_items'}, {'loc': ('bar',), 'msg': 'the list has duplicated items', 'type': 'value_error.list.unique_items'}, ] + + [email protected]( + 'func,allow_reuse', + [ + pytest.param(partial, False, id='`partial` and check for reuse'), + pytest.param(partial, True, id='`partial` and ignore reuse'), + pytest.param(partialmethod, False, id='`partialmethod` and check for reuse'), + pytest.param(partialmethod, True, id='`partialmethod` and ignore reuse'), + ], +) +def test_functool_as_validator( + reset_tracked_validators, + func: Callable, + allow_reuse: bool, +): + def custom_validator( + cls, + v: Any, + allowed: str, + ) -> Any: + assert v == allowed, f'Only {allowed} allowed as value; given: {v}' + return v + + validate = func(custom_validator, allowed='TEXT') + + class TestClass(BaseModel): + name: str + _custom_validate = validator('name', allow_reuse=allow_reuse)(validate)
Attribute error for `functools.partial` ### Initial Checks - [X] I have searched GitHub for a duplicate issue and I'm sure this is something new - [X] I have searched Google & StackOverflow for a solution and couldn't find anything - [X] I have read and followed [the docs](https://pydantic-docs.helpmanual.io) and still think this is a bug - [X] I am confident that the issue is with pydantic (not my code, or another library in the ecosystem like [FastAPI](https://fastapi.tiangolo.com) or [mypy](https://mypy.readthedocs.io/en/stable)) ### Description Using a `partialmethod`or `partial` as a `validator` or `root_validator` creates an unhelpful `AttributeError`: ``` tests/conftest.py:14: in <module> class TestClass(BaseModel): tests/conftest.py:17: in TestClass _custom_validate = validator("name")(validate) pydantic/class_validators.py:93: in pydantic.class_validators.validator.dec ??? pydantic/class_validators.py:150: in pydantic.class_validators._prepare_validator ??? E AttributeError: 'functools.partial' object has no attribute '__qualname__' ``` The problem is rooted at [this code](https://github.com/pydantic/pydantic/blob/314abcabbde0936ec2e8e5ff6532d64a221210c5/pydantic/class_validators.py#L150). IMO an try except block with a test for partial methods would be useful here, telling the User to supply the "allow_reuse" parameter for partials. ### Example Code ```Python from functools import partial from pydantic import validator, BaseModel from pydantic.main import ModelMetaclass from pydantic.utils import GetterDict def custom_validator(additional_stuff: str, cls: ModelMetaclass, values: GetterDict): print(additional_stuff) return values validate = partial(custom_validator, "TEXT") class TestClass(BaseModel): name: str _custom_validate = validator("name")(validate) ``` ### Python, Pydantic & OS Version ```Text pydantic version: 1.10.5 pydantic compiled: True install path: XXX/.venv/lib/python3.10/site-packages/pydantic python version: 3.10.7 (main, Nov 24 2022, 19:45:47) [GCC 12.2.0] platform: Linux-5.19.0-31-generic-x86_64-with-glibc2.36 optional deps. installed: ['typing-extensions'] ``` ### Affected Components - [ ] [Compatibility between releases](https://pydantic-docs.helpmanual.io/changelog/) - [X] [Data validation/parsing](https://pydantic-docs.helpmanual.io/usage/models/#basic-model-usage) - [ ] [Data serialization](https://pydantic-docs.helpmanual.io/usage/exporting_models/) - `.model_dump()` and `.model_dump_json()` - [ ] [JSON Schema](https://pydantic-docs.helpmanual.io/usage/schema/) - [ ] [Dataclasses](https://pydantic-docs.helpmanual.io/usage/dataclasses/) - [ ] [Model Config](https://pydantic-docs.helpmanual.io/usage/model_config/) - [ ] [Field Types](https://pydantic-docs.helpmanual.io/usage/types/) - adding or changing a particular data type - [ ] [Function validation decorator](https://pydantic-docs.helpmanual.io/usage/validation_decorator/) - [ ] [Generic Models](https://pydantic-docs.helpmanual.io/usage/models/#generic-models) - [ ] [Other Model behaviour](https://pydantic-docs.helpmanual.io/usage/models/) - `model_construct()`, pickling, private attributes, ORM mode - [ ] [Plugins](https://pydantic-docs.helpmanual.io/) and integration with other tools - mypy, FastAPI, python-devtools, Hypothesis, VS Code, PyCharm, etc.
0.0
9d0edbe4846373c4154ad9aaf79ffa5238c1b7ea
[ "tests/test_validators.py::test_functool_as_validator[`partial`", "tests/test_validators.py::test_functool_as_validator[`partialmethod`" ]
[ "tests/test_validators.py::test_simple", "tests/test_validators.py::test_int_validation", "tests/test_validators.py::test_int_overflow_validation[inf0]", "tests/test_validators.py::test_int_overflow_validation[nan]", "tests/test_validators.py::test_int_overflow_validation[inf1]", "tests/test_validators.py::test_frozenset_validation", "tests/test_validators.py::test_deque_validation", "tests/test_validators.py::test_validate_whole", "tests/test_validators.py::test_validate_kwargs", "tests/test_validators.py::test_validate_pre_error", "tests/test_validators.py::test_validating_assignment_ok", "tests/test_validators.py::test_validating_assignment_fail", "tests/test_validators.py::test_validating_assignment_value_change", "tests/test_validators.py::test_validating_assignment_extra", "tests/test_validators.py::test_validating_assignment_dict", "tests/test_validators.py::test_validating_assignment_values_dict", "tests/test_validators.py::test_validate_multiple", "tests/test_validators.py::test_classmethod", "tests/test_validators.py::test_duplicates", "tests/test_validators.py::test_use_bare", "tests/test_validators.py::test_use_no_fields", "tests/test_validators.py::test_validate_always", "tests/test_validators.py::test_validate_always_on_inheritance", "tests/test_validators.py::test_validate_not_always", "tests/test_validators.py::test_wildcard_validators", "tests/test_validators.py::test_wildcard_validator_error", "tests/test_validators.py::test_invalid_field", "tests/test_validators.py::test_validate_child", "tests/test_validators.py::test_validate_child_extra", "tests/test_validators.py::test_validate_child_all", "tests/test_validators.py::test_validate_parent", "tests/test_validators.py::test_validate_parent_all", "tests/test_validators.py::test_inheritance_keep", "tests/test_validators.py::test_inheritance_replace", "tests/test_validators.py::test_inheritance_new", "tests/test_validators.py::test_validation_each_item", "tests/test_validators.py::test_validation_each_item_one_sublevel", "tests/test_validators.py::test_key_validation", "tests/test_validators.py::test_validator_always_optional", "tests/test_validators.py::test_validator_always_pre", "tests/test_validators.py::test_validator_always_post", "tests/test_validators.py::test_validator_always_post_optional", "tests/test_validators.py::test_validator_bad_fields_throws_configerror", "tests/test_validators.py::test_datetime_validator", "tests/test_validators.py::test_pre_called_once", "tests/test_validators.py::test_make_generic_validator[fields0-_v_]", "tests/test_validators.py::test_make_generic_validator[fields1-_v_]", "tests/test_validators.py::test_make_generic_validator[fields2-_v_,_field_]", "tests/test_validators.py::test_make_generic_validator[fields3-_v_,_config_]", "tests/test_validators.py::test_make_generic_validator[fields4-_v_,_values_]", "tests/test_validators.py::test_make_generic_validator[fields5-_v_,_field_,_config_]", "tests/test_validators.py::test_make_generic_validator[fields6-_v_,_field_,_values_]", "tests/test_validators.py::test_make_generic_validator[fields7-_v_,_config_,_values_]", "tests/test_validators.py::test_make_generic_validator[fields8-_v_,_field_,_values_,_config_]", "tests/test_validators.py::test_make_generic_validator[fields9-_cls_,_v_]", "tests/test_validators.py::test_make_generic_validator[fields10-_cls_,_v_]", "tests/test_validators.py::test_make_generic_validator[fields11-_cls_,_v_,_field_]", "tests/test_validators.py::test_make_generic_validator[fields12-_cls_,_v_,_config_]", "tests/test_validators.py::test_make_generic_validator[fields13-_cls_,_v_,_values_]", "tests/test_validators.py::test_make_generic_validator[fields14-_cls_,_v_,_field_,_config_]", "tests/test_validators.py::test_make_generic_validator[fields15-_cls_,_v_,_field_,_values_]", "tests/test_validators.py::test_make_generic_validator[fields16-_cls_,_v_,_config_,_values_]", "tests/test_validators.py::test_make_generic_validator[fields17-_cls_,_v_,_field_,_values_,_config_]", "tests/test_validators.py::test_make_generic_validator_kwargs", "tests/test_validators.py::test_make_generic_validator_invalid", "tests/test_validators.py::test_make_generic_validator_cls_kwargs", "tests/test_validators.py::test_make_generic_validator_cls_invalid", "tests/test_validators.py::test_make_generic_validator_self", "tests/test_validators.py::test_assert_raises_validation_error", "tests/test_validators.py::test_whole", "tests/test_validators.py::test_root_validator", "tests/test_validators.py::test_root_validator_pre", "tests/test_validators.py::test_root_validator_repeat", "tests/test_validators.py::test_root_validator_repeat2", "tests/test_validators.py::test_root_validator_self", "tests/test_validators.py::test_root_validator_extra", "tests/test_validators.py::test_root_validator_types", "tests/test_validators.py::test_root_validator_inheritance", "tests/test_validators.py::test_root_validator_returns_none_exception", "tests/test_validators.py::test_reuse_global_validators", "tests/test_validators.py::test_allow_reuse[True-True-True-True]", "tests/test_validators.py::test_allow_reuse[True-True-True-False]", "tests/test_validators.py::test_allow_reuse[True-True-False-True]", "tests/test_validators.py::test_allow_reuse[True-True-False-False]", "tests/test_validators.py::test_allow_reuse[True-False-True-True]", "tests/test_validators.py::test_allow_reuse[True-False-True-False]", "tests/test_validators.py::test_allow_reuse[True-False-False-True]", "tests/test_validators.py::test_allow_reuse[True-False-False-False]", "tests/test_validators.py::test_allow_reuse[False-True-True-True]", "tests/test_validators.py::test_allow_reuse[False-True-True-False]", "tests/test_validators.py::test_allow_reuse[False-True-False-True]", "tests/test_validators.py::test_allow_reuse[False-True-False-False]", "tests/test_validators.py::test_allow_reuse[False-False-True-True]", "tests/test_validators.py::test_allow_reuse[False-False-True-False]", "tests/test_validators.py::test_allow_reuse[False-False-False-True]", "tests/test_validators.py::test_allow_reuse[False-False-False-False]", "tests/test_validators.py::test_root_validator_classmethod[True-True]", "tests/test_validators.py::test_root_validator_classmethod[True-False]", "tests/test_validators.py::test_root_validator_classmethod[False-True]", "tests/test_validators.py::test_root_validator_classmethod[False-False]", "tests/test_validators.py::test_root_validator_skip_on_failure", "tests/test_validators.py::test_assignment_validator_cls", "tests/test_validators.py::test_literal_validator", "tests/test_validators.py::test_literal_validator_str_enum", "tests/test_validators.py::test_nested_literal_validator", "tests/test_validators.py::test_union_literal_with_constraints", "tests/test_validators.py::test_field_that_is_being_validated_is_excluded_from_validator_values", "tests/test_validators.py::test_exceptions_in_field_validators_restore_original_field_value", "tests/test_validators.py::test_overridden_root_validators", "tests/test_validators.py::test_list_unique_items_with_optional" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-03-01 08:09:16+00:00
mit
4,888
pydantic__pydantic-5132
diff --git a/pydantic/fields.py b/pydantic/fields.py --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -1117,15 +1117,18 @@ def _validate_discriminated_union( except (AttributeError, TypeError): return v, ErrorWrapper(MissingDiscriminator(discriminator_key=self.discriminator_key), loc) - try: - sub_field = self.sub_fields_mapping[discriminator_value] # type: ignore[index] - except TypeError: + if self.sub_fields_mapping is None: assert cls is not None raise ConfigError( f'field "{self.name}" not yet prepared so type is still a ForwardRef, ' f'you might need to call {cls.__name__}.update_forward_refs().' ) - except KeyError: + + try: + sub_field = self.sub_fields_mapping[discriminator_value] + except (KeyError, TypeError): + # KeyError: `discriminator_value` is not in the dictionary. + # TypeError: `discriminator_value` is unhashable. assert self.sub_fields_mapping is not None return v, ErrorWrapper( InvalidDiscriminator(
pydantic/pydantic
2bf4a124a290f5b5e13a57b52b2259cb75a9a6cf
The real error is there `TypeError: unhashable type: 'list'` but `TypeError` is caught to raise a `ConfigError` indeed. I wrote about error, which received by user. I just didn't understand https://github.com/pydantic/pydantic/blob/v1.10.2/pydantic/fields.py#L1124 otherwise I would have created PR, not issue > I wrote about error, which received by user. I just didn't understand https://github.com/pydantic/pydantic/blob/v1.10.2/pydantic/fields.py#L1124 otherwise I would have created PR, not issue `discriminator` decide `target` can be `Model1` or `Model2` example ```python Foo(foo={'target': 't1', 'a': 1}) # this is Model1 ``` ```python Foo(foo={'target': 't2', 'b': 1}) # this is Model2 ``` Usage below is not right ```python Foo(**{"foo": {"target": {}}}) ``` this is not a bug > this is not a bug You mean that I need to validate `target` field separately or something else? > Usage below is not right Why do you think so? > ```python > Foo(foo={'target': 't2', 'b': 1}) > ``` target should not be {}, target should be one of t1 / t2 > target should not be {}, target should be one of t1 / t2 sounds weird In this case how to explain that all works correctly with `Foo(**{"foo": {"target": 123}})`? The bug report seems to be about the error handling itself. ``` Foo(**{"foo": {"target": 123}}) ``` raises a `ValidationError` indicating the document failed validation ``` Foo(**{"foo": {"target": []}}) ``` raises a `ConfigError` indicating the Model is incorrect --- Both documents should be invalid and thus should both raise `ValidationError`s
diff --git a/tests/test_discrimated_union.py b/tests/test_discrimated_union.py --- a/tests/test_discrimated_union.py +++ b/tests/test_discrimated_union.py @@ -423,3 +423,21 @@ class Container(GenericModel, Generic[T]): # coercion is done properly assert Container[str].parse_obj({'result': {'type': 'Success', 'data': 1}}).result.data == '1' + + +def test_discriminator_with_unhashable_type(): + """Verify an unhashable discriminator value raises a ValidationError.""" + + class Model1(BaseModel): + target: Literal['t1'] + a: int + + class Model2(BaseModel): + target: Literal['t2'] + b: int + + class Foo(BaseModel): + foo: Union[Model1, Model2] = Field(discriminator='target') + + with pytest.raises(ValidationError, match=re.escape("No match for discriminator 'target' and value {}")): + Foo(**{'foo': {'target': {}}})
Unexpected Config Error with discriminator ### Initial Checks - [X] I have searched GitHub for a duplicate issue and I'm sure this is something new - [X] I have searched Google & StackOverflow for a solution and couldn't find anything - [X] I have read and followed [the docs](https://pydantic-docs.helpmanual.io) and still think this is a bug - [X] I am confident that the issue is with pydantic (not my code, or another library in the ecosystem like [FastAPI](https://fastapi.tiangolo.com) or [mypy](https://mypy.readthedocs.io/en/stable)) ### Description Discriminator validation. Expected: ValidationError when passing list or dict as discriminator. Received: ConfigError. ### Example Code ```Python from typing import Literal import pydantic class Model1(pydantic.BaseModel): target: Literal["t1"] a: int class Model2(pydantic.BaseModel): target: Literal["t2"] b: int class Foo(pydantic.BaseModel): foo: Model1 | Model2 = pydantic.Field(discriminator="target") # Foo(**{"foo": {"target": []}}) Foo(**{"foo": {"target": {}}}) ``` ### Python, Pydantic & OS Version ```Text pydantic version: 1.10.2 pydantic compiled: True install path: /home/.../lib/python3.10/site-packages/pydantic python version: 3.10.8 (main, Oct 19 2022, 10:31:59) [GCC 9.4.0] platform: Linux-5.15.0-53-generic-x86_64-with-glibc2.31 optional deps. installed: ['typing-extensions'] ``` ### Affected Components - [ ] [Compatibility between releases](https://pydantic-docs.helpmanual.io/changelog/) - [X] [Data validation/parsing](https://pydantic-docs.helpmanual.io/usage/models/#basic-model-usage) - [ ] [Data serialization](https://pydantic-docs.helpmanual.io/usage/exporting_models/) - `.dict()` and `.json()` - [ ] [JSON Schema](https://pydantic-docs.helpmanual.io/usage/schema/) - [ ] [Dataclasses](https://pydantic-docs.helpmanual.io/usage/dataclasses/) - [ ] [Model Config](https://pydantic-docs.helpmanual.io/usage/model_config/) - [ ] [Field Types](https://pydantic-docs.helpmanual.io/usage/types/) - adding or changing a particular data type - [ ] [Function validation decorator](https://pydantic-docs.helpmanual.io/usage/validation_decorator/) - [ ] [Generic Models](https://pydantic-docs.helpmanual.io/usage/models/#generic-models) - [ ] [Other Model behaviour](https://pydantic-docs.helpmanual.io/usage/models/) - `construct()`, pickling, private attributes, ORM mode - [ ] [Plugins](https://pydantic-docs.helpmanual.io/) and integration with other tools - mypy, FastAPI, python-devtools, Hypothesis, VS Code, PyCharm, etc.
0.0
2bf4a124a290f5b5e13a57b52b2259cb75a9a6cf
[ "tests/test_discrimated_union.py::test_discriminator_with_unhashable_type" ]
[ "tests/test_discrimated_union.py::test_discriminated_union_only_union", "tests/test_discrimated_union.py::test_discriminated_union_single_variant", "tests/test_discrimated_union.py::test_discriminated_union_invalid_type", "tests/test_discrimated_union.py::test_discriminated_union_defined_discriminator", "tests/test_discrimated_union.py::test_discriminated_union_literal_discriminator", "tests/test_discrimated_union.py::test_discriminated_union_root_same_discriminator", "tests/test_discrimated_union.py::test_discriminated_union_validation", "tests/test_discrimated_union.py::test_discriminated_annotated_union", "tests/test_discrimated_union.py::test_discriminated_union_basemodel_instance_value", "tests/test_discrimated_union.py::test_discriminated_union_basemodel_instance_value_with_alias", "tests/test_discrimated_union.py::test_discriminated_union_int", "tests/test_discrimated_union.py::test_discriminated_union_enum", "tests/test_discrimated_union.py::test_alias_different", "tests/test_discrimated_union.py::test_alias_same", "tests/test_discrimated_union.py::test_nested", "tests/test_discrimated_union.py::test_generic" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2023-03-02 23:17:32+00:00
mit
4,889
pydantic__pydantic-5449
diff --git a/pydantic/mypy.py b/pydantic/mypy.py --- a/pydantic/mypy.py +++ b/pydantic/mypy.py @@ -307,15 +307,11 @@ def transform(self) -> None: * stores the fields, config, and if the class is settings in the mypy metadata for access by subclasses """ ctx = self._ctx - info = self._ctx.cls.info + info = ctx.cls.info self.adjust_validator_signatures() config = self.collect_config() fields = self.collect_fields(config) - for field in fields: - if info[field.name].type is None: - if not ctx.api.final_iteration: - ctx.api.defer() is_settings = any(get_fullname(base) == BASESETTINGS_FULLNAME for base in info.mro[:-1]) self.add_initializer(fields, config, is_settings) self.add_construct_method(fields)
pydantic/pydantic
d3cd6c39b4ee617116ff7bb7aab58dcd832d8401
diff --git a/tests/mypy/modules/plugin_success.py b/tests/mypy/modules/plugin_success.py --- a/tests/mypy/modules/plugin_success.py +++ b/tests/mypy/modules/plugin_success.py @@ -262,3 +262,19 @@ class Sample(BaseModel): Sample(foo='hello world') + + +def get_my_custom_validator(field_name: str) -> Any: + @validator(field_name, allow_reuse=True) + def my_custom_validator(cls: Any, v: int) -> int: + return v + + return my_custom_validator + + +def foo() -> None: + class MyModel(BaseModel): + number: int + custom_validator = get_my_custom_validator('number') + + MyModel(number=2) diff --git a/tests/mypy/outputs/plugin-success-strict.txt b/tests/mypy/outputs/plugin-success-strict.txt --- a/tests/mypy/outputs/plugin-success-strict.txt +++ b/tests/mypy/outputs/plugin-success-strict.txt @@ -1,3 +1,4 @@ 30: error: Unexpected keyword argument "z" for "Model" [call-arg] 65: error: Untyped fields disallowed [pydantic-field] 80: error: Argument "x" to "OverrideModel" has incompatible type "float"; expected "int" [arg-type] +278: error: Untyped fields disallowed [pydantic-field] diff --git a/tests/mypy/test_mypy.py b/tests/mypy/test_mypy.py --- a/tests/mypy/test_mypy.py +++ b/tests/mypy/test_mypy.py @@ -64,7 +64,15 @@ def test_mypy_results(config_filename: str, python_filename: str, output_filenam # Specifying a different cache dir for each configuration dramatically speeds up subsequent execution # It also prevents cache-invalidation-related bugs in the tests cache_dir = f'.mypy_cache/test-{os.path.splitext(config_filename)[0]}' - command = [full_filename, '--config-file', full_config_filename, '--cache-dir', cache_dir, '--show-error-codes'] + command = [ + full_filename, + '--config-file', + full_config_filename, + '--cache-dir', + cache_dir, + '--show-error-codes', + '--show-traceback', + ] print(f"\nExecuting: mypy {' '.join(command)}") # makes it easier to debug as necessary actual_result = mypy_api.run(command) actual_out, actual_err, actual_returncode = actual_result
defining a validator causes mypy: maximum semantic analysis iteration count reached ### Initial Checks - [X] I have searched GitHub for a duplicate issue and I'm sure this is something new - [X] I have searched Google & StackOverflow for a solution and couldn't find anything - [X] I have read and followed [the docs](https://docs.pydantic.dev) and still think this is a bug - [X] I am confident that the issue is with pydantic (not my code, or another library in the ecosystem like [FastAPI](https://fastapi.tiangolo.com) or [mypy](https://mypy.readthedocs.io/en/stable)) ### Description Hi, I'm getting the mypy `INTERNAL ERROR: maximum semantic analysis iteration count reached` error when defining a validator in a model via a helper function. Note that declaring the type of the validator makes mypy not crash anymore (see example). Also the issue occurs only with `pydantic.mypy` plugin. ``` mypy tests/test_validators2.py Deferral trace: tests.test_validators2:13 tests.test_validators2:11 tests.test_validators2:11 tests.test_validators2:11 tests.test_validators2:11 tests.test_validators2:11 tests.test_validators2:11 tests.test_validators2:11 tests.test_validators2:11 tests.test_validators2:11 tests.test_validators2:11 tests.test_validators2:11 tests.test_validators2:11 tests.test_validators2:11 tests.test_validators2:11 tests.test_validators2:11 tests.test_validators2:11 tests.test_validators2:11 tests.test_validators2:11 tests/test_validators2.py: error: INTERNAL ERROR: maximum semantic analysis iteration count reached Found 1 error in 1 file (errors prevented further checking) ``` ### Example Code ```Python import pydantic def get_my_custom_validator(field_name: str) -> classmethod: @pydantic.validator(field_name, allow_reuse=True) def my_custom_validator(cls, v: int) -> int: return v return my_custom_validator def foo(): class MyModel(pydantic.BaseModel): number: int custom_validator = get_my_custom_validator("number") # custom_validator: classmethod = get_my_custom_validator("number") # does not crash pass ``` ### Python, Pydantic & OS Version ```Text pydantic version: 1.10.7 pydantic compiled: True install path: /home/.../.cache/pypoetry/virtualenvs/...-aO4xbsjX-py3.10/lib/python3.10/site-packages/pydantic python version: 3.10.4 (main, Apr 27 2022, 18:18:04) [GCC 9.4.0] platform: Linux-5.14.0-1054-oem-x86_64-with-glibc2.35 optional deps. installed: ['dotenv', 'typing-extensions'] mypy: both 1.0.1 and 1.1.1 give the same error pyproject.toml configuration: [tool.mypy] python_version = "3.10" plugins = [ "pydantic.mypy" ] check_untyped_defs = true ignore_missing_imports = true namespace_packages = true strict = true disallow_any_generics = false disallow_incomplete_defs = false disallow_subclassing_any = false disallow_untyped_calls = false disallow_untyped_decorators = false disallow_untyped_defs = false no_implicit_optional = false no_implicit_reexport = false strict_equality = false warn_return_any = false warn_redundant_casts = true warn_unused_ignores = true [tool.pydantic-mypy] init_forbid_extra = true init_typed = true warn_required_dynamic_aliases = true warn_untyped_fields = false ``` ### Affected Components - [ ] [Compatibility between releases](https://docs.pydantic.dev/changelog/) - [ ] [Data validation/parsing](https://docs.pydantic.dev/usage/models/#basic-model-usage) - [ ] [Data serialization](https://docs.pydantic.dev/usage/exporting_models/) - `.dict()` and `.json()` - [ ] [JSON Schema](https://docs.pydantic.dev/usage/schema/) - [ ] [Dataclasses](https://docs.pydantic.dev/usage/dataclasses/) - [ ] [Model Config](https://docs.pydantic.dev/usage/model_config/) - [ ] [Field Types](https://docs.pydantic.dev/usage/types/) - adding or changing a particular data type - [ ] [Function validation decorator](https://docs.pydantic.dev/usage/validation_decorator/) - [ ] [Generic Models](https://docs.pydantic.dev/usage/models/#generic-models) - [ ] [Other Model behaviour](https://docs.pydantic.dev/usage/models/) - `construct()`, pickling, private attributes, ORM mode - [X] [Plugins](https://docs.pydantic.dev/) and integration with other tools - mypy, FastAPI, python-devtools, Hypothesis, VS Code, PyCharm, etc.
0.0
d3cd6c39b4ee617116ff7bb7aab58dcd832d8401
[ "tests/mypy/test_mypy.py::test_mypy_results[mypy-plugin.ini-plugin_success.py-None]", "tests/mypy/test_mypy.py::test_mypy_results[mypy-plugin-strict.ini-plugin_success.py-plugin-success-strict.txt]", "tests/mypy/test_mypy.py::test_mypy_results[pyproject-plugin.toml-plugin_success.py-None]", "tests/mypy/test_mypy.py::test_mypy_results[pyproject-plugin-strict.toml-plugin_success.py-plugin-success-strict.txt]" ]
[ "tests/mypy/test_mypy.py::test_mypy_results[mypy-plugin.ini-plugin_fail.py-plugin-fail.txt]", "tests/mypy/test_mypy.py::test_mypy_results[mypy-plugin.ini-custom_constructor.py-custom_constructor.txt]", "tests/mypy/test_mypy.py::test_mypy_results[mypy-plugin-strict.ini-plugin_fail.py-plugin-fail-strict.txt]", "tests/mypy/test_mypy.py::test_mypy_results[mypy-plugin-strict.ini-fail_defaults.py-fail_defaults.txt]", "tests/mypy/test_mypy.py::test_mypy_results[mypy-default.ini-success.py-None]", "tests/mypy/test_mypy.py::test_mypy_results[mypy-default.ini-fail1.py-fail1.txt]", "tests/mypy/test_mypy.py::test_mypy_results[mypy-default.ini-fail2.py-fail2.txt]", "tests/mypy/test_mypy.py::test_mypy_results[mypy-default.ini-fail3.py-fail3.txt]", "tests/mypy/test_mypy.py::test_mypy_results[mypy-default.ini-fail4.py-fail4.txt]", "tests/mypy/test_mypy.py::test_mypy_results[mypy-default.ini-plugin_success.py-plugin_success.txt]", "tests/mypy/test_mypy.py::test_mypy_results[mypy-plugin-strict-no-any.ini-no_any.py-None]", "tests/mypy/test_mypy.py::test_mypy_results[pyproject-default.toml-success.py-None]", "tests/mypy/test_mypy.py::test_mypy_results[pyproject-default.toml-fail1.py-fail1.txt]", "tests/mypy/test_mypy.py::test_mypy_results[pyproject-default.toml-fail2.py-fail2.txt]", "tests/mypy/test_mypy.py::test_mypy_results[pyproject-default.toml-fail3.py-fail3.txt]", "tests/mypy/test_mypy.py::test_mypy_results[pyproject-default.toml-fail4.py-fail4.txt]", "tests/mypy/test_mypy.py::test_mypy_results[pyproject-plugin.toml-plugin_fail.py-plugin-fail.txt]", "tests/mypy/test_mypy.py::test_mypy_results[pyproject-plugin-strict.toml-plugin_fail.py-plugin-fail-strict.txt]", "tests/mypy/test_mypy.py::test_mypy_results[pyproject-plugin-strict.toml-fail_defaults.py-fail_defaults.txt]", "tests/mypy/test_mypy.py::test_mypy_results[mypy-plugin-strict.ini-settings_config.py-None]", "tests/mypy/test_mypy.py::test_mypy_results[mypy-plugin-strict.ini-plugin_default_factory.py-plugin_default_factory.txt]", "tests/mypy/test_mypy.py::test_bad_toml_config", "tests/mypy/test_mypy.py::test_success_cases_run[settings_config]", "tests/mypy/test_mypy.py::test_success_cases_run[plugin_success]", "tests/mypy/test_mypy.py::test_success_cases_run[success]", "tests/mypy/test_mypy.py::test_success_cases_run[no_any]", "tests/mypy/test_mypy.py::test_explicit_reexports", "tests/mypy/test_mypy.py::test_explicit_reexports_exist", "tests/mypy/test_mypy.py::test_parse_mypy_version[0-v_tuple0]", "tests/mypy/test_mypy.py::test_parse_mypy_version[0.930-v_tuple1]", "tests/mypy/test_mypy.py::test_parse_mypy_version[0.940+dev.04cac4b5d911c4f9529e6ce86a27b44f28846f5d.dirty-v_tuple2]" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2023-04-11 20:07:59+00:00
mit
4,890
pydantic__pydantic-572
diff --git a/pydantic/schema.py b/pydantic/schema.py --- a/pydantic/schema.py +++ b/pydantic/schema.py @@ -220,9 +220,14 @@ def model_schema(model: Type['BaseModel'], by_alias: bool = True, ref_prefix: Op ref_prefix = ref_prefix or default_prefix flat_models = get_flat_models_from_model(model) model_name_map = get_model_name_map(flat_models) + model_name = model_name_map[model] m_schema, m_definitions = model_process_schema( model, by_alias=by_alias, model_name_map=model_name_map, ref_prefix=ref_prefix ) + if model_name in m_definitions: + # m_definitions[model_name] is None, it has circular references + m_definitions[model_name] = m_schema + m_schema = {'$ref': ref_prefix + model_name} if m_definitions: m_schema.update({'definitions': m_definitions}) return m_schema @@ -234,6 +239,7 @@ def field_schema( by_alias: bool = True, model_name_map: Dict[Type['BaseModel'], str], ref_prefix: Optional[str] = None, + known_models: Set[Type['BaseModel']] = None, ) -> Tuple[Dict[str, Any], Dict[str, Any]]: """ Process a Pydantic field and return a tuple with a JSON Schema for it as the first item. @@ -246,6 +252,7 @@ def field_schema( :param model_name_map: used to generate the JSON Schema references to other models included in the definitions :param ref_prefix: the JSON Pointer prefix to use for references to other schemas, if None, the default of #/definitions/ will be used + :param known_models: used to solve circular references :return: tuple of the schema for this field and additional definitions """ ref_prefix = ref_prefix or default_prefix @@ -274,6 +281,7 @@ def field_schema( model_name_map=model_name_map, schema_overrides=schema_overrides, ref_prefix=ref_prefix, + known_models=known_models or set(), ) # $ref will only be returned when there are no schema_overrides if '$ref' in f_schema: @@ -350,7 +358,9 @@ def get_model_name_map(unique_models: Set[Type['BaseModel']]) -> Dict[Type['Base return {v: k for k, v in name_model_map.items()} -def get_flat_models_from_model(model: Type['BaseModel']) -> Set[Type['BaseModel']]: +def get_flat_models_from_model( + model: Type['BaseModel'], known_models: Set[Type['BaseModel']] = None +) -> Set[Type['BaseModel']]: """ Take a single ``model`` and generate a set with itself and all the sub-models in the tree. I.e. if you pass model ``Foo`` (subclass of Pydantic ``BaseModel``) as ``model``, and it has a field of type ``Bar`` (also @@ -358,16 +368,19 @@ def get_flat_models_from_model(model: Type['BaseModel']) -> Set[Type['BaseModel' the return value will be ``set([Foo, Bar, Baz])``. :param model: a Pydantic ``BaseModel`` subclass + :param known_models: used to solve circular references :return: a set with the initial model and all its sub-models """ + known_models = known_models or set() flat_models: Set[Type['BaseModel']] = set() flat_models.add(model) + known_models |= flat_models fields = cast(Sequence[Field], model.__fields__.values()) - flat_models |= get_flat_models_from_fields(fields) + flat_models |= get_flat_models_from_fields(fields, known_models=known_models) return flat_models -def get_flat_models_from_field(field: Field) -> Set[Type['BaseModel']]: +def get_flat_models_from_field(field: Field, known_models: Set[Type['BaseModel']]) -> Set[Type['BaseModel']]: """ Take a single Pydantic ``Field`` (from a model) that could have been declared as a sublcass of BaseModel (so, it could be a submodel), and generate a set with its model and all the sub-models in the tree. @@ -376,20 +389,24 @@ def get_flat_models_from_field(field: Field) -> Set[Type['BaseModel']]: type ``Baz`` (also subclass of ``BaseModel``), the return value will be ``set([Foo, Bar, Baz])``. :param field: a Pydantic ``Field`` + :param known_models: used to solve circular references :return: a set with the model used in the declaration for this field, if any, and all its sub-models """ flat_models: Set[Type['BaseModel']] = set() + # Handle dataclass-based models + field_type = field.type_ + if lenient_issubclass(getattr(field_type, '__pydantic_model__', None), pydantic.BaseModel): + field_type = field_type.__pydantic_model__ # type: ignore if field.sub_fields: - flat_models |= get_flat_models_from_fields(field.sub_fields) - elif lenient_issubclass(field.type_, pydantic.BaseModel): - flat_models |= get_flat_models_from_model(field.type_) - elif lenient_issubclass(getattr(field.type_, '__pydantic_model__', None), pydantic.BaseModel): - field.type_ = cast(Type['dataclasses.DataclassType'], field.type_) - flat_models |= get_flat_models_from_model(field.type_.__pydantic_model__) + flat_models |= get_flat_models_from_fields(field.sub_fields, known_models=known_models) + elif lenient_issubclass(field_type, pydantic.BaseModel) and field_type not in known_models: + flat_models |= get_flat_models_from_model(field_type, known_models=known_models) return flat_models -def get_flat_models_from_fields(fields: Sequence[Field]) -> Set[Type['BaseModel']]: +def get_flat_models_from_fields( + fields: Sequence[Field], known_models: Set[Type['BaseModel']] +) -> Set[Type['BaseModel']]: """ Take a list of Pydantic ``Field``s (from a model) that could have been declared as sublcasses of ``BaseModel`` (so, any of them could be a submodel), and generate a set with their models and all the sub-models in the tree. @@ -398,11 +415,12 @@ def get_flat_models_from_fields(fields: Sequence[Field]) -> Set[Type['BaseModel' subclass of ``BaseModel``), the return value will be ``set([Foo, Bar, Baz])``. :param fields: a list of Pydantic ``Field``s + :param known_models: used to solve circular references :return: a set with any model declared in the fields, and all their sub-models """ flat_models: Set[Type['BaseModel']] = set() for field in fields: - flat_models |= get_flat_models_from_field(field) + flat_models |= get_flat_models_from_field(field, known_models=known_models) return flat_models @@ -429,6 +447,7 @@ def field_type_schema( model_name_map: Dict[Type['BaseModel'], str], schema_overrides: bool = False, ref_prefix: Optional[str] = None, + known_models: Set[Type['BaseModel']], ) -> Tuple[Dict[str, Any], Dict[str, Any]]: """ Used by ``field_schema()``, you probably should be using that function. @@ -440,13 +459,13 @@ def field_type_schema( ref_prefix = ref_prefix or default_prefix if field.shape is Shape.LIST: f_schema, f_definitions = field_singleton_schema( - field, by_alias=by_alias, model_name_map=model_name_map, ref_prefix=ref_prefix + field, by_alias=by_alias, model_name_map=model_name_map, ref_prefix=ref_prefix, known_models=known_models ) definitions.update(f_definitions) return {'type': 'array', 'items': f_schema}, definitions elif field.shape is Shape.SET: f_schema, f_definitions = field_singleton_schema( - field, by_alias=by_alias, model_name_map=model_name_map, ref_prefix=ref_prefix + field, by_alias=by_alias, model_name_map=model_name_map, ref_prefix=ref_prefix, known_models=known_models ) definitions.update(f_definitions) return {'type': 'array', 'uniqueItems': True, 'items': f_schema}, definitions @@ -455,7 +474,7 @@ def field_type_schema( key_field = cast(Field, field.key_field) regex = getattr(key_field.type_, 'regex', None) f_schema, f_definitions = field_singleton_schema( - field, by_alias=by_alias, model_name_map=model_name_map, ref_prefix=ref_prefix + field, by_alias=by_alias, model_name_map=model_name_map, ref_prefix=ref_prefix, known_models=known_models ) definitions.update(f_definitions) if regex: @@ -471,7 +490,7 @@ def field_type_schema( sub_fields = cast(List[Field], field.sub_fields) for sf in sub_fields: sf_schema, sf_definitions = field_type_schema( - sf, by_alias=by_alias, model_name_map=model_name_map, ref_prefix=ref_prefix + sf, by_alias=by_alias, model_name_map=model_name_map, ref_prefix=ref_prefix, known_models=known_models ) definitions.update(sf_definitions) sub_schema.append(sf_schema) @@ -486,6 +505,7 @@ def field_type_schema( model_name_map=model_name_map, schema_overrides=schema_overrides, ref_prefix=ref_prefix, + known_models=known_models, ) definitions.update(f_definitions) return f_schema, definitions @@ -497,6 +517,7 @@ def model_process_schema( by_alias: bool = True, model_name_map: Dict[Type['BaseModel'], str], ref_prefix: Optional[str] = None, + known_models: Set[Type['BaseModel']] = None, ) -> Tuple[Dict[str, Any], Dict[str, Any]]: """ Used by ``model_schema()``, you probably should be using that function. @@ -506,11 +527,13 @@ def model_process_schema( the definitions are returned as the second value. """ ref_prefix = ref_prefix or default_prefix + known_models = known_models or set() s = {'title': model.__config__.title or model.__name__} if model.__doc__: s['description'] = clean_docstring(model.__doc__) + known_models.add(model) m_schema, m_definitions = model_type_schema( - model, by_alias=by_alias, model_name_map=model_name_map, ref_prefix=ref_prefix + model, by_alias=by_alias, model_name_map=model_name_map, ref_prefix=ref_prefix, known_models=known_models ) s.update(m_schema) return s, m_definitions @@ -522,6 +545,7 @@ def model_type_schema( by_alias: bool, model_name_map: Dict[Type['BaseModel'], str], ref_prefix: Optional[str] = None, + known_models: Set[Type['BaseModel']], ) -> Tuple[Dict[str, Any], Dict[str, Any]]: """ You probably should be using ``model_schema()``, this function is indirectly used by that function. @@ -536,7 +560,7 @@ def model_type_schema( for k, f in model.__fields__.items(): try: f_schema, f_definitions = field_schema( - f, by_alias=by_alias, model_name_map=model_name_map, ref_prefix=ref_prefix + f, by_alias=by_alias, model_name_map=model_name_map, ref_prefix=ref_prefix, known_models=known_models ) except SkipField as skip: warnings.warn(skip.message, UserWarning) @@ -563,6 +587,7 @@ def field_singleton_sub_fields_schema( model_name_map: Dict[Type['BaseModel'], str], schema_overrides: bool = False, ref_prefix: Optional[str] = None, + known_models: Set[Type['BaseModel']], ) -> Tuple[Dict[str, Any], Dict[str, Any]]: """ This function is indirectly used by ``field_schema()``, you probably should be using that function. @@ -580,6 +605,7 @@ def field_singleton_sub_fields_schema( model_name_map=model_name_map, schema_overrides=schema_overrides, ref_prefix=ref_prefix, + known_models=known_models, ) else: sub_field_schemas = [] @@ -590,6 +616,7 @@ def field_singleton_sub_fields_schema( model_name_map=model_name_map, schema_overrides=schema_overrides, ref_prefix=ref_prefix, + known_models=known_models, ) definitions.update(sub_definitions) sub_field_schemas.append(sub_schema) @@ -662,6 +689,7 @@ def field_singleton_schema( # noqa: C901 (ignore complexity) model_name_map: Dict[Type['BaseModel'], str], schema_overrides: bool = False, ref_prefix: Optional[str] = None, + known_models: Set[Type['BaseModel']], ) -> Tuple[Dict[str, Any], Dict[str, Any]]: """ This function is indirectly used by ``field_schema()``, you should probably be using that function. @@ -678,6 +706,7 @@ def field_singleton_schema( # noqa: C901 (ignore complexity) model_name_map=model_name_map, schema_overrides=schema_overrides, ref_prefix=ref_prefix, + known_models=known_models, ) if field.type_ is Any: return {}, definitions # no restrictions @@ -708,19 +737,26 @@ def field_singleton_schema( # noqa: C901 (ignore complexity) # Handle dataclass-based models field_type = field.type_ if lenient_issubclass(getattr(field_type, '__pydantic_model__', None), pydantic.BaseModel): - field_type = cast(Type['dataclasses.DataclassType'], field_type) - field_type = field_type.__pydantic_model__ + field_type = field_type.__pydantic_model__ # type: ignore if issubclass(field_type, pydantic.BaseModel): - sub_schema, sub_definitions = model_process_schema( - field_type, by_alias=by_alias, model_name_map=model_name_map, ref_prefix=ref_prefix - ) - definitions.update(sub_definitions) - if not schema_overrides: - model_name = model_name_map[field_type] + model_name = model_name_map[field_type] + if field_type not in known_models: + sub_schema, sub_definitions = model_process_schema( + field_type, + by_alias=by_alias, + model_name_map=model_name_map, + ref_prefix=ref_prefix, + known_models=known_models, + ) + definitions.update(sub_definitions) definitions[model_name] = sub_schema - return {'$ref': f'{ref_prefix}{model_name}'}, definitions else: - return sub_schema, definitions + definitions[model_name] = None + schema_ref = {'$ref': ref_prefix + model_name} + if not schema_overrides: + return schema_ref, definitions + else: + return {'allOf': [schema_ref]}, definitions raise ValueError(f'Value not declarable with JSON Schema, field: {field}')
pydantic/pydantic
9ffa311f8fd54ad2a5619477a0612f99c7bc7ae4
I'm not sure what the correct behaviour would be here? Since the model is self referencing, the schema surely is infinitely recursive? @tiangolo do you have an idea about what to do here? Maybe just a more constructive error. Yes, it should be able to create the JSON Schema, assign an ID to it and then reference it with `$ref`. Here's the relevant section in the spec: http://json-schema.org/latest/json-schema-core.html#rfc.section.8.3 I'll try to fix it as soon as I get a chance. Awesome, thank you. I think you're the best person to do it since you understand schema best.
diff --git a/tests/test_py37.py b/tests/test_py37.py --- a/tests/test_py37.py +++ b/tests/test_py37.py @@ -203,7 +203,7 @@ class Node(BaseModel): ) Node = module.Node Leaf = module.Leaf - data = {"value": 3, "left": {"a": "foo"}, "right": {"value": 5, "left": {"a": "bar"}, "right": {"a": "buzz"}}} + data = {'value': 3, 'left': {'a': 'foo'}, 'right': {'value': 5, 'left': {'a': 'bar'}, 'right': {'a': 'buzz'}}} node = Node(**data) assert isinstance(node.left, Leaf) @@ -238,11 +238,97 @@ class Node(BaseModel): Node = module.Node Leaf = module.Leaf data = { - "value": 3, - "left": {"a": "foo"}, - "right": [{"value": 5, "left": {"a": "bar"}, "right": {"a": "buzz"}}, "test"], + 'value': 3, + 'left': {'a': 'foo'}, + 'right': [{'value': 5, 'left': {'a': 'bar'}, 'right': {'a': 'buzz'}}, 'test'], } node = Node(**data) assert isinstance(node.left, Leaf) assert isinstance(node.right[0], Node) + + +@skip_not_37 +def test_self_reference_json_schema(create_module): + module = create_module( + """ +from __future__ import annotations +from typing import List +from pydantic import BaseModel, Schema + +class Account(BaseModel): + name: str + subaccounts: List[Account] = [] + +Account.update_forward_refs() + """ + ) + Account = module.Account + assert Account.schema() == { + '$ref': '#/definitions/Account', + 'definitions': { + 'Account': { + 'title': 'Account', + 'type': 'object', + 'properties': { + 'name': {'title': 'Name', 'type': 'string'}, + 'subaccounts': { + 'title': 'Subaccounts', + 'default': [], + 'type': 'array', + 'items': {'$ref': '#/definitions/Account'}, + }, + }, + 'required': ['name'], + } + }, + } + + +@skip_not_37 +def test_circular_reference_json_schema(create_module): + module = create_module( + """ +from __future__ import annotations +from typing import List +from pydantic import BaseModel, Schema + +class Owner(BaseModel): + account: Account + +class Account(BaseModel): + name: str + owner: Owner + subaccounts: List[Account] = [] + +Account.update_forward_refs() +Owner.update_forward_refs() + """ + ) + Account = module.Account + assert Account.schema() == { + '$ref': '#/definitions/Account', + 'definitions': { + 'Account': { + 'title': 'Account', + 'type': 'object', + 'properties': { + 'name': {'title': 'Name', 'type': 'string'}, + 'owner': {'$ref': '#/definitions/Owner'}, + 'subaccounts': { + 'title': 'Subaccounts', + 'default': [], + 'type': 'array', + 'items': {'$ref': '#/definitions/Account'}, + }, + }, + 'required': ['name', 'owner'], + }, + 'Owner': { + 'title': 'Owner', + 'type': 'object', + 'properties': {'account': {'$ref': '#/definitions/Account'}}, + 'required': ['account'], + }, + }, + } diff --git a/tests/test_schema.py b/tests/test_schema.py --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -917,18 +917,16 @@ class Model(BaseModel): 'title': 'Model', 'type': 'object', 'definitions': { + 'Foo': { + 'title': 'Foo', + 'type': 'object', + 'properties': {'a': {'title': 'A', 'type': 'string'}}, + 'required': ['a'], + }, 'Bar': { 'title': 'Bar', 'type': 'object', - 'properties': { - 'b': { - 'title': 'Foo', - 'type': 'object', - 'properties': {'a': {'title': 'A', 'type': 'string'}}, - 'required': ['a'], - 'default': {'a': 'foo'}, - } - }, + 'properties': {'b': {'title': 'B', 'default': {'a': 'foo'}, 'allOf': [{'$ref': '#/definitions/Foo'}]}}, }, 'Baz': {'title': 'Baz', 'type': 'object', 'properties': {'c': {'$ref': '#/definitions/Bar'}}}, },
Recursion error when generating schema <!-- Questions, Feature Requests, and Bug Reports are all welcome --> <!-- delete as applicable: --> # Bug For bugs/questions: * OS: **ubuntu 18.04** * Python version `import sys; print(sys.version)`: **3.7.3** * Pydantic version `import pydantic; print(pydantic.VERSION)`: **0.25** Running the code below to generate schema causes a recursion error. ```py from __future__ import annotations import typing from pydantic import BaseModel, Schema class Account(BaseModel): name: str subaccounts: typing.List[Account] = [] Account.update_forward_refs() print(Account.schema_json(indent=2)) ... ``` Snippet of recursion traceback ```py ... flat_models |= get_flat_models_from_model(field.type_) File "/home/nav/.local/share/virtualenvs/project-oxBoBmI4/lib/python3.7/site-packages/pydantic/schema.py", line 355, in get_flat_models_from_model flat_models |= get_flat_models_from_fields(fields) File "/home/nav/.local/share/virtualenvs/project-oxBoBmI4/lib/python3.7/site-packages/pydantic/schema.py", line 394, in get_flat_models_from_fields flat_models |= get_flat_models_from_field(field) File "/home/nav/.local/share/virtualenvs/project-oxBoBmI4/lib/python3.7/site-packages/pydantic/schema.py", line 373, in get_flat_models_from_field elif lenient_issubclass(field.type_, main.BaseModel): File "/home/nav/.local/share/virtualenvs/project-oxBoBmI4/lib/python3.7/site-packages/pydantic/utils.py", line 232, in lenient_issubclass return isinstance(cls, type) and issubclass(cls, class_or_tuple) File "/home/nav/.local/share/virtualenvs/project-oxBoBmI4/lib/python3.7/abc.py", line 143, in __subclasscheck__ return _abc_subclasscheck(cls, subclass) RecursionError: maximum recursion depth exceeded in comparison ```
0.0
9ffa311f8fd54ad2a5619477a0612f99c7bc7ae4
[ "tests/test_py37.py::test_self_reference_json_schema", "tests/test_py37.py::test_circular_reference_json_schema", "tests/test_schema.py::test_schema_overrides" ]
[ "tests/test_py37.py::test_postponed_annotations", "tests/test_py37.py::test_postponed_annotations_optional", "tests/test_py37.py::test_basic_forward_ref", "tests/test_py37.py::test_self_forward_ref_module", "tests/test_py37.py::test_self_forward_ref_collection", "tests/test_py37.py::test_self_forward_ref_local", "tests/test_py37.py::test_missing_update_forward_refs", "tests/test_py37.py::test_forward_ref_dataclass", "tests/test_py37.py::test_forward_ref_sub_types", "tests/test_py37.py::test_forward_ref_nested_sub_types", "tests/test_schema.py::test_key", "tests/test_schema.py::test_by_alias", "tests/test_schema.py::test_sub_model", "tests/test_schema.py::test_schema_class", "tests/test_schema.py::test_schema_repr", "tests/test_schema.py::test_schema_class_by_alias", "tests/test_schema.py::test_choices", "tests/test_schema.py::test_json_schema", "tests/test_schema.py::test_list_sub_model", "tests/test_schema.py::test_optional", "tests/test_schema.py::test_any", "tests/test_schema.py::test_set", "tests/test_schema.py::test_const_str", "tests/test_schema.py::test_const_false", "tests/test_schema.py::test_tuple[tuple-expected_schema0]", "tests/test_schema.py::test_tuple[field_type1-expected_schema1]", "tests/test_schema.py::test_tuple[field_type2-expected_schema2]", "tests/test_schema.py::test_bool", "tests/test_schema.py::test_dict", "tests/test_schema.py::test_list", "tests/test_schema.py::test_list_union_dict[field_type0-expected_schema0]", "tests/test_schema.py::test_list_union_dict[field_type1-expected_schema1]", "tests/test_schema.py::test_list_union_dict[field_type2-expected_schema2]", "tests/test_schema.py::test_list_union_dict[field_type3-expected_schema3]", "tests/test_schema.py::test_list_union_dict[field_type4-expected_schema4]", "tests/test_schema.py::test_date_types[datetime-expected_schema0]", "tests/test_schema.py::test_date_types[date-expected_schema1]", "tests/test_schema.py::test_date_types[time-expected_schema2]", "tests/test_schema.py::test_date_types[timedelta-expected_schema3]", "tests/test_schema.py::test_str_basic_types[field_type0-expected_schema0]", "tests/test_schema.py::test_str_basic_types[field_type1-expected_schema1]", "tests/test_schema.py::test_str_basic_types[field_type2-expected_schema2]", "tests/test_schema.py::test_str_basic_types[field_type3-expected_schema3]", "tests/test_schema.py::test_str_constrained_types[StrictStr-expected_schema0]", "tests/test_schema.py::test_str_constrained_types[ConstrainedStr-expected_schema1]", "tests/test_schema.py::test_str_constrained_types[ConstrainedStrValue-expected_schema2]", "tests/test_schema.py::test_special_str_types[UrlStr-expected_schema0]", "tests/test_schema.py::test_special_str_types[UrlStrValue-expected_schema1]", "tests/test_schema.py::test_special_str_types[DSN-expected_schema2]", "tests/test_schema.py::test_email_str_types[EmailStr-email]", "tests/test_schema.py::test_email_str_types[NameEmail-name-email]", "tests/test_schema.py::test_secret_types[SecretBytes-string]", "tests/test_schema.py::test_secret_types[SecretStr-string]", "tests/test_schema.py::test_special_int_types[ConstrainedInt-expected_schema0]", "tests/test_schema.py::test_special_int_types[ConstrainedIntValue-expected_schema1]", "tests/test_schema.py::test_special_int_types[ConstrainedIntValue-expected_schema2]", "tests/test_schema.py::test_special_int_types[ConstrainedIntValue-expected_schema3]", "tests/test_schema.py::test_special_int_types[PositiveInt-expected_schema4]", "tests/test_schema.py::test_special_int_types[NegativeInt-expected_schema5]", "tests/test_schema.py::test_special_float_types[ConstrainedFloat-expected_schema0]", "tests/test_schema.py::test_special_float_types[ConstrainedFloatValue-expected_schema1]", "tests/test_schema.py::test_special_float_types[ConstrainedFloatValue-expected_schema2]", "tests/test_schema.py::test_special_float_types[ConstrainedFloatValue-expected_schema3]", "tests/test_schema.py::test_special_float_types[PositiveFloat-expected_schema4]", "tests/test_schema.py::test_special_float_types[NegativeFloat-expected_schema5]", "tests/test_schema.py::test_special_float_types[ConstrainedDecimal-expected_schema6]", "tests/test_schema.py::test_special_float_types[ConstrainedDecimalValue-expected_schema7]", "tests/test_schema.py::test_special_float_types[ConstrainedDecimalValue-expected_schema8]", "tests/test_schema.py::test_special_float_types[ConstrainedDecimalValue-expected_schema9]", "tests/test_schema.py::test_uuid_types[UUID-uuid]", "tests/test_schema.py::test_uuid_types[UUID1-uuid1]", "tests/test_schema.py::test_uuid_types[UUID3-uuid3]", "tests/test_schema.py::test_uuid_types[UUID4-uuid4]", "tests/test_schema.py::test_uuid_types[UUID5-uuid5]", "tests/test_schema.py::test_path_types[FilePath-file-path]", "tests/test_schema.py::test_path_types[DirectoryPath-directory-path]", "tests/test_schema.py::test_path_types[Path-path]", "tests/test_schema.py::test_json_type", "tests/test_schema.py::test_ipv4address_type", "tests/test_schema.py::test_ipv6address_type", "tests/test_schema.py::test_ipvanyaddress_type", "tests/test_schema.py::test_ipv4interface_type", "tests/test_schema.py::test_ipv6interface_type", "tests/test_schema.py::test_ipvanyinterface_type", "tests/test_schema.py::test_ipv4network_type", "tests/test_schema.py::test_ipv6network_type", "tests/test_schema.py::test_ipvanynetwork_type", "tests/test_schema.py::test_callable_type[annotation0]", "tests/test_schema.py::test_callable_type[annotation1]", "tests/test_schema.py::test_error_non_supported_types", "tests/test_schema.py::test_flat_models_unique_models", "tests/test_schema.py::test_flat_models_with_submodels", "tests/test_schema.py::test_flat_models_with_submodels_from_sequence", "tests/test_schema.py::test_model_name_maps", "tests/test_schema.py::test_schema_from_models", "tests/test_schema.py::test_schema_with_ref_prefix", "tests/test_schema.py::test_schema_no_definitions", "tests/test_schema.py::test_list_default", "tests/test_schema.py::test_dict_default", "tests/test_schema.py::test_constraints_schema[kwargs0-str-expected_extra0]", "tests/test_schema.py::test_constraints_schema[kwargs1-ConstrainedStrValue-expected_extra1]", "tests/test_schema.py::test_constraints_schema[kwargs2-str-expected_extra2]", "tests/test_schema.py::test_constraints_schema[kwargs3-bytes-expected_extra3]", "tests/test_schema.py::test_constraints_schema[kwargs4-str-expected_extra4]", "tests/test_schema.py::test_constraints_schema[kwargs5-int-expected_extra5]", "tests/test_schema.py::test_constraints_schema[kwargs6-int-expected_extra6]", "tests/test_schema.py::test_constraints_schema[kwargs7-int-expected_extra7]", "tests/test_schema.py::test_constraints_schema[kwargs8-int-expected_extra8]", "tests/test_schema.py::test_constraints_schema[kwargs9-int-expected_extra9]", "tests/test_schema.py::test_constraints_schema[kwargs10-float-expected_extra10]", "tests/test_schema.py::test_constraints_schema[kwargs11-float-expected_extra11]", "tests/test_schema.py::test_constraints_schema[kwargs12-float-expected_extra12]", "tests/test_schema.py::test_constraints_schema[kwargs13-float-expected_extra13]", "tests/test_schema.py::test_constraints_schema[kwargs14-float-expected_extra14]", "tests/test_schema.py::test_constraints_schema[kwargs15-Decimal-expected_extra15]", "tests/test_schema.py::test_constraints_schema[kwargs16-Decimal-expected_extra16]", "tests/test_schema.py::test_constraints_schema[kwargs17-Decimal-expected_extra17]", "tests/test_schema.py::test_constraints_schema[kwargs18-Decimal-expected_extra18]", "tests/test_schema.py::test_constraints_schema[kwargs19-Decimal-expected_extra19]", "tests/test_schema.py::test_not_constraints_schema[kwargs0-int-expected0]", "tests/test_schema.py::test_not_constraints_schema[kwargs1-float-expected1]", "tests/test_schema.py::test_not_constraints_schema[kwargs2-Decimal-expected2]", "tests/test_schema.py::test_not_constraints_schema[kwargs3-int-expected3]", "tests/test_schema.py::test_not_constraints_schema[kwargs4-str-expected4]", "tests/test_schema.py::test_not_constraints_schema[kwargs5-bytes-expected5]", "tests/test_schema.py::test_not_constraints_schema[kwargs6-str-expected6]", "tests/test_schema.py::test_not_constraints_schema[kwargs7-bool-expected7]", "tests/test_schema.py::test_constraints_schema_validation[kwargs0-str-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs1-ConstrainedStrValue-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs2-str-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs3-bytes-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs4-str-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs5-bool-True]", "tests/test_schema.py::test_constraints_schema_validation[kwargs6-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs7-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs8-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs9-int-2]", "tests/test_schema.py::test_constraints_schema_validation[kwargs10-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs11-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs12-int-5]", "tests/test_schema.py::test_constraints_schema_validation[kwargs13-float-3.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs14-float-2.1]", "tests/test_schema.py::test_constraints_schema_validation[kwargs15-float-3.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs16-float-4.9]", "tests/test_schema.py::test_constraints_schema_validation[kwargs17-float-3.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs18-float-2.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs19-float-3.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs20-float-5.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs21-float-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs22-float-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs23-Decimal-value23]", "tests/test_schema.py::test_constraints_schema_validation[kwargs24-Decimal-value24]", "tests/test_schema.py::test_constraints_schema_validation[kwargs25-Decimal-value25]", "tests/test_schema.py::test_constraints_schema_validation[kwargs26-Decimal-value26]", "tests/test_schema.py::test_constraints_schema_validation[kwargs27-Decimal-value27]", "tests/test_schema.py::test_constraints_schema_validation[kwargs28-Decimal-value28]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs0-str-foobar]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs1-str-f]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs2-str-bar]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs3-int-2]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs4-int-5]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs5-int-1]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs6-int-6]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs7-float-2.0]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs8-float-5.0]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs9-float-1.9]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs10-float-5.1]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs11-Decimal-value11]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs12-Decimal-value12]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs13-Decimal-value13]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs14-Decimal-value14]", "tests/test_schema.py::test_schema_kwargs", "tests/test_schema.py::test_schema_dict_constr", "tests/test_schema.py::test_bytes_constrained_types[ConstrainedBytes-expected_schema0]", "tests/test_schema.py::test_bytes_constrained_types[ConstrainedBytesValue-expected_schema1]", "tests/test_schema.py::test_optional_dict", "tests/test_schema.py::test_field_with_validator" ]
{ "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-06-03 14:36:49+00:00
mit
4,891
pydantic__pydantic-5736
diff --git a/pydantic/fields.py b/pydantic/fields.py --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -1107,7 +1107,13 @@ def _validate_discriminated_union( assert self.discriminator_alias is not None try: - discriminator_value = v[self.discriminator_alias] + try: + discriminator_value = v[self.discriminator_alias] + except KeyError: + if self.model_config.allow_population_by_field_name: + discriminator_value = v[self.discriminator_key] + else: + raise except KeyError: return v, ErrorWrapper(MissingDiscriminator(discriminator_key=self.discriminator_key), loc) except TypeError:
pydantic/pydantic
81311964d2da6b1606d9b7c175f84171a54271ec
I think this is a duplicate of #3846. Apologies, I started writing this yesterday evening before the other issue was created. Spooky that we found a similar problem around the same time! 😅 If you'd like to confirm, you could try the tentative fix that I've proposed here to see if it fixes your issue too. If so then we could link both tickets to the same PR. https://github.com/samuelcolvin/pydantic/pull/3847 I'll check this tomorrow at work, thanks! **EDIT**: Just tried it out and it doesn't seem to work for the example above :disappointed: ``` ---> 35 print(Model(pet={"pet_type": "dog", "barks": 3.14}, n=1)) ~/src/pydantic/pydantic/main.py in __init__(__pydantic_self__, **data) 329 values, fields_set, validation_error = validate_model(__pydantic_self__.__class__, data) 330 if validation_error: --> 331 raise validation_error 332 try: 333 object_setattr(__pydantic_self__, '__dict__', values) ValidationError: 1 validation error for Model pet Discriminator 'pet_type' is missing in value (type=value_error.discriminated_union.missing_discriminator; discriminator_key=pet_type) ``` Can confirm, just had this same issue today Hello, we are having the same issue. It happens not only when passing dicts like the OP did, but also if you pass model instances (See example below). @samuelcolvin Is there any plan to fix this soon? Thank you ``` class Cat(BaseModel): pet_type: Literal['cat'] = Field(alias='pet_type_alias') name: str class Dog(BaseModel): pet_type: Literal['dog'] = Field(alias='pet_type_alias') name: str class Home(BaseModel): pet: Annotated[Union[Dog, Cat], Field(discriminator='pet_type')] cat = Cat(name="Mitzi", pet_type_alias='cat') home = Home(pet=cat) # pydantic.error_wrappers.ValidationError: 1 validation error for Home # pet # Discriminator 'pet_type' is missing in value (type=value_error.discriminated_union.missing_discriminator; discriminator_key=pet_type) ``` Yes, it's fixed in pydantic-core and will be fixed in V2. It seems this is fixed in v2: ```python from pydantic import BaseModel, Field from typing import Union from typing_extensions import Literal, Annotated class Cat(BaseModel): pet_type: Literal['cat'] = Field(alias='pet_type_alias') name: str class Dog(BaseModel): pet_type: Literal['dog'] = Field(alias='pet_type_alias') name: str class Home(BaseModel): pet: Annotated[Union[Dog, Cat], Field(discriminator='pet_type')] cat = Cat(name="Mitzi", pet_type_alias='cat') home = Home(pet=cat) print(home) #> pet=Cat(pet_type='cat', name='Mitzi') ```
diff --git a/tests/test_discrimated_union.py b/tests/test_discrimated_union.py --- a/tests/test_discrimated_union.py +++ b/tests/test_discrimated_union.py @@ -285,6 +285,80 @@ class Top(BaseModel): assert Top(sub=B(literal='b')).sub.literal == 'b' +def test_discriminated_union_model_with_alias(): + class A(BaseModel): + literal: Literal['a'] = Field(alias='lit') + + class B(BaseModel): + literal: Literal['b'] = Field(alias='lit') + + class Config: + allow_population_by_field_name = True + + class TopDisallow(BaseModel): + sub: Union[A, B] = Field(..., discriminator='literal', alias='s') + + class TopAllow(BaseModel): + sub: Union[A, B] = Field(..., discriminator='literal', alias='s') + + class Config: + allow_population_by_field_name = True + + assert TopDisallow.parse_obj({'s': {'lit': 'a'}}).sub.literal == 'a' + + with pytest.raises(ValidationError) as exc_info: + TopDisallow.parse_obj({'s': {'literal': 'b'}}) + + assert exc_info.value.errors() == [ + { + 'ctx': {'discriminator_key': 'literal'}, + 'loc': ('s',), + 'msg': "Discriminator 'literal' is missing in value", + 'type': 'value_error.discriminated_union.missing_discriminator', + }, + ] + + with pytest.raises(ValidationError) as exc_info: + TopDisallow.parse_obj({'s': {'literal': 'a'}}) + + assert exc_info.value.errors() == [ + { + 'ctx': {'discriminator_key': 'literal'}, + 'loc': ('s',), + 'msg': "Discriminator 'literal' is missing in value", + 'type': 'value_error.discriminated_union.missing_discriminator', + } + ] + + with pytest.raises(ValidationError) as exc_info: + TopDisallow.parse_obj({'sub': {'lit': 'a'}}) + + assert exc_info.value.errors() == [ + {'loc': ('s',), 'msg': 'field required', 'type': 'value_error.missing'}, + ] + + assert TopAllow.parse_obj({'s': {'lit': 'a'}}).sub.literal == 'a' + assert TopAllow.parse_obj({'s': {'lit': 'b'}}).sub.literal == 'b' + assert TopAllow.parse_obj({'s': {'literal': 'b'}}).sub.literal == 'b' + assert TopAllow.parse_obj({'sub': {'lit': 'a'}}).sub.literal == 'a' + assert TopAllow.parse_obj({'sub': {'lit': 'b'}}).sub.literal == 'b' + assert TopAllow.parse_obj({'sub': {'literal': 'b'}}).sub.literal == 'b' + + with pytest.raises(ValidationError) as exc_info: + TopAllow.parse_obj({'s': {'literal': 'a'}}) + + assert exc_info.value.errors() == [ + {'loc': ('s', 'A', 'lit'), 'msg': 'field required', 'type': 'value_error.missing'}, + ] + + with pytest.raises(ValidationError) as exc_info: + TopAllow.parse_obj({'sub': {'literal': 'a'}}) + + assert exc_info.value.errors() == [ + {'loc': ('s', 'A', 'lit'), 'msg': 'field required', 'type': 'value_error.missing'}, + ] + + def test_discriminated_union_int(): class A(BaseModel): l: Literal[1]
Discriminated union does not work with aliased literal field ### Checks * [x] I added a descriptive title to this issue * [x] I have searched (google, github) for similar issues and couldn't find anything * [x] I have read and followed [the docs](https://pydantic-docs.helpmanual.io/) and still think this is a bug <!-- Sorry to sound so draconian, but every second saved replying to issues is time spend improving pydantic :-) --> # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.9.0 pydantic compiled: True install path: /home/ljnsn/.virtualenvs/py39/lib/python3.9/site-packages/ pydantic python version: 3.9.7 (default, Sep 10 2021, 14:59:43) [GCC 11.2.0] platform: Linux-5.15.23-76051523-generic-x86_64-with-glibc2.34 optional deps. installed: ['typing-extensions'] ``` It seems like the discriminator field for a discriminated union is only recognized when it is passed by its alias, even when `allow_population_by_field_name = True`. I would expect to be able to pass the discriminator field by field name, just like any other field, when that config option is set. ```py from typing import Literal, Union from pydantic import BaseModel, Field class Base(BaseModel): class Config: allow_population_by_field_name = True class Cat(Base): pet_type: Literal["cat"] = Field(alias="petType") meows: int class Dog(Base): pet_type: Literal["dog"] = Field(alias="petType") barks: float class Lizard(Base): pet_type: Literal["reptile", "lizard"] = Field(alias="petType") scales: bool class Model(Base): pet: Union[Cat, Dog, Lizard] = Field(..., discriminator="pet_type") n: int print(Dog(**{"pet_type": "dog", "barks": 3.14})) print(Model(pet={"petType": "dog", "barks": 3.14}, n=1)) print(Model(pet={"pet_type": "dog", "barks": 3.14}, n=1)) # > pydantic.error_wrappers.ValidationError: 1 validation error for Model pet # Discriminator 'pet_type' is missing in value (type=value_error.discriminated_union.miss # ing_discriminator; discriminator_key=pet_type) ```
0.0
81311964d2da6b1606d9b7c175f84171a54271ec
[ "tests/test_discrimated_union.py::test_discriminated_union_model_with_alias" ]
[ "tests/test_discrimated_union.py::test_discriminated_union_only_union", "tests/test_discrimated_union.py::test_discriminated_union_single_variant", "tests/test_discrimated_union.py::test_discriminated_union_invalid_type", "tests/test_discrimated_union.py::test_discriminated_union_defined_discriminator", "tests/test_discrimated_union.py::test_discriminated_union_literal_discriminator", "tests/test_discrimated_union.py::test_discriminated_union_root_same_discriminator", "tests/test_discrimated_union.py::test_discriminated_union_validation", "tests/test_discrimated_union.py::test_discriminated_annotated_union", "tests/test_discrimated_union.py::test_discriminated_union_basemodel_instance_value", "tests/test_discrimated_union.py::test_discriminated_union_basemodel_instance_value_with_alias", "tests/test_discrimated_union.py::test_discriminated_union_int", "tests/test_discrimated_union.py::test_discriminated_union_enum", "tests/test_discrimated_union.py::test_alias_different", "tests/test_discrimated_union.py::test_alias_same", "tests/test_discrimated_union.py::test_nested", "tests/test_discrimated_union.py::test_generic", "tests/test_discrimated_union.py::test_discriminator_with_unhashable_type" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2023-05-10 15:56:51+00:00
mit
4,892
pydantic__pydantic-606
diff --git a/pydantic/dataclasses.py b/pydantic/dataclasses.py --- a/pydantic/dataclasses.py +++ b/pydantic/dataclasses.py @@ -13,8 +13,6 @@ class DataclassType: __pydantic_model__: Type[BaseModel] - __post_init_original__: Callable[..., None] - __post_init_post_parse__: Callable[..., None] __initialised__: bool def __init__(self, *args: Any, **kwargs: Any) -> None: @@ -25,16 +23,6 @@ def __validate__(cls, v: Any) -> 'DataclassType': pass -def _pydantic_post_init(self: 'DataclassType', *initvars: Any) -> None: - if self.__post_init_original__: - self.__post_init_original__(*initvars) - d = validate_model(self.__pydantic_model__, self.__dict__, cls=self.__class__)[0] - object.__setattr__(self, '__dict__', d) - object.__setattr__(self, '__initialised__', True) - if self.__post_init_post_parse__: - self.__post_init_post_parse__() - - def _validate_dataclass(cls: Type['DataclassType'], v: Any) -> 'DataclassType': if isinstance(v, cls): return v @@ -75,6 +63,16 @@ def _process_class( post_init_post_parse = getattr(_cls, '__post_init_post_parse__', None) if post_init_original and post_init_original.__name__ == '_pydantic_post_init': post_init_original = None + + def _pydantic_post_init(self: 'DataclassType', *initvars: Any) -> None: + if post_init_original is not None: + post_init_original(self, *initvars) + d = validate_model(self.__pydantic_model__, self.__dict__, cls=self.__class__)[0] + object.__setattr__(self, '__dict__', d) + object.__setattr__(self, '__initialised__', True) + if post_init_post_parse is not None: + post_init_post_parse(self) + _cls.__post_init__ = _pydantic_post_init cls = dataclasses._process_class(_cls, init, repr, eq, order, unsafe_hash, frozen) # type: ignore @@ -82,8 +80,6 @@ def _process_class( field.name: (field.type, field.default if field.default != dataclasses.MISSING else Required) for field in dataclasses.fields(cls) } - cls.__post_init_original__ = post_init_original - cls.__post_init_post_parse__ = post_init_post_parse validators = gather_validators(cls) cls.__pydantic_model__ = create_model(
pydantic/pydantic
dd44fda8a6f6eed961cd03ad1e70049e523cdb40
However, calling `super().__post_init_original__()` instead of `super().__post_init__()` does seem to work as expected. Is this intended behavior? maybe be possible to fix this, but I can't look into this right now. PR welcome if you can resolve it. pydantic will replace user's `__post_init__` to `_pydantic_post_init` https://github.com/samuelcolvin/pydantic/blob/84820bdede195b36f6862b3978cf9e0814989f16/pydantic/dataclasses.py#L74-L78 And `_pydantic_post_init`, it will call origin `__post_init__` https://github.com/samuelcolvin/pydantic/blob/84820bdede195b36f6862b3978cf9e0814989f16/pydantic/dataclasses.py#L28-L30 From the above example code `__post_init__` in class `B` invokes `super().__post_init__()`, and it will invoke class `A`'s `_pydantic_post_init`, and pass instance `b` as `self` argument. So it will find class `B`'s `__post_init__` again. I think this is the root cause. `_pydantic_post_init` should find the origin `__post_init__` through the class, instead of instance. Here's a Way to Fix It. Move `_pydantic_post_init` to `_process_class`, use closure to capture user's `__post_init__`. But it will recreate `_pydantic_post_init` function object everytime. ```Diff diff --git a/pydantic/dataclasses.py b/pydantic/dataclasses.py index 4dbae31..c3b7546 100644 --- a/pydantic/dataclasses.py +++ b/pydantic/dataclasses.py @@ -25,16 +25,6 @@ if TYPE_CHECKING: # pragma: no cover pass -def _pydantic_post_init(self: 'DataclassType', *initvars: Any) -> None: - if self.__post_init_original__: - self.__post_init_original__(*initvars) - d = validate_model(self.__pydantic_model__, self.__dict__, cls=self.__class__)[0] - object.__setattr__(self, '__dict__', d) - object.__setattr__(self, '__initialised__', True) - if self.__post_init_post_parse__: - self.__post_init_post_parse__() - - def _validate_dataclass(cls: Type['DataclassType'], v: Any) -> 'DataclassType': if isinstance(v, cls): return v @@ -75,6 +65,16 @@ def _process_class( post_init_post_parse = getattr(_cls, '__post_init_post_parse__', None) if post_init_original and post_init_original.__name__ == '_pydantic_post_init': post_init_original = None + + def _pydantic_post_init(instance: 'DataclassType', *initvars: Any) -> None: + if post_init_original: + post_init_original(instance, *initvars) + d = validate_model(instance.__pydantic_model__, instance.__dict__, cls=instance.__class__)[0] + object.__setattr__(instance, '__dict__', d) + object.__setattr__(instance, '__initialised__', True) + if post_init_post_parse: + post_init_post_parse(instance) + _cls.__post_init__ = _pydantic_post_init cls = dataclasses._process_class(_cls, init, repr, eq, order, unsafe_hash, frozen) # type: ignore ``` I'm not sure I understand this, if you think there should be a change, please create a PR and we can discuss from there.
diff --git a/tests/test_dataclasses.py b/tests/test_dataclasses.py --- a/tests/test_dataclasses.py +++ b/tests/test_dataclasses.py @@ -108,6 +108,34 @@ def __post_init__(self): assert post_init_called +def test_post_init_inheritance_chain(): + parent_post_init_called = False + post_init_called = False + + @pydantic.dataclasses.dataclass + class ParentDataclass: + a: int + + def __post_init__(self): + nonlocal parent_post_init_called + parent_post_init_called = True + + @pydantic.dataclasses.dataclass + class MyDataclass(ParentDataclass): + b: int + + def __post_init__(self): + super().__post_init__() + nonlocal post_init_called + post_init_called = True + + d = MyDataclass(a=1, b=2) + assert d.a == 1 + assert d.b == 2 + assert parent_post_init_called + assert post_init_called + + def test_post_init_post_parse(): post_init_post_parse_called = False
Recursion issue with dataclass inheritance <!-- Questions, Feature Requests, and Bug Reports are all welcome --> <!-- delete as applicable: --> # Bug For bugs/questions: * OS: **Ubuntu 19.04** * Python version `3.7.3 (default, Mar 27 2019, 22:11:17) [GCC 7.3.0]` * Pydantic version `0.25` Where possible please include a self contained code snippet describing your bug, question, or where applicable feature request: ```py from pydantic.dataclasses import dataclass @dataclass class A: a: int def __post_init__(self): print("A") @dataclass class B(A): b: int def __post_init__(self): super().__post_init__() print("B") B(b=1, a=2) ``` **Expected Output**: ```py A B B(a=2, b=1) ``` <details><summary><strong>Current Error & Stacktrace</strong></summary> <p> ```py --------------------------------------------------------------------------- RecursionError Traceback (most recent call last) <ipython-input-28-55581d931e2a> in <module> ----> 1 B(b=1, a=2) <string> in __init__(self, a, b) [path_removed]/.venv/lib/python3.7/site-packages/pydantic/dataclasses.py in _pydantic_post_init(self) 30 object.__setattr__(self, '__initialised__', True) 31 if self.__post_init_original__: ---> 32 self.__post_init_original__() 33 34 <ipython-input-27-252024563a0b> in __post_init__(self) 11 12 def __post_init__(self): ---> 13 super().__post_init__() 14 print("B") ... last 2 frames repeated, from the frame below ... [path_removed]/.venv/lib/python3.7/site-packages/pydantic/dataclasses.py in _pydantic_post_init(self) 30 object.__setattr__(self, '__initialised__', True) 31 if self.__post_init_original__: ---> 32 self.__post_init_original__() 33 34 RecursionError: maximum recursion depth exceeded while calling a Python object ``` </p> </details>
0.0
dd44fda8a6f6eed961cd03ad1e70049e523cdb40
[ "tests/test_dataclasses.py::test_post_init_inheritance_chain" ]
[ "tests/test_dataclasses.py::test_simple", "tests/test_dataclasses.py::test_value_error", "tests/test_dataclasses.py::test_frozen", "tests/test_dataclasses.py::test_validate_assignment", "tests/test_dataclasses.py::test_validate_assignment_error", "tests/test_dataclasses.py::test_not_validate_assignment", "tests/test_dataclasses.py::test_post_init", "tests/test_dataclasses.py::test_post_init_post_parse", "tests/test_dataclasses.py::test_post_init_post_parse_types", "tests/test_dataclasses.py::test_post_init_assignment", "tests/test_dataclasses.py::test_inheritance", "tests/test_dataclasses.py::test_validate_long_string_error", "tests/test_dataclasses.py::test_validate_assigment_long_string_error", "tests/test_dataclasses.py::test_no_validate_assigment_long_string_error", "tests/test_dataclasses.py::test_nested_dataclass", "tests/test_dataclasses.py::test_arbitrary_types_allowed", "tests/test_dataclasses.py::test_nested_dataclass_model", "tests/test_dataclasses.py::test_fields", "tests/test_dataclasses.py::test_schema", "tests/test_dataclasses.py::test_nested_schema", "tests/test_dataclasses.py::test_initvar", "tests/test_dataclasses.py::test_derived_field_from_initvar", "tests/test_dataclasses.py::test_classvar" ]
{ "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-06-20 04:24:13+00:00
mit
4,893
pydantic__pydantic-610
diff --git a/pydantic/generics.py b/pydantic/generics.py --- a/pydantic/generics.py +++ b/pydantic/generics.py @@ -43,7 +43,7 @@ def __class_getitem__( # type: ignore model_name = concrete_name(cls, params) validators = gather_validators(cls) fields: Dict[str, Tuple[Type[Any], Any]] = { - k: (v, getattr(cls, k, ...)) for k, v in concrete_type_hints.items() + k: (v, cls.__fields__[k].default) for k, v in concrete_type_hints.items() if k in cls.__fields__ } created_model = create_model( model_name=model_name,
pydantic/pydantic
3ee54ed2bbd2cc31499312bca4cf767649cd4dae
diff --git a/tests/test_generics.py b/tests/test_generics.py --- a/tests/test_generics.py +++ b/tests/test_generics.py @@ -1,6 +1,6 @@ import sys from enum import Enum -from typing import Any, Dict, Generic, List, Optional, TypeVar, Union +from typing import Any, ClassVar, Dict, Generic, List, Optional, TypeVar, Union import pytest @@ -33,6 +33,31 @@ class Result(GenericModel, Generic[data_type]): assert str(exc_info.value) == 'Cannot parameterize a concrete instantiation of a generic model' +@skip_36 +def test_value_validation(): + T = TypeVar('T') + + class Response(GenericModel, Generic[T]): + data: T + + @validator('data') + def validate_value_nonzero(cls, v): + if isinstance(v, dict): + return v # ensure v is actually a value of the dict, not the dict itself + if v == 0: + raise ValueError('value is zero') + + with pytest.raises(ValidationError) as exc_info: + Response[Dict[int, int]](data={1: 'a'}) + assert exc_info.value.errors() == [ + {'loc': ('data', 1), 'msg': 'value is not a valid integer', 'type': 'type_error.integer'} + ] + + with pytest.raises(ValidationError) as exc_info: + Response[Dict[int, int]](data={1: 0}) + assert exc_info.value.errors() == [{'loc': ('data', 1), 'msg': 'value is zero', 'type': 'value_error'}] + + @skip_36 def test_methods_are_inherited(): class CustomGenericModel(GenericModel): @@ -68,6 +93,64 @@ class Model(CustomGenericModel, Generic[T]): assert str(exc_info.value) == '"Model[int]" is immutable and does not support item assignment' +@skip_36 +def test_default_argument(): + T = TypeVar('T') + + class Result(GenericModel, Generic[T]): + data: T + other: bool = True + + result = Result[int](data=1) + assert result.other is True + + +@skip_36 +def test_default_argument_for_typevar(): + T = TypeVar('T') + + class Result(GenericModel, Generic[T]): + data: T = 4 + + result = Result[int]() + assert result.data == 4 + + result = Result[float]() + assert result.data == 4 + + result = Result[int](data=1) + assert result.data == 1 + + +@skip_36 +def test_classvar(): + T = TypeVar('T') + + class Result(GenericModel, Generic[T]): + data: T + other: ClassVar[int] = 1 + + assert Result.other == 1 + assert Result[int].other == 1 + assert Result[int](data=1).other == 1 + assert 'other' not in Result.__fields__ + + +@skip_36 +def test_non_annotated_field(): + T = TypeVar('T') + + class Result(GenericModel, Generic[T]): + data: T + other = True + + assert 'other' in Result.__fields__ + assert 'other' in Result[int].__fields__ + + result = Result[int](data=1) + assert result.other is True + + @skip_36 def test_must_inherit_from_generic(): with pytest.raises(TypeError) as exc_info:
Default values ignored for GenericModel # Bug * Python version: 3.7 * Pydantic version: 0.29 This test fails: ```python def test_default_arguments(): T = TypeVar('T') class Result(GenericModel, Generic[T]): data: T other: bool = True result = Result[int](data=1) ``` with result: ``` E pydantic.error_wrappers.ValidationError: 1 validation error E other E field required (type=value_error.missing) ``` I have a simple patch to fix this and will submit it shortly.
0.0
3ee54ed2bbd2cc31499312bca4cf767649cd4dae
[ "tests/test_generics.py::test_default_argument", "tests/test_generics.py::test_default_argument_for_typevar" ]
[ "tests/test_generics.py::test_generic_name", "tests/test_generics.py::test_double_parameterize_error", "tests/test_generics.py::test_value_validation", "tests/test_generics.py::test_methods_are_inherited", "tests/test_generics.py::test_config_is_inherited", "tests/test_generics.py::test_classvar", "tests/test_generics.py::test_non_annotated_field", "tests/test_generics.py::test_must_inherit_from_generic", "tests/test_generics.py::test_parameters_must_be_typevar", "tests/test_generics.py::test_parameter_count", "tests/test_generics.py::test_cover_cache", "tests/test_generics.py::test_generic_config", "tests/test_generics.py::test_generic_instantiation_error", "tests/test_generics.py::test_parameterized_generic_instantiation_error", "tests/test_generics.py::test_deep_generic", "tests/test_generics.py::test_enum_generic", "tests/test_generics.py::test_generic" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2019-06-21 04:47:58+00:00
mit
4,894
pydantic__pydantic-611
diff --git a/pydantic/utils.py b/pydantic/utils.py --- a/pydantic/utils.py +++ b/pydantic/utils.py @@ -160,7 +160,10 @@ def truncate(v: Union[str], *, max_len: int = 80) -> str: if isinstance(v, str) and len(v) > (max_len - 2): # -3 so quote + string + … + quote has correct length return (v[: (max_len - 3)] + '…').__repr__() - v = v.__repr__() + try: + v = v.__repr__() + except TypeError: + v = type(v).__repr__(v) # in case v is a type if len(v) > max_len: v = v[: max_len - 1] + '…' return v
pydantic/pydantic
3f754c8cbd4ab1f28009b83560ed350236b241f3
diff --git a/tests/test_utils.py b/tests/test_utils.py --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -4,7 +4,7 @@ import pytest -from pydantic.utils import display_as_type, import_string, lenient_issubclass, make_dsn, validate_email +from pydantic.utils import display_as_type, import_string, lenient_issubclass, make_dsn, truncate, validate_email try: import email_validator @@ -146,3 +146,7 @@ class A(str): def test_lenient_issubclass_is_lenient(): assert lenient_issubclass('a', 'a') is False + + +def test_truncate_type(): + assert truncate(object) == "<class 'object'>"
Call repr on model with class type field will cause exception I define a model with class type field. It will raise exception when calling repr on this model. env: python version: ``3.6.4`` pydantic version: ``0.28`` code: ```py import inspect from pydantic import BaseSettings class TestClass(object): pass class TestModel(object): @classmethod def __get_validators__(cls): yield cls.validate @classmethod def validate(cls, v): if not (inspect.isclass(v) and issubclass(v, TestClass)): raise ValueError(f'TestClass expected not {type(v)}') return v class TestSettings(BaseSettings): cls: TestModel = None # this line will raise exception print(TestSettings(cls=TestClass)) ``` exception: ``` Traceback (most recent call last): File "test.py", line 23, in <module> print(TestSettings(cls=TestClass)) File "pydantic/main.py", line 534, in pydantic.main.BaseModel.__str__ File "pydantic/main.py", line 530, in genexpr File "pydantic/main.py", line 530, in genexpr File "pydantic/utils.py", line 158, in pydantic.utils.truncate TypeError: descriptor '__repr__' of 'object' object needs an argument ``` I think the problem is the class object ``__repr__`` property is not callable. [pydantic/utils.py :158](https://github.com/samuelcolvin/pydantic/blob/dd44fda8a6f6eed961cd03ad1e70049e523cdb40/pydantic/utils.py#L158) ``` def truncate(v: Union[str], *, max_len: int = 80) -> str: """ Truncate a value and add a unicode ellipsis (three dots) to the end if it was too long """ if isinstance(v, str) and len(v) > (max_len - 2): # -3 so quote + string + … + quote has correct length return (v[: (max_len - 3)] + '…').__repr__() v = v.__repr__() if len(v) > max_len: v = v[: max_len - 1] + '…' return v ``` Call repr on model with class type field will cause exception I define a model with class type field. It will raise exception when calling repr on this model. env: python version: ``3.6.4`` pydantic version: ``0.28`` code: ```py import inspect from pydantic import BaseSettings class TestClass(object): pass class TestModel(object): @classmethod def __get_validators__(cls): yield cls.validate @classmethod def validate(cls, v): if not (inspect.isclass(v) and issubclass(v, TestClass)): raise ValueError(f'TestClass expected not {type(v)}') return v class TestSettings(BaseSettings): cls: TestModel = None # this line will raise exception print(TestSettings(cls=TestClass)) ``` exception: ``` Traceback (most recent call last): File "test.py", line 23, in <module> print(TestSettings(cls=TestClass)) File "pydantic/main.py", line 534, in pydantic.main.BaseModel.__str__ File "pydantic/main.py", line 530, in genexpr File "pydantic/main.py", line 530, in genexpr File "pydantic/utils.py", line 158, in pydantic.utils.truncate TypeError: descriptor '__repr__' of 'object' object needs an argument ``` I think the problem is the class object ``__repr__`` property is not callable. [pydantic/utils.py :158](https://github.com/samuelcolvin/pydantic/blob/dd44fda8a6f6eed961cd03ad1e70049e523cdb40/pydantic/utils.py#L158) ``` def truncate(v: Union[str], *, max_len: int = 80) -> str: """ Truncate a value and add a unicode ellipsis (three dots) to the end if it was too long """ if isinstance(v, str) and len(v) > (max_len - 2): # -3 so quote + string + … + quote has correct length return (v[: (max_len - 3)] + '…').__repr__() v = v.__repr__() if len(v) > max_len: v = v[: max_len - 1] + '…' return v ```
0.0
3f754c8cbd4ab1f28009b83560ed350236b241f3
[ "tests/test_utils.py::test_truncate_type" ]
[ "tests/test_utils.py::test_address_valid[[email protected]@example.com]", "tests/test_utils.py::test_address_valid[[email protected]@muelcolvin.com]", "tests/test_utils.py::test_address_valid[Samuel", "tests/test_utils.py::test_address_valid[foobar", "tests/test_utils.py::test_address_valid[", "tests/test_utils.py::test_address_valid[[email protected]", "tests/test_utils.py::test_address_valid[foo", "tests/test_utils.py::test_address_valid[FOO", "tests/test_utils.py::test_address_valid[<[email protected]>", "tests/test_utils.py::test_address_valid[\\xf1o\\xf1\\[email protected]\\xf1o\\xf1\\xf3-\\xf1o\\xf1\\[email protected]]", "tests/test_utils.py::test_address_valid[\\u6211\\[email protected]\\u6211\\u8cb7-\\u6211\\[email protected]]", "tests/test_utils.py::test_address_valid[\\u7532\\u6590\\u9ed2\\u5ddd\\u65e5\\[email protected]\\u7532\\u6590\\u9ed2\\u5ddd\\u65e5\\u672c-\\u7532\\u6590\\u9ed2\\u5ddd\\u65e5\\[email protected]]", "tests/test_utils.py::test_address_valid[\\u0447\\u0435\\u0431\\u0443\\u0440\\u0430\\u0448\\u043a\\u0430\\u044f\\u0449\\u0438\\u043a-\\u0441-\\u0430\\u043f\\u0435\\u043b\\u044c\\u0441\\u0438\\u043d\\u0430\\u043c\\u0438.\\u0440\\[email protected]\\u0447\\u0435\\u0431\\u0443\\u0440\\u0430\\u0448\\u043a\\u0430\\u044f\\u0449\\u0438\\u043a-\\u0441-\\u0430\\u043f\\u0435\\u043b\\u044c\\u0441\\u0438\\u043d\\u0430\\u043c\\u0438.\\u0440\\u0444-\\u0447\\u0435\\u0431\\u0443\\u0440\\u0430\\u0448\\u043a\\u0430\\u044f\\u0449\\u0438\\u043a-\\u0441-\\u0430\\u043f\\u0435\\u043b\\u044c\\u0441\\u0438\\u043d\\u0430\\u043c\\u0438.\\u0440\\[email protected]]", "tests/test_utils.py::test_address_valid[\\u0909\\u0926\\u093e\\u0939\\u0930\\u0923.\\u092a\\u0930\\u0940\\u0915\\u094d\\[email protected]\\u0909\\u0926\\u093e\\u0939\\u0930\\u0923.\\u092a\\u0930\\u0940\\u0915\\u094d\\u0937-\\u0909\\u0926\\u093e\\u0939\\u0930\\u0923.\\u092a\\u0930\\u0940\\u0915\\u094d\\[email protected]]", "tests/test_utils.py::test_address_valid[[email protected]@example.com]", "tests/test_utils.py::test_address_valid[[email protected]", "tests/test_utils.py::test_address_valid[\\u03b9\\u03c9\\u03ac\\u03bd\\u03bd\\u03b7\\u03c2@\\u03b5\\u03b5\\u03c4\\u03c4.gr-\\u03b9\\u03c9\\u03ac\\u03bd\\u03bd\\u03b7\\u03c2-\\u03b9\\u03c9\\u03ac\\u03bd\\u03bd\\u03b7\\u03c2@\\u03b5\\u03b5\\u03c4\\u03c4.gr]", "tests/test_utils.py::test_address_invalid[f", "tests/test_utils.py::test_address_invalid[foo.bar@exam\\nple.com", "tests/test_utils.py::test_address_invalid[foobar]", "tests/test_utils.py::test_address_invalid[foobar", "tests/test_utils.py::test_address_invalid[@example.com]", "tests/test_utils.py::test_address_invalid[[email protected]]", "tests/test_utils.py::test_address_invalid[[email protected]]", "tests/test_utils.py::test_address_invalid[foo", "tests/test_utils.py::test_address_invalid[foo@[email protected]]", "tests/test_utils.py::test_address_invalid[\\[email protected]]", "tests/test_utils.py::test_address_invalid[\\[email protected]]", "tests/test_utils.py::test_address_invalid[\\[email protected]]", "tests/test_utils.py::test_address_invalid[", "tests/test_utils.py::test_address_invalid[\\[email protected]]", "tests/test_utils.py::test_address_invalid[\"@example.com0]", "tests/test_utils.py::test_address_invalid[\"@example.com1]", "tests/test_utils.py::test_address_invalid[,@example.com]", "tests/test_utils.py::test_empty_dsn", "tests/test_utils.py::test_dsn_odd_user", "tests/test_utils.py::test_import_module", "tests/test_utils.py::test_import_module_invalid", "tests/test_utils.py::test_import_no_attr", "tests/test_utils.py::test_display_as_type[str-str]", "tests/test_utils.py::test_display_as_type[string-str]", "tests/test_utils.py::test_display_as_type[value2-typing.Union[str,", "tests/test_utils.py::test_display_as_type_enum", "tests/test_utils.py::test_display_as_type_enum_int", "tests/test_utils.py::test_display_as_type_enum_str", "tests/test_utils.py::test_lenient_issubclass", "tests/test_utils.py::test_lenient_issubclass_is_lenient" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2019-06-21 06:43:33+00:00
mit
4,895
pydantic__pydantic-6194
diff --git a/pydantic/validators.py b/pydantic/validators.py --- a/pydantic/validators.py +++ b/pydantic/validators.py @@ -488,7 +488,7 @@ def make_literal_validator(type_: Any) -> Callable[[Any], Any]: def literal_validator(v: Any) -> Any: try: return allowed_choices[v] - except KeyError: + except (KeyError, TypeError): raise errors.WrongConstantError(given=v, permitted=permitted_choices) return literal_validator
pydantic/pydantic
ccedd746de49179fe835610f793459b84fb9f754
Thanks @markus1978 for reporting. Would you like to open a PR for fixing? @hramezani > Would you like to open a PR for fixing? Sure. I guess, I should base of and target `1.10.X-fixes`? > @hramezani > > > Would you like to open a PR for fixing? > > Sure. I guess, I should base of and target `1.10.X-fixes`? Yes
diff --git a/tests/test_validators.py b/tests/test_validators.py --- a/tests/test_validators.py +++ b/tests/test_validators.py @@ -1189,6 +1189,24 @@ class Model(BaseModel): ] +def test_literal_validator_non_str_value(): + class Model(BaseModel): + a: Literal['foo'] + + Model(a='foo') + + with pytest.raises(ValidationError) as exc_info: + Model(a={'bar': 'foo'}) + assert exc_info.value.errors() == [ + { + 'loc': ('a',), + 'msg': "unexpected value; permitted: 'foo'", + 'type': 'value_error.const', + 'ctx': {'given': {'bar': 'foo'}, 'permitted': ('foo',)}, + } + ] + + def test_literal_validator_str_enum(): class Bar(str, Enum): FIZ = 'fiz'
Validating a dict value agains a Literal type gives the wrong ValidationError ### Initial Checks - [X] I have searched GitHub for a duplicate issue and I'm sure this is something new - [X] I have searched Google & StackOverflow for a solution and couldn't find anything - [X] I have read and followed [the docs](https://docs.pydantic.dev) and still think this is a bug - [X] I am confident that the issue is with pydantic (not my code, or another library in the ecosystem like [FastAPI](https://fastapi.tiangolo.com) or [mypy](https://mypy.readthedocs.io/en/stable)) ### Description Validating a dict value agains a Literal type gives the wrong ValidationError. Instead of `unexpected value; permitted: '*'` the validation error just says `unhashable type: 'dict' (type=type_error)`. Which does not describe the problem and is confusing, e.g. if handing this to API users in fastAPI. I would also expect an `unexpected value; permitted: '*'` for all non string values. The respective validator in `pydantic/validators.py` (line 480ff) only catches a KeyError: ```py def make_literal_validator(type_: Any) -> Callable[[Any], Any]: permitted_choices = all_literal_values(type_) # To have a O(1) complexity and still return one of the values set inside the `Literal`, # we create a dict with the set values (a set causes some problems with the way intersection works). # In some cases the set value and checked value can indeed be different (see `test_literal_validator_str_enum`) allowed_choices = {v: v for v in permitted_choices} def literal_validator(v: Any) -> Any: try: return allowed_choices[v] except KeyError: raise errors.WrongConstantError(given=v, permitted=permitted_choices) return literal_validator ``` IMHO, it should also catch a `TypeError` (i.e. the "unhashable type") and produce a corresponding error. Or, it could check for `isinstance(v, str)` first and raise respective error if it is not a string. ### Example Code ```Python import pydantic from typing import Literal pydantic.parse_obj_as(Literal['*'], {}) ``` ### Python, Pydantic & OS Version ```Text pydantic version: 1.10.9 pydantic compiled: True install path: ********.pyenv/lib/python3.9/site-packages/pydantic python version: 3.9.16 (main, Dec 7 2022, 10:16:11) [Clang 14.0.0 (clang-1400.0.29.202)] platform: macOS-13.2-x86_64-i386-64bit optional deps. installed: ['devtools', 'dotenv', 'email-validator', 'typing-extensions'] ``` ### Affected Components - [ ] [Compatibility between releases](https://docs.pydantic.dev/changelog/) - [X] [Data validation/parsing](https://docs.pydantic.dev/usage/models/#basic-model-usage) - [ ] [Data serialization](https://docs.pydantic.dev/usage/exporting_models/) - `.dict()` and `.json()` - [ ] [JSON Schema](https://docs.pydantic.dev/usage/schema/) - [ ] [Dataclasses](https://docs.pydantic.dev/usage/dataclasses/) - [ ] [Model Config](https://docs.pydantic.dev/usage/model_config/) - [ ] [Field Types](https://docs.pydantic.dev/usage/types/) - adding or changing a particular data type - [ ] [Function validation decorator](https://docs.pydantic.dev/usage/validation_decorator/) - [ ] [Generic Models](https://docs.pydantic.dev/usage/models/#generic-models) - [ ] [Other Model behaviour](https://docs.pydantic.dev/usage/models/) - `construct()`, pickling, private attributes, ORM mode - [ ] [Plugins](https://docs.pydantic.dev/) and integration with other tools - mypy, FastAPI, python-devtools, Hypothesis, VS Code, PyCharm, etc.
0.0
ccedd746de49179fe835610f793459b84fb9f754
[ "tests/test_validators.py::test_literal_validator_non_str_value" ]
[ "tests/test_validators.py::test_simple", "tests/test_validators.py::test_int_validation", "tests/test_validators.py::test_int_overflow_validation[inf0]", "tests/test_validators.py::test_int_overflow_validation[nan]", "tests/test_validators.py::test_int_overflow_validation[inf1]", "tests/test_validators.py::test_frozenset_validation", "tests/test_validators.py::test_deque_validation", "tests/test_validators.py::test_validate_whole", "tests/test_validators.py::test_validate_kwargs", "tests/test_validators.py::test_validate_pre_error", "tests/test_validators.py::test_validating_assignment_ok", "tests/test_validators.py::test_validating_assignment_fail", "tests/test_validators.py::test_validating_assignment_value_change", "tests/test_validators.py::test_validating_assignment_extra", "tests/test_validators.py::test_validating_assignment_dict", "tests/test_validators.py::test_validating_assignment_values_dict", "tests/test_validators.py::test_validate_multiple", "tests/test_validators.py::test_classmethod", "tests/test_validators.py::test_duplicates", "tests/test_validators.py::test_use_bare", "tests/test_validators.py::test_use_no_fields", "tests/test_validators.py::test_validate_always", "tests/test_validators.py::test_validate_always_on_inheritance", "tests/test_validators.py::test_validate_not_always", "tests/test_validators.py::test_wildcard_validators", "tests/test_validators.py::test_wildcard_validator_error", "tests/test_validators.py::test_invalid_field", "tests/test_validators.py::test_validate_child", "tests/test_validators.py::test_validate_child_extra", "tests/test_validators.py::test_validate_child_all", "tests/test_validators.py::test_validate_parent", "tests/test_validators.py::test_validate_parent_all", "tests/test_validators.py::test_inheritance_keep", "tests/test_validators.py::test_inheritance_replace", "tests/test_validators.py::test_inheritance_new", "tests/test_validators.py::test_validation_each_item", "tests/test_validators.py::test_validation_each_item_one_sublevel", "tests/test_validators.py::test_key_validation", "tests/test_validators.py::test_validator_always_optional", "tests/test_validators.py::test_validator_always_pre", "tests/test_validators.py::test_validator_always_post", "tests/test_validators.py::test_validator_always_post_optional", "tests/test_validators.py::test_validator_bad_fields_throws_configerror", "tests/test_validators.py::test_datetime_validator", "tests/test_validators.py::test_pre_called_once", "tests/test_validators.py::test_make_generic_validator[fields0-_v_]", "tests/test_validators.py::test_make_generic_validator[fields1-_v_]", "tests/test_validators.py::test_make_generic_validator[fields2-_v_,_field_]", "tests/test_validators.py::test_make_generic_validator[fields3-_v_,_config_]", "tests/test_validators.py::test_make_generic_validator[fields4-_v_,_values_]", "tests/test_validators.py::test_make_generic_validator[fields5-_v_,_field_,_config_]", "tests/test_validators.py::test_make_generic_validator[fields6-_v_,_field_,_values_]", "tests/test_validators.py::test_make_generic_validator[fields7-_v_,_config_,_values_]", "tests/test_validators.py::test_make_generic_validator[fields8-_v_,_field_,_values_,_config_]", "tests/test_validators.py::test_make_generic_validator[fields9-_cls_,_v_]", "tests/test_validators.py::test_make_generic_validator[fields10-_cls_,_v_]", "tests/test_validators.py::test_make_generic_validator[fields11-_cls_,_v_,_field_]", "tests/test_validators.py::test_make_generic_validator[fields12-_cls_,_v_,_config_]", "tests/test_validators.py::test_make_generic_validator[fields13-_cls_,_v_,_values_]", "tests/test_validators.py::test_make_generic_validator[fields14-_cls_,_v_,_field_,_config_]", "tests/test_validators.py::test_make_generic_validator[fields15-_cls_,_v_,_field_,_values_]", "tests/test_validators.py::test_make_generic_validator[fields16-_cls_,_v_,_config_,_values_]", "tests/test_validators.py::test_make_generic_validator[fields17-_cls_,_v_,_field_,_values_,_config_]", "tests/test_validators.py::test_make_generic_validator_kwargs", "tests/test_validators.py::test_make_generic_validator_invalid", "tests/test_validators.py::test_make_generic_validator_cls_kwargs", "tests/test_validators.py::test_make_generic_validator_cls_invalid", "tests/test_validators.py::test_make_generic_validator_self", "tests/test_validators.py::test_assert_raises_validation_error", "tests/test_validators.py::test_whole", "tests/test_validators.py::test_root_validator", "tests/test_validators.py::test_root_validator_pre", "tests/test_validators.py::test_root_validator_repeat", "tests/test_validators.py::test_root_validator_repeat2", "tests/test_validators.py::test_root_validator_self", "tests/test_validators.py::test_root_validator_extra", "tests/test_validators.py::test_root_validator_types", "tests/test_validators.py::test_root_validator_inheritance", "tests/test_validators.py::test_root_validator_returns_none_exception", "tests/test_validators.py::test_reuse_global_validators", "tests/test_validators.py::test_allow_reuse[True-True-True-True]", "tests/test_validators.py::test_allow_reuse[True-True-True-False]", "tests/test_validators.py::test_allow_reuse[True-True-False-True]", "tests/test_validators.py::test_allow_reuse[True-True-False-False]", "tests/test_validators.py::test_allow_reuse[True-False-True-True]", "tests/test_validators.py::test_allow_reuse[True-False-True-False]", "tests/test_validators.py::test_allow_reuse[True-False-False-True]", "tests/test_validators.py::test_allow_reuse[True-False-False-False]", "tests/test_validators.py::test_allow_reuse[False-True-True-True]", "tests/test_validators.py::test_allow_reuse[False-True-True-False]", "tests/test_validators.py::test_allow_reuse[False-True-False-True]", "tests/test_validators.py::test_allow_reuse[False-True-False-False]", "tests/test_validators.py::test_allow_reuse[False-False-True-True]", "tests/test_validators.py::test_allow_reuse[False-False-True-False]", "tests/test_validators.py::test_allow_reuse[False-False-False-True]", "tests/test_validators.py::test_allow_reuse[False-False-False-False]", "tests/test_validators.py::test_root_validator_classmethod[True-True]", "tests/test_validators.py::test_root_validator_classmethod[True-False]", "tests/test_validators.py::test_root_validator_classmethod[False-True]", "tests/test_validators.py::test_root_validator_classmethod[False-False]", "tests/test_validators.py::test_root_validator_skip_on_failure", "tests/test_validators.py::test_assignment_validator_cls", "tests/test_validators.py::test_literal_validator", "tests/test_validators.py::test_literal_validator_str_enum", "tests/test_validators.py::test_nested_literal_validator", "tests/test_validators.py::test_union_literal_with_constraints", "tests/test_validators.py::test_field_that_is_being_validated_is_excluded_from_validator_values", "tests/test_validators.py::test_exceptions_in_field_validators_restore_original_field_value", "tests/test_validators.py::test_overridden_root_validators", "tests/test_validators.py::test_list_unique_items_with_optional", "tests/test_validators.py::test_functool_as_validator[`partial`", "tests/test_validators.py::test_functool_as_validator[`partialmethod`" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2023-06-20 10:52:05+00:00
mit
4,896
pydantic__pydantic-625
diff --git a/pydantic/schema.py b/pydantic/schema.py --- a/pydantic/schema.py +++ b/pydantic/schema.py @@ -4,7 +4,7 @@ from decimal import Decimal from enum import Enum from pathlib import Path -from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Sequence, Set, Tuple, Type, Union, cast +from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Sequence, Set, Tuple, Type, TypeVar, Union, cast from uuid import UUID import pydantic @@ -731,7 +731,7 @@ def field_singleton_schema( # noqa: C901 (ignore complexity) ref_prefix=ref_prefix, known_models=known_models, ) - if field.type_ is Any: + if field.type_ is Any or type(field.type_) == TypeVar: return {}, definitions, nested_models # no restrictions if is_callable_type(field.type_): raise SkipField(f'Callable {field.name} was excluded from schema since JSON schema has no equivalent type.')
pydantic/pydantic
3cdbbaee953639ba1bd99a7eab761b987af626ef
The solution is to allow naked `Dict` and treat it like `dict`. This was referenced at https://github.com/samuelcolvin/pydantic/issues/545#issuecomment-495943391 PR welcome to fix this. The solution is to allow naked `Dict` and treat it like `dict`. This was referenced at https://github.com/samuelcolvin/pydantic/issues/545#issuecomment-495943391 PR welcome to fix this.
diff --git a/tests/test_schema.py b/tests/test_schema.py --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -11,7 +11,13 @@ import pytest from pydantic import BaseModel, Schema, ValidationError, validator -from pydantic.schema import get_flat_models_from_model, get_flat_models_from_models, get_model_name_map, schema +from pydantic.schema import ( + get_flat_models_from_model, + get_flat_models_from_models, + get_model_name_map, + model_schema, + schema, +) from pydantic.types import ( DSN, UUID1, @@ -1303,6 +1309,45 @@ def check_field(cls, v, *, values, config, field): } +def test_unparameterized_schema_generation(): + class FooList(BaseModel): + d: List + + class BarList(BaseModel): + d: list + + assert model_schema(FooList) == { + 'title': 'FooList', + 'type': 'object', + 'properties': {'d': {'items': {}, 'title': 'D', 'type': 'array'}}, + 'required': ['d'], + } + + foo_list_schema = model_schema(FooList) + bar_list_schema = model_schema(BarList) + bar_list_schema['title'] = 'FooList' # to check for equality + assert foo_list_schema == bar_list_schema + + class FooDict(BaseModel): + d: Dict + + class BarDict(BaseModel): + d: dict + + model_schema(Foo) + assert model_schema(FooDict) == { + 'title': 'FooDict', + 'type': 'object', + 'properties': {'d': {'title': 'D', 'type': 'object'}}, + 'required': ['d'], + } + + foo_dict_schema = model_schema(FooDict) + bar_dict_schema = model_schema(BarDict) + bar_dict_schema['title'] = 'FooDict' # to check for equality + assert foo_dict_schema == bar_dict_schema + + def test_known_model_optimization(): class Dep(BaseModel): number: int
Possible to give a more useful error message on partial type? # Feature Request Is it possible to give a more useful error message on partial type? I think my code here is incorrect because I've not specified the parameters to `typing.Dict`, but would it be possible for this to give a more useful error message than "TypeError: issubclass() arg 1 must be a class"? ```py from typing import Any, Dict import pydantic from pydantic.schema import model_schema class Foo(pydantic.BaseModel): d: Dict # should be # d: Dict[Any, Any] model_schema(Foo) ``` ``` TypeError: issubclass() arg 1 must be a class ``` Possible to give a more useful error message on partial type? # Feature Request Is it possible to give a more useful error message on partial type? I think my code here is incorrect because I've not specified the parameters to `typing.Dict`, but would it be possible for this to give a more useful error message than "TypeError: issubclass() arg 1 must be a class"? ```py from typing import Any, Dict import pydantic from pydantic.schema import model_schema class Foo(pydantic.BaseModel): d: Dict # should be # d: Dict[Any, Any] model_schema(Foo) ``` ``` TypeError: issubclass() arg 1 must be a class ```
0.0
3cdbbaee953639ba1bd99a7eab761b987af626ef
[ "tests/test_schema.py::test_unparameterized_schema_generation" ]
[ "tests/test_schema.py::test_key", "tests/test_schema.py::test_by_alias", "tests/test_schema.py::test_sub_model", "tests/test_schema.py::test_schema_class", "tests/test_schema.py::test_schema_repr", "tests/test_schema.py::test_schema_class_by_alias", "tests/test_schema.py::test_choices", "tests/test_schema.py::test_json_schema", "tests/test_schema.py::test_list_sub_model", "tests/test_schema.py::test_optional", "tests/test_schema.py::test_any", "tests/test_schema.py::test_set", "tests/test_schema.py::test_const_str", "tests/test_schema.py::test_const_false", "tests/test_schema.py::test_tuple[tuple-expected_schema0]", "tests/test_schema.py::test_tuple[field_type1-expected_schema1]", "tests/test_schema.py::test_tuple[field_type2-expected_schema2]", "tests/test_schema.py::test_bool", "tests/test_schema.py::test_strict_bool", "tests/test_schema.py::test_dict", "tests/test_schema.py::test_list", "tests/test_schema.py::test_list_union_dict[field_type0-expected_schema0]", "tests/test_schema.py::test_list_union_dict[field_type1-expected_schema1]", "tests/test_schema.py::test_list_union_dict[field_type2-expected_schema2]", "tests/test_schema.py::test_list_union_dict[field_type3-expected_schema3]", "tests/test_schema.py::test_list_union_dict[field_type4-expected_schema4]", "tests/test_schema.py::test_date_types[datetime-expected_schema0]", "tests/test_schema.py::test_date_types[date-expected_schema1]", "tests/test_schema.py::test_date_types[time-expected_schema2]", "tests/test_schema.py::test_date_types[timedelta-expected_schema3]", "tests/test_schema.py::test_str_basic_types[field_type0-expected_schema0]", "tests/test_schema.py::test_str_basic_types[field_type1-expected_schema1]", "tests/test_schema.py::test_str_basic_types[field_type2-expected_schema2]", "tests/test_schema.py::test_str_basic_types[field_type3-expected_schema3]", "tests/test_schema.py::test_str_constrained_types[StrictStr-expected_schema0]", "tests/test_schema.py::test_str_constrained_types[ConstrainedStr-expected_schema1]", "tests/test_schema.py::test_str_constrained_types[ConstrainedStrValue-expected_schema2]", "tests/test_schema.py::test_special_str_types[UrlStr-expected_schema0]", "tests/test_schema.py::test_special_str_types[UrlStrValue-expected_schema1]", "tests/test_schema.py::test_special_str_types[DSN-expected_schema2]", "tests/test_schema.py::test_email_str_types[EmailStr-email]", "tests/test_schema.py::test_email_str_types[NameEmail-name-email]", "tests/test_schema.py::test_secret_types[SecretBytes-string]", "tests/test_schema.py::test_secret_types[SecretStr-string]", "tests/test_schema.py::test_special_int_types[ConstrainedInt-expected_schema0]", "tests/test_schema.py::test_special_int_types[ConstrainedIntValue-expected_schema1]", "tests/test_schema.py::test_special_int_types[ConstrainedIntValue-expected_schema2]", "tests/test_schema.py::test_special_int_types[ConstrainedIntValue-expected_schema3]", "tests/test_schema.py::test_special_int_types[PositiveInt-expected_schema4]", "tests/test_schema.py::test_special_int_types[NegativeInt-expected_schema5]", "tests/test_schema.py::test_special_float_types[ConstrainedFloat-expected_schema0]", "tests/test_schema.py::test_special_float_types[ConstrainedFloatValue-expected_schema1]", "tests/test_schema.py::test_special_float_types[ConstrainedFloatValue-expected_schema2]", "tests/test_schema.py::test_special_float_types[ConstrainedFloatValue-expected_schema3]", "tests/test_schema.py::test_special_float_types[PositiveFloat-expected_schema4]", "tests/test_schema.py::test_special_float_types[NegativeFloat-expected_schema5]", "tests/test_schema.py::test_special_float_types[ConstrainedDecimal-expected_schema6]", "tests/test_schema.py::test_special_float_types[ConstrainedDecimalValue-expected_schema7]", "tests/test_schema.py::test_special_float_types[ConstrainedDecimalValue-expected_schema8]", "tests/test_schema.py::test_special_float_types[ConstrainedDecimalValue-expected_schema9]", "tests/test_schema.py::test_uuid_types[UUID-uuid]", "tests/test_schema.py::test_uuid_types[UUID1-uuid1]", "tests/test_schema.py::test_uuid_types[UUID3-uuid3]", "tests/test_schema.py::test_uuid_types[UUID4-uuid4]", "tests/test_schema.py::test_uuid_types[UUID5-uuid5]", "tests/test_schema.py::test_path_types[FilePath-file-path]", "tests/test_schema.py::test_path_types[DirectoryPath-directory-path]", "tests/test_schema.py::test_path_types[Path-path]", "tests/test_schema.py::test_json_type", "tests/test_schema.py::test_ipv4address_type", "tests/test_schema.py::test_ipv6address_type", "tests/test_schema.py::test_ipvanyaddress_type", "tests/test_schema.py::test_ipv4interface_type", "tests/test_schema.py::test_ipv6interface_type", "tests/test_schema.py::test_ipvanyinterface_type", "tests/test_schema.py::test_ipv4network_type", "tests/test_schema.py::test_ipv6network_type", "tests/test_schema.py::test_ipvanynetwork_type", "tests/test_schema.py::test_callable_type[annotation0]", "tests/test_schema.py::test_callable_type[annotation1]", "tests/test_schema.py::test_error_non_supported_types", "tests/test_schema.py::test_flat_models_unique_models", "tests/test_schema.py::test_flat_models_with_submodels", "tests/test_schema.py::test_flat_models_with_submodels_from_sequence", "tests/test_schema.py::test_model_name_maps", "tests/test_schema.py::test_schema_overrides", "tests/test_schema.py::test_schema_from_models", "tests/test_schema.py::test_schema_with_ref_prefix", "tests/test_schema.py::test_schema_no_definitions", "tests/test_schema.py::test_list_default", "tests/test_schema.py::test_dict_default", "tests/test_schema.py::test_constraints_schema[kwargs0-str-expected_extra0]", "tests/test_schema.py::test_constraints_schema[kwargs1-ConstrainedStrValue-expected_extra1]", "tests/test_schema.py::test_constraints_schema[kwargs2-str-expected_extra2]", "tests/test_schema.py::test_constraints_schema[kwargs3-bytes-expected_extra3]", "tests/test_schema.py::test_constraints_schema[kwargs4-str-expected_extra4]", "tests/test_schema.py::test_constraints_schema[kwargs5-int-expected_extra5]", "tests/test_schema.py::test_constraints_schema[kwargs6-int-expected_extra6]", "tests/test_schema.py::test_constraints_schema[kwargs7-int-expected_extra7]", "tests/test_schema.py::test_constraints_schema[kwargs8-int-expected_extra8]", "tests/test_schema.py::test_constraints_schema[kwargs9-int-expected_extra9]", "tests/test_schema.py::test_constraints_schema[kwargs10-float-expected_extra10]", "tests/test_schema.py::test_constraints_schema[kwargs11-float-expected_extra11]", "tests/test_schema.py::test_constraints_schema[kwargs12-float-expected_extra12]", "tests/test_schema.py::test_constraints_schema[kwargs13-float-expected_extra13]", "tests/test_schema.py::test_constraints_schema[kwargs14-float-expected_extra14]", "tests/test_schema.py::test_constraints_schema[kwargs15-Decimal-expected_extra15]", "tests/test_schema.py::test_constraints_schema[kwargs16-Decimal-expected_extra16]", "tests/test_schema.py::test_constraints_schema[kwargs17-Decimal-expected_extra17]", "tests/test_schema.py::test_constraints_schema[kwargs18-Decimal-expected_extra18]", "tests/test_schema.py::test_constraints_schema[kwargs19-Decimal-expected_extra19]", "tests/test_schema.py::test_not_constraints_schema[kwargs0-int-expected0]", "tests/test_schema.py::test_not_constraints_schema[kwargs1-float-expected1]", "tests/test_schema.py::test_not_constraints_schema[kwargs2-Decimal-expected2]", "tests/test_schema.py::test_not_constraints_schema[kwargs3-int-expected3]", "tests/test_schema.py::test_not_constraints_schema[kwargs4-str-expected4]", "tests/test_schema.py::test_not_constraints_schema[kwargs5-bytes-expected5]", "tests/test_schema.py::test_not_constraints_schema[kwargs6-str-expected6]", "tests/test_schema.py::test_not_constraints_schema[kwargs7-bool-expected7]", "tests/test_schema.py::test_constraints_schema_validation[kwargs0-str-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs1-ConstrainedStrValue-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs2-str-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs3-bytes-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs4-str-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs5-bool-True]", "tests/test_schema.py::test_constraints_schema_validation[kwargs6-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs7-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs8-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs9-int-2]", "tests/test_schema.py::test_constraints_schema_validation[kwargs10-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs11-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs12-int-5]", "tests/test_schema.py::test_constraints_schema_validation[kwargs13-float-3.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs14-float-2.1]", "tests/test_schema.py::test_constraints_schema_validation[kwargs15-float-3.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs16-float-4.9]", "tests/test_schema.py::test_constraints_schema_validation[kwargs17-float-3.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs18-float-2.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs19-float-3.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs20-float-5.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs21-float-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs22-float-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs23-Decimal-value23]", "tests/test_schema.py::test_constraints_schema_validation[kwargs24-Decimal-value24]", "tests/test_schema.py::test_constraints_schema_validation[kwargs25-Decimal-value25]", "tests/test_schema.py::test_constraints_schema_validation[kwargs26-Decimal-value26]", "tests/test_schema.py::test_constraints_schema_validation[kwargs27-Decimal-value27]", "tests/test_schema.py::test_constraints_schema_validation[kwargs28-Decimal-value28]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs0-str-foobar]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs1-str-f]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs2-str-bar]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs3-int-2]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs4-int-5]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs5-int-1]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs6-int-6]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs7-float-2.0]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs8-float-5.0]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs9-float-1.9]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs10-float-5.1]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs11-Decimal-value11]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs12-Decimal-value12]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs13-Decimal-value13]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs14-Decimal-value14]", "tests/test_schema.py::test_schema_kwargs", "tests/test_schema.py::test_schema_dict_constr", "tests/test_schema.py::test_bytes_constrained_types[ConstrainedBytes-expected_schema0]", "tests/test_schema.py::test_bytes_constrained_types[ConstrainedBytesValue-expected_schema1]", "tests/test_schema.py::test_optional_dict", "tests/test_schema.py::test_field_with_validator", "tests/test_schema.py::test_known_model_optimization" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2019-06-27 09:42:31+00:00
mit
4,897
pydantic__pydantic-632
diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -358,7 +358,12 @@ def parse_obj(cls: Type['Model'], obj: Any) -> 'Model': except (TypeError, ValueError) as e: exc = TypeError(f'{cls.__name__} expected dict not {type(obj).__name__}') raise ValidationError([ErrorWrapper(exc, loc='__obj__')]) from e - return cls(**obj) + + m = cls.__new__(cls) + values, fields_set, _ = validate_model(m, obj) + object.__setattr__(m, '__values__', values) + object.__setattr__(m, '__fields_set__', fields_set) + return m @classmethod def parse_raw( @@ -472,14 +477,14 @@ def __get_validators__(cls) -> 'CallableGenerator': @classmethod def validate(cls: Type['Model'], value: Any) -> 'Model': if isinstance(value, dict): - return cls(**value) + return cls.parse_obj(value) elif isinstance(value, cls): return value.copy() elif cls.__config__.orm_mode: return cls.from_orm(value) else: with change_exception(DictError, TypeError, ValueError): - return cls(**dict(value)) + return cls.parse_obj(value) @classmethod def _decompose_class(cls: Type['Model'], obj: Any) -> GetterDict:
pydantic/pydantic
e4b285a0cdf6bafc34367e1fcbe88305d8811db3
Try `m = Model(self_=“some URL”)` with the rest of the code as is (from the with-alias example). @dmontagu the problem is deserialization. I get a json body in a request with {"self": "someurl"} in it and I can't create a model instance without preparsing the body to replace "self" with "self_" If pydantic had a way to "preload" like marshmallow does it might help? Would #624 help? @samuelcolvin would having a load alias give you a different function to call that didn’t already have `self` as a parameter? I don’t see that discussed in the linked issue. Given how frequently the specific field name `self` seems to be desired (I think it has meaning in certain json schema specs), might it make sense to rename `self` to `__self__` or something else equally unlikely to cause conflicts in `BaseModel.__init__` (and perhaps other methods expecting field names as kwargs)? Unless the approach of calling `Model(**data)` to initialize a model becomes discouraged, it feels unfortunate to me to have to change the model initialization code just to support a reasonably-named field (reasonable in a JSON context, rather than a python context anyway). @samuelcolvin not sure whether splitting out load and dump aliases changes the fact. Seems to me being able to avoid `Model(**data)` to initialize a model avoids all sorts of possible issues with name clashes. Moving this to a 'marshmallow' style `load(...)` has other advantages for pre-formatting data etc. but I don't really want to suggest any specific approach here not knowing the history and roadmap of the project well enough, rather just if there is a way to handle this. Regardless, as @dmontagu points out, 'self' and even 'kwargs' should be possible to specify in a schema.
diff --git a/tests/test_edge_cases.py b/tests/test_edge_cases.py --- a/tests/test_edge_cases.py +++ b/tests/test_edge_cases.py @@ -880,3 +880,29 @@ class Spam(BaseModel): assert Spam(c=Foo(a='123')).dict() == {'c': {'a': 123}} with pytest.raises(ValidationError): Spam(c=Bar(b='123')) + + +def test_self(): + class Model(BaseModel): + self: str + + m = Model.parse_obj(dict(self='some value')) + assert m.dict() == {'self': 'some value'} + assert m.self == 'some value' + assert m.schema() == { + 'title': 'Model', + 'type': 'object', + 'properties': {'self': {'title': 'Self', 'type': 'string'}}, + 'required': ['self'], + } + + +def test_self_recursive(): + class SubModel(BaseModel): + self: int + + class Model(BaseModel): + sm: SubModel + + m = Model.parse_obj({'sm': {'self': '123'}}) + assert m.dict() == {'sm': {'self': 123}}
How to use a field called "self" # Question Is it possible to have a field on a model called "self"? (Background to the question is JSON-API has links called "self", "related" etc.) * Python version 3.7.3 * Pydantic version 0.29 ```py from pydantic import BaseModel class Model(BaseModel): self: str m = Model(self="some URL") # TypeError: __init__() got multiple values for argument 'self' ``` I tried calling the field "self_" using an alias called "self" ```py from pydantic import BaseModel, Schema class Model(BaseModel): self_: str = Schema(alias="self") m = Model(self="some URL") # TypeError: __init__() got multiple values for argument 'self' ```
0.0
e4b285a0cdf6bafc34367e1fcbe88305d8811db3
[ "tests/test_edge_cases.py::test_self", "tests/test_edge_cases.py::test_self_recursive" ]
[ "tests/test_edge_cases.py::test_str_bytes", "tests/test_edge_cases.py::test_str_bytes_none", "tests/test_edge_cases.py::test_union_int_str", "tests/test_edge_cases.py::test_union_priority", "tests/test_edge_cases.py::test_typed_list", "tests/test_edge_cases.py::test_typed_set", "tests/test_edge_cases.py::test_dict_dict", "tests/test_edge_cases.py::test_typed_dict[value0-result0]", "tests/test_edge_cases.py::test_typed_dict[value1-result1]", "tests/test_edge_cases.py::test_typed_dict[value2-result2]", "tests/test_edge_cases.py::test_typed_dict_error[1-errors0]", "tests/test_edge_cases.py::test_typed_dict_error[value1-errors1]", "tests/test_edge_cases.py::test_typed_dict_error[value2-errors2]", "tests/test_edge_cases.py::test_dict_key_error", "tests/test_edge_cases.py::test_tuple", "tests/test_edge_cases.py::test_tuple_more", "tests/test_edge_cases.py::test_tuple_length_error", "tests/test_edge_cases.py::test_tuple_invalid", "tests/test_edge_cases.py::test_tuple_value_error", "tests/test_edge_cases.py::test_recursive_list", "tests/test_edge_cases.py::test_recursive_list_error", "tests/test_edge_cases.py::test_list_unions", "tests/test_edge_cases.py::test_recursive_lists", "tests/test_edge_cases.py::test_str_enum", "tests/test_edge_cases.py::test_any_dict", "tests/test_edge_cases.py::test_infer_alias", "tests/test_edge_cases.py::test_alias_error", "tests/test_edge_cases.py::test_annotation_config", "tests/test_edge_cases.py::test_success_values_include", "tests/test_edge_cases.py::test_include_exclude_default", "tests/test_edge_cases.py::test_field_set_ignore_extra", "tests/test_edge_cases.py::test_field_set_allow_extra", "tests/test_edge_cases.py::test_field_set_field_name", "tests/test_edge_cases.py::test_values_order", "tests/test_edge_cases.py::test_inheritance", "tests/test_edge_cases.py::test_invalid_type", "tests/test_edge_cases.py::test_valid_string_types[a", "tests/test_edge_cases.py::test_valid_string_types[some", "tests/test_edge_cases.py::test_valid_string_types[value2-foobar]", "tests/test_edge_cases.py::test_valid_string_types[123-123]", "tests/test_edge_cases.py::test_valid_string_types[123.45-123.45]", "tests/test_edge_cases.py::test_valid_string_types[value5-12.45]", "tests/test_edge_cases.py::test_valid_string_types[True-True]", "tests/test_edge_cases.py::test_valid_string_types[False-False]", "tests/test_edge_cases.py::test_valid_string_types[a10-a10]", "tests/test_edge_cases.py::test_valid_string_types[whatever-whatever]", "tests/test_edge_cases.py::test_invalid_string_types[value0-errors0]", "tests/test_edge_cases.py::test_invalid_string_types[value1-errors1]", "tests/test_edge_cases.py::test_inheritance_config", "tests/test_edge_cases.py::test_partial_inheritance_config", "tests/test_edge_cases.py::test_string_none", "tests/test_edge_cases.py::test_alias_camel_case", "tests/test_edge_cases.py::test_get_field_schema_inherit", "tests/test_edge_cases.py::test_return_errors_ok", "tests/test_edge_cases.py::test_return_errors_error", "tests/test_edge_cases.py::test_optional_required", "tests/test_edge_cases.py::test_invalid_validator", "tests/test_edge_cases.py::test_unable_to_infer", "tests/test_edge_cases.py::test_get_validator", "tests/test_edge_cases.py::test_multiple_errors", "tests/test_edge_cases.py::test_pop_by_alias", "tests/test_edge_cases.py::test_validate_all", "tests/test_edge_cases.py::test_ignore_extra_true", "tests/test_edge_cases.py::test_ignore_extra_false", "tests/test_edge_cases.py::test_allow_extra", "tests/test_edge_cases.py::test_ignore_extra_allow_extra", "tests/test_edge_cases.py::test_force_extra", "tests/test_edge_cases.py::test_illegal_extra_value", "tests/test_edge_cases.py::test_multiple_inheritance_config", "tests/test_edge_cases.py::test_multiple_inheritance_config_legacy_extra", "tests/test_edge_cases.py::test_submodel_different_type" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2019-07-01 09:03:52+00:00
mit
4,898
pydantic__pydantic-6586
diff --git a/pydantic/fields.py b/pydantic/fields.py --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -943,7 +943,7 @@ def _validate_sequence_like( # noqa: C901 (ignore complexity) elif self.shape == SHAPE_TUPLE_ELLIPSIS: converted = tuple(result) elif self.shape == SHAPE_DEQUE: - converted = deque(result) + converted = deque(result, maxlen=getattr(v, 'maxlen', None)) elif self.shape == SHAPE_SEQUENCE: if isinstance(v, tuple): converted = tuple(result) @@ -952,7 +952,7 @@ def _validate_sequence_like( # noqa: C901 (ignore complexity) elif isinstance(v, Generator): converted = iter(result) elif isinstance(v, deque): - converted = deque(result) + converted = deque(result, maxlen=getattr(v, 'maxlen', None)) return converted, None def _validate_iterable(
pydantic/pydantic
15c82d978d9e3b3893f00982b9e0c5c8d5c7821d
Some more cases: ``` >>> from collections import deque >>> from pydantic import BaseModel >>> class D(BaseModel): ... q: deque[int] = deque(maxlen=10) ... >>> d = D() >>> d D(q=deque([], maxlen=10)) >>> d.q = deque(maxlen=25) >>> d D(q=deque([], maxlen=25)) ``` So it seems that it is validation issue on model creation only. I do not know the codebase here but potentially: https://github.com/pydantic/pydantic/blob/f35c780cc3cf073c400ee038b8b6dd6d7b5703d9/pydantic/v1/fields.py#L954C25-L954C25 Thanks @maciekglowka for this issue 🙏 As you may know, `Pydantic V2` is out and we are not actively working on `V1`. I've checked your first example code on V2, all of them returning `D(q=deque([], maxlen=15))` Same for you second example. In `V2` you can have validation on assignment to a `deque` field like: ```py from collections import deque from typing import Deque from typing_extensions import Annotated from pydantic import BaseModel, ConfigDict, Field class D(BaseModel): q: Annotated[Deque[int], Field(deque(maxlen=10), max_length=10)] model_config = ConfigDict(validate_assignment=True) d = D() d.q = deque([1] * 25) ``` Note: We still accept bug fixes on `V1` but it should be an easy fix. Thanks for checking. Yeah I've just forked the repo. If I'll be able to fix this I'm gonna make a PR.
diff --git a/tests/test_types.py b/tests/test_types.py --- a/tests/test_types.py +++ b/tests/test_types.py @@ -3123,6 +3123,25 @@ class Model(BaseModel): assert Model(v=value).v == result +def test_deque_maxlen(): + class DequeTypedModel(BaseModel): + field: Deque[int] = deque(maxlen=10) + + assert DequeTypedModel(field=deque(maxlen=25)).field.maxlen == 25 + assert DequeTypedModel().field.maxlen == 10 + + class DequeUnTypedModel(BaseModel): + field: deque = deque(maxlen=10) + + assert DequeUnTypedModel(field=deque(maxlen=25)).field.maxlen == 25 + assert DequeTypedModel().field.maxlen == 10 + + class DeuqueNoDefaultModel(BaseModel): + field: deque + + assert DeuqueNoDefaultModel(field=deque(maxlen=25)).field.maxlen == 25 + + @pytest.mark.parametrize( 'cls,value,errors', (
Maxlen property always set to None, when deque item type is provided. ### Initial Checks - [X] I have searched GitHub for a duplicate issue and I'm sure this is something new - [X] I have searched Google & StackOverflow for a solution and couldn't find anything - [X] I have read and followed [the docs](https://docs.pydantic.dev) and still think this is a bug - [X] I am confident that the issue is with pydantic (not my code, or another library in the ecosystem like [FastAPI](https://fastapi.tiangolo.com) or [mypy](https://mypy.readthedocs.io/en/stable)) ### Description The `maxlen` property of the `deque` field seems to be set to `None` when the queue item type is provided. In the example below I first create an untyped deque and upon instancing everything goes well - the `maxlen` is set to `15`. However when the model definitions is more specific: `deque[int]` or `Deque[int]` then the `maxlen` value cannot be set. ### Example Code ```Python >>> from pydantic import BaseModel >>> from collections import deque >>> class D(BaseModel): ... q: deque = deque(maxlen=10) ... >>> d = D(q=deque(maxlen=15)) >>> d D(q=deque([], maxlen=15)) >>> >>> >>> class DI(BaseModel): ... q: deque[int] = deque(maxlen=10) ... >>> d = DI(q=deque(maxlen=15)) >>> d DI(q=deque([])) >>> >>> from typing import Deque >>> >>> class DT(BaseModel): ... q: Deque[int] = deque(maxlen=10) ... >>> d = DT(q=deque(maxlen=15)) >>> d DT(q=deque([])) ``` ### Python, Pydantic & OS Version ```Text pydantic version: 1.10.5 pydantic compiled: True install path: /opt/venv/lib/python3.11/site-packages/pydantic python version: 3.11.4 (main, Jun 13 2023, 15:08:32) [GCC 10.2.1 20210110] platform: Linux-5.15.90.1-microsoft-standard-WSL2-x86_64-with-glibc2.31 optional deps. installed: ['typing-extensions'] ``` ### Affected Components - [ ] [Compatibility between releases](https://docs.pydantic.dev/changelog/) - [ ] [Data validation/parsing](https://docs.pydantic.dev/usage/models/#basic-model-usage) - [ ] [Data serialization](https://docs.pydantic.dev/usage/exporting_models/) - `.dict()` and `.json()` - [ ] [JSON Schema](https://docs.pydantic.dev/usage/schema/) - [ ] [Dataclasses](https://docs.pydantic.dev/usage/dataclasses/) - [ ] [Model Config](https://docs.pydantic.dev/usage/model_config/) - [X] [Field Types](https://docs.pydantic.dev/usage/types/) - adding or changing a particular data type - [ ] [Function validation decorator](https://docs.pydantic.dev/usage/validation_decorator/) - [ ] [Generic Models](https://docs.pydantic.dev/usage/models/#generic-models) - [ ] [Other Model behaviour](https://docs.pydantic.dev/usage/models/) - `construct()`, pickling, private attributes, ORM mode - [ ] [Plugins](https://docs.pydantic.dev/) and integration with other tools - mypy, FastAPI, python-devtools, Hypothesis, VS Code, PyCharm, etc. Selected Assignee: @davidhewitt
0.0
15c82d978d9e3b3893f00982b9e0c5c8d5c7821d
[ "tests/test_types.py::test_deque_maxlen" ]
[ "tests/test_types.py::test_constrained_bytes_good", "tests/test_types.py::test_constrained_bytes_default", "tests/test_types.py::test_constrained_bytes_too_long", "tests/test_types.py::test_constrained_bytes_upper[True-abcd-ABCD]", "tests/test_types.py::test_constrained_bytes_upper[False-aBcD-aBcD]", "tests/test_types.py::test_constrained_bytes_lower[True-ABCD-abcd]", "tests/test_types.py::test_constrained_bytes_lower[False-ABCD-ABCD]", "tests/test_types.py::test_constrained_bytes_strict_true", "tests/test_types.py::test_constrained_bytes_strict_false", "tests/test_types.py::test_constrained_bytes_strict_default", "tests/test_types.py::test_constrained_list_good", "tests/test_types.py::test_constrained_list_default", "tests/test_types.py::test_constrained_list_too_long", "tests/test_types.py::test_constrained_list_too_short", "tests/test_types.py::test_constrained_list_not_unique_hashable_items", "tests/test_types.py::test_constrained_list_not_unique_unhashable_items", "tests/test_types.py::test_constrained_list_optional", "tests/test_types.py::test_constrained_list_constraints", "tests/test_types.py::test_constrained_list_item_type_fails", "tests/test_types.py::test_conlist", "tests/test_types.py::test_conlist_wrong_type_default", "tests/test_types.py::test_constrained_set_good", "tests/test_types.py::test_constrained_set_default", "tests/test_types.py::test_constrained_set_default_invalid", "tests/test_types.py::test_constrained_set_too_long", "tests/test_types.py::test_constrained_set_too_short", "tests/test_types.py::test_constrained_set_optional", "tests/test_types.py::test_constrained_set_constraints", "tests/test_types.py::test_constrained_set_item_type_fails", "tests/test_types.py::test_conset", "tests/test_types.py::test_conset_not_required", "tests/test_types.py::test_confrozenset", "tests/test_types.py::test_confrozenset_not_required", "tests/test_types.py::test_constrained_frozenset_optional", "tests/test_types.py::test_constrained_str_good", "tests/test_types.py::test_constrained_str_default", "tests/test_types.py::test_constrained_str_too_long", "tests/test_types.py::test_constrained_str_upper[True-abcd-ABCD]", "tests/test_types.py::test_constrained_str_upper[False-aBcD-aBcD]", "tests/test_types.py::test_constrained_str_lower[True-ABCD-abcd]", "tests/test_types.py::test_constrained_str_lower[False-ABCD-ABCD]", "tests/test_types.py::test_constrained_str_max_length_0", "tests/test_types.py::test_module_import", "tests/test_types.py::test_pyobject_none", "tests/test_types.py::test_pyobject_callable", "tests/test_types.py::test_default_validators[bool_check-True-True0]", "tests/test_types.py::test_default_validators[bool_check-1-True0]", "tests/test_types.py::test_default_validators[bool_check-y-True]", "tests/test_types.py::test_default_validators[bool_check-Y-True]", "tests/test_types.py::test_default_validators[bool_check-yes-True]", "tests/test_types.py::test_default_validators[bool_check-Yes-True]", "tests/test_types.py::test_default_validators[bool_check-YES-True]", "tests/test_types.py::test_default_validators[bool_check-true-True]", "tests/test_types.py::test_default_validators[bool_check-True-True1]", "tests/test_types.py::test_default_validators[bool_check-TRUE-True0]", "tests/test_types.py::test_default_validators[bool_check-on-True]", "tests/test_types.py::test_default_validators[bool_check-On-True]", "tests/test_types.py::test_default_validators[bool_check-ON-True]", "tests/test_types.py::test_default_validators[bool_check-1-True1]", "tests/test_types.py::test_default_validators[bool_check-t-True]", "tests/test_types.py::test_default_validators[bool_check-T-True]", "tests/test_types.py::test_default_validators[bool_check-TRUE-True1]", "tests/test_types.py::test_default_validators[bool_check-False-False0]", "tests/test_types.py::test_default_validators[bool_check-0-False0]", "tests/test_types.py::test_default_validators[bool_check-n-False]", "tests/test_types.py::test_default_validators[bool_check-N-False]", "tests/test_types.py::test_default_validators[bool_check-no-False]", "tests/test_types.py::test_default_validators[bool_check-No-False]", "tests/test_types.py::test_default_validators[bool_check-NO-False]", "tests/test_types.py::test_default_validators[bool_check-false-False]", "tests/test_types.py::test_default_validators[bool_check-False-False1]", "tests/test_types.py::test_default_validators[bool_check-FALSE-False0]", "tests/test_types.py::test_default_validators[bool_check-off-False]", "tests/test_types.py::test_default_validators[bool_check-Off-False]", "tests/test_types.py::test_default_validators[bool_check-OFF-False]", "tests/test_types.py::test_default_validators[bool_check-0-False1]", "tests/test_types.py::test_default_validators[bool_check-f-False]", "tests/test_types.py::test_default_validators[bool_check-F-False]", "tests/test_types.py::test_default_validators[bool_check-FALSE-False1]", "tests/test_types.py::test_default_validators[bool_check-None-ValidationError]", "tests/test_types.py::test_default_validators[bool_check--ValidationError]", "tests/test_types.py::test_default_validators[bool_check-value36-ValidationError]", "tests/test_types.py::test_default_validators[bool_check-value37-ValidationError]", "tests/test_types.py::test_default_validators[bool_check-value38-ValidationError]", "tests/test_types.py::test_default_validators[bool_check-value39-ValidationError]", "tests/test_types.py::test_default_validators[bool_check-2-ValidationError0]", "tests/test_types.py::test_default_validators[bool_check-2-ValidationError1]", "tests/test_types.py::test_default_validators[bool_check-2-ValidationError2]", "tests/test_types.py::test_default_validators[bool_check-\\x81-ValidationError]", "tests/test_types.py::test_default_validators[bool_check-value44-ValidationError]", "tests/test_types.py::test_default_validators[str_check-s-s0]", "tests/test_types.py::test_default_validators[str_check-", "tests/test_types.py::test_default_validators[str_check-s-s1]", "tests/test_types.py::test_default_validators[str_check-1-1]", "tests/test_types.py::test_default_validators[str_check-xxxxxxxxxxx-ValidationError0]", "tests/test_types.py::test_default_validators[str_check-xxxxxxxxxxx-ValidationError1]", "tests/test_types.py::test_default_validators[bytes_check-s-s0]", "tests/test_types.py::test_default_validators[bytes_check-", "tests/test_types.py::test_default_validators[bytes_check-s-s1]", "tests/test_types.py::test_default_validators[bytes_check-1-1]", "tests/test_types.py::test_default_validators[bytes_check-value57-xx]", "tests/test_types.py::test_default_validators[bytes_check-True-True]", "tests/test_types.py::test_default_validators[bytes_check-False-False]", "tests/test_types.py::test_default_validators[bytes_check-value60-ValidationError]", "tests/test_types.py::test_default_validators[bytes_check-xxxxxxxxxxx-ValidationError0]", "tests/test_types.py::test_default_validators[bytes_check-xxxxxxxxxxx-ValidationError1]", "tests/test_types.py::test_default_validators[int_check-1-10]", "tests/test_types.py::test_default_validators[int_check-1.9-1]", "tests/test_types.py::test_default_validators[int_check-1-11]", "tests/test_types.py::test_default_validators[int_check-1.9-ValidationError]", "tests/test_types.py::test_default_validators[int_check-1-12]", "tests/test_types.py::test_default_validators[int_check-12-120]", "tests/test_types.py::test_default_validators[int_check-12-121]", "tests/test_types.py::test_default_validators[int_check-12-122]", "tests/test_types.py::test_default_validators[float_check-1-1.00]", "tests/test_types.py::test_default_validators[float_check-1.0-1.00]", "tests/test_types.py::test_default_validators[float_check-1.0-1.01]", "tests/test_types.py::test_default_validators[float_check-1-1.01]", "tests/test_types.py::test_default_validators[float_check-1.0-1.02]", "tests/test_types.py::test_default_validators[float_check-1-1.02]", "tests/test_types.py::test_default_validators[uuid_check-ebcdab58-6eb8-46fb-a190-d07a33e9eac8-result77]", "tests/test_types.py::test_default_validators[uuid_check-value78-result78]", "tests/test_types.py::test_default_validators[uuid_check-ebcdab58-6eb8-46fb-a190-d07a33e9eac8-result79]", "tests/test_types.py::test_default_validators[uuid_check-\\x124Vx\\x124Vx\\x124Vx\\x124Vx-result80]", "tests/test_types.py::test_default_validators[uuid_check-ebcdab58-6eb8-46fb-a190--ValidationError]", "tests/test_types.py::test_default_validators[uuid_check-123-ValidationError]", "tests/test_types.py::test_default_validators[decimal_check-42.24-result83]", "tests/test_types.py::test_default_validators[decimal_check-42.24-result84]", "tests/test_types.py::test_default_validators[decimal_check-42.24-result85]", "tests/test_types.py::test_default_validators[decimal_check-", "tests/test_types.py::test_default_validators[decimal_check-value87-result87]", "tests/test_types.py::test_default_validators[decimal_check-not", "tests/test_types.py::test_default_validators[decimal_check-NaN-ValidationError]", "tests/test_types.py::test_string_too_long", "tests/test_types.py::test_string_too_short", "tests/test_types.py::test_datetime_successful", "tests/test_types.py::test_datetime_errors", "tests/test_types.py::test_enum_successful", "tests/test_types.py::test_enum_fails", "tests/test_types.py::test_int_enum_successful_for_str_int", "tests/test_types.py::test_enum_type", "tests/test_types.py::test_int_enum_type", "tests/test_types.py::test_string_success", "tests/test_types.py::test_string_fails", "tests/test_types.py::test_dict", "tests/test_types.py::test_list_success[value0-result0]", "tests/test_types.py::test_list_success[value1-result1]", "tests/test_types.py::test_list_success[value2-result2]", "tests/test_types.py::test_list_success[<genexpr>-result3]", "tests/test_types.py::test_list_success[value4-result4]", "tests/test_types.py::test_list_fails[1230]", "tests/test_types.py::test_list_fails[1231]", "tests/test_types.py::test_ordered_dict", "tests/test_types.py::test_tuple_success[value0-result0]", "tests/test_types.py::test_tuple_success[value1-result1]", "tests/test_types.py::test_tuple_success[value2-result2]", "tests/test_types.py::test_tuple_success[<genexpr>-result3]", "tests/test_types.py::test_tuple_success[value4-result4]", "tests/test_types.py::test_tuple_fails[1230]", "tests/test_types.py::test_tuple_fails[1231]", "tests/test_types.py::test_tuple_variable_len_success[value0-int-result0]", "tests/test_types.py::test_tuple_variable_len_success[value1-int-result1]", "tests/test_types.py::test_tuple_variable_len_success[<genexpr>-int-result2]", "tests/test_types.py::test_tuple_variable_len_success[value3-str-result3]", "tests/test_types.py::test_tuple_variable_len_fails[value0-str-exc0]", "tests/test_types.py::test_tuple_variable_len_fails[value1-str-exc1]", "tests/test_types.py::test_set_success[value0-result0]", "tests/test_types.py::test_set_success[value1-result1]", "tests/test_types.py::test_set_success[value2-result2]", "tests/test_types.py::test_set_success[value3-result3]", "tests/test_types.py::test_set_fails[1230]", "tests/test_types.py::test_set_fails[1231]", "tests/test_types.py::test_list_type_fails", "tests/test_types.py::test_set_type_fails", "tests/test_types.py::test_sequence_success[int-value0-result0]", "tests/test_types.py::test_sequence_success[int-value1-result1]", "tests/test_types.py::test_sequence_success[int-value2-result2]", "tests/test_types.py::test_sequence_success[float-value3-result3]", "tests/test_types.py::test_sequence_success[cls4-value4-result4]", "tests/test_types.py::test_sequence_success[cls5-value5-result5]", "tests/test_types.py::test_sequence_generator_success[int-<genexpr>-result0]", "tests/test_types.py::test_sequence_generator_success[float-<genexpr>-result1]", "tests/test_types.py::test_sequence_generator_success[str-<genexpr>-result2]", "tests/test_types.py::test_infinite_iterable", "tests/test_types.py::test_invalid_iterable", "tests/test_types.py::test_infinite_iterable_validate_first", "tests/test_types.py::test_sequence_generator_fails[int-<genexpr>-errors0]", "tests/test_types.py::test_sequence_generator_fails[float-<genexpr>-errors1]", "tests/test_types.py::test_sequence_fails[int-value0-errors0]", "tests/test_types.py::test_sequence_fails[int-value1-errors1]", "tests/test_types.py::test_sequence_fails[float-value2-errors2]", "tests/test_types.py::test_sequence_fails[float-value3-errors3]", "tests/test_types.py::test_sequence_fails[float-value4-errors4]", "tests/test_types.py::test_sequence_fails[cls5-value5-errors5]", "tests/test_types.py::test_sequence_fails[cls6-value6-errors6]", "tests/test_types.py::test_sequence_fails[cls7-value7-errors7]", "tests/test_types.py::test_int_validation", "tests/test_types.py::test_float_validation", "tests/test_types.py::test_finite_float_validation", "tests/test_types.py::test_finite_float_validation_error[inf]", "tests/test_types.py::test_finite_float_validation_error[-inf]", "tests/test_types.py::test_finite_float_validation_error[nan]", "tests/test_types.py::test_finite_float_config", "tests/test_types.py::test_strict_bytes", "tests/test_types.py::test_strict_bytes_max_length", "tests/test_types.py::test_strict_bytes_subclass", "tests/test_types.py::test_strict_str", "tests/test_types.py::test_strict_str_subclass", "tests/test_types.py::test_strict_str_max_length", "tests/test_types.py::test_strict_str_regex", "tests/test_types.py::test_string_regex", "tests/test_types.py::test_strict_bool", "tests/test_types.py::test_strict_int", "tests/test_types.py::test_strict_int_subclass", "tests/test_types.py::test_strict_float", "tests/test_types.py::test_strict_float_subclass", "tests/test_types.py::test_bool_unhashable_fails", "tests/test_types.py::test_uuid_error", "tests/test_types.py::test_uuid_validation", "tests/test_types.py::test_anystr_strip_whitespace[True-", "tests/test_types.py::test_anystr_strip_whitespace[False-", "tests/test_types.py::test_anystr_upper[True-ABCDefG-abCD1Fg-ABCDEFG-ABCD1FG]", "tests/test_types.py::test_anystr_upper[False-ABCDefG-abCD1Fg-ABCDefG-abCD1Fg]", "tests/test_types.py::test_anystr_lower[True-ABCDefG-abCD1Fg-abcdefg-abcd1fg]", "tests/test_types.py::test_anystr_lower[False-ABCDefG-abCD1Fg-ABCDefG-abCD1Fg]", "tests/test_types.py::test_decimal_validation[type_args0-value0-result0]", "tests/test_types.py::test_decimal_validation[type_args1-value1-result1]", "tests/test_types.py::test_decimal_validation[type_args2-value2-result2]", "tests/test_types.py::test_decimal_validation[type_args3-value3-result3]", "tests/test_types.py::test_decimal_validation[type_args4-value4-result4]", "tests/test_types.py::test_decimal_validation[type_args5-value5-result5]", "tests/test_types.py::test_decimal_validation[type_args6-value6-result6]", "tests/test_types.py::test_decimal_validation[type_args7-value7-result7]", "tests/test_types.py::test_decimal_validation[type_args8-value8-result8]", "tests/test_types.py::test_decimal_validation[type_args9-value9-result9]", "tests/test_types.py::test_decimal_validation[type_args10-value10-result10]", "tests/test_types.py::test_decimal_validation[type_args11-value11-result11]", "tests/test_types.py::test_decimal_validation[type_args12-value12-result12]", "tests/test_types.py::test_decimal_validation[type_args13-value13-result13]", "tests/test_types.py::test_decimal_validation[type_args14-value14-result14]", "tests/test_types.py::test_decimal_validation[type_args15-value15-result15]", "tests/test_types.py::test_decimal_validation[type_args16-value16-result16]", "tests/test_types.py::test_decimal_validation[type_args17-value17-result17]", "tests/test_types.py::test_decimal_validation[type_args18-value18-result18]", "tests/test_types.py::test_decimal_validation[type_args19-value19-result19]", "tests/test_types.py::test_decimal_validation[type_args20-value20-result20]", "tests/test_types.py::test_decimal_validation[type_args21-value21-result21]", "tests/test_types.py::test_decimal_validation[type_args22-value22-result22]", "tests/test_types.py::test_decimal_validation[type_args23-NaN-result23]", "tests/test_types.py::test_decimal_validation[type_args24--NaN-result24]", "tests/test_types.py::test_decimal_validation[type_args25-+NaN-result25]", "tests/test_types.py::test_decimal_validation[type_args26-sNaN-result26]", "tests/test_types.py::test_decimal_validation[type_args27--sNaN-result27]", "tests/test_types.py::test_decimal_validation[type_args28-+sNaN-result28]", "tests/test_types.py::test_decimal_validation[type_args29-Inf-result29]", "tests/test_types.py::test_decimal_validation[type_args30--Inf-result30]", "tests/test_types.py::test_decimal_validation[type_args31-+Inf-result31]", "tests/test_types.py::test_decimal_validation[type_args32-Infinity-result32]", "tests/test_types.py::test_decimal_validation[type_args33--Infinity-result33]", "tests/test_types.py::test_decimal_validation[type_args34--Infinity-result34]", "tests/test_types.py::test_decimal_validation[type_args35-value35-result35]", "tests/test_types.py::test_decimal_validation[type_args36-value36-result36]", "tests/test_types.py::test_decimal_validation[type_args37-value37-result37]", "tests/test_types.py::test_decimal_validation[type_args38-value38-result38]", "tests/test_types.py::test_decimal_validation[type_args39-value39-result39]", "tests/test_types.py::test_decimal_validation[type_args40-value40-result40]", "tests/test_types.py::test_decimal_validation[type_args41-value41-result41]", "tests/test_types.py::test_decimal_validation[type_args42-value42-result42]", "tests/test_types.py::test_decimal_validation[type_args43-value43-result43]", "tests/test_types.py::test_decimal_validation[type_args44-value44-result44]", "tests/test_types.py::test_decimal_validation[type_args45-value45-result45]", "tests/test_types.py::test_decimal_validation[type_args46-value46-result46]", "tests/test_types.py::test_decimal_validation[type_args47-value47-result47]", "tests/test_types.py::test_path_validation_success[/test/path-result0]", "tests/test_types.py::test_path_validation_success[value1-result1]", "tests/test_types.py::test_path_validation_fails", "tests/test_types.py::test_file_path_validation_success[tests/test_types.py-result0]", "tests/test_types.py::test_file_path_validation_success[value1-result1]", "tests/test_types.py::test_file_path_validation_fails[nonexistentfile-errors0]", "tests/test_types.py::test_file_path_validation_fails[value1-errors1]", "tests/test_types.py::test_file_path_validation_fails[tests-errors2]", "tests/test_types.py::test_file_path_validation_fails[value3-errors3]", "tests/test_types.py::test_directory_path_validation_success[tests-result0]", "tests/test_types.py::test_directory_path_validation_success[value1-result1]", "tests/test_types.py::test_directory_path_validation_fails[nonexistentdirectory-errors0]", "tests/test_types.py::test_directory_path_validation_fails[value1-errors1]", "tests/test_types.py::test_directory_path_validation_fails[tests/test_types.py-errors2]", "tests/test_types.py::test_directory_path_validation_fails[value3-errors3]", "tests/test_types.py::test_number_gt", "tests/test_types.py::test_number_ge", "tests/test_types.py::test_number_lt", "tests/test_types.py::test_number_le", "tests/test_types.py::test_number_multiple_of_int_valid[10]", "tests/test_types.py::test_number_multiple_of_int_valid[100]", "tests/test_types.py::test_number_multiple_of_int_valid[20]", "tests/test_types.py::test_number_multiple_of_int_invalid[1337]", "tests/test_types.py::test_number_multiple_of_int_invalid[23]", "tests/test_types.py::test_number_multiple_of_int_invalid[6]", "tests/test_types.py::test_number_multiple_of_int_invalid[14]", "tests/test_types.py::test_number_multiple_of_float_valid[0.2]", "tests/test_types.py::test_number_multiple_of_float_valid[0.3]", "tests/test_types.py::test_number_multiple_of_float_valid[0.4]", "tests/test_types.py::test_number_multiple_of_float_valid[0.5]", "tests/test_types.py::test_number_multiple_of_float_valid[1]", "tests/test_types.py::test_number_multiple_of_float_invalid[0.07]", "tests/test_types.py::test_number_multiple_of_float_invalid[1.27]", "tests/test_types.py::test_number_multiple_of_float_invalid[1.003]", "tests/test_types.py::test_bounds_config_exceptions[conint]", "tests/test_types.py::test_bounds_config_exceptions[confloat]", "tests/test_types.py::test_bounds_config_exceptions[condecimal]", "tests/test_types.py::test_new_type_success", "tests/test_types.py::test_new_type_fails", "tests/test_types.py::test_json_any_is_json", "tests/test_types.py::test_valid_simple_json", "tests/test_types.py::test_valid_simple_json_any", "tests/test_types.py::test_invalid_simple_json", "tests/test_types.py::test_invalid_simple_json_any", "tests/test_types.py::test_valid_simple_json_bytes", "tests/test_types.py::test_valid_detailed_json", "tests/test_types.py::test_invalid_detailed_json_value_error", "tests/test_types.py::test_valid_detailed_json_bytes", "tests/test_types.py::test_valid_model_json", "tests/test_types.py::test_invalid_model_json", "tests/test_types.py::test_invalid_detailed_json_type_error", "tests/test_types.py::test_json_not_str", "tests/test_types.py::test_json_pre_validator", "tests/test_types.py::test_json_optional_simple", "tests/test_types.py::test_json_optional_complex", "tests/test_types.py::test_json_explicitly_required", "tests/test_types.py::test_json_no_default", "tests/test_types.py::test_pattern[Pattern]", "tests/test_types.py::test_pattern[pattern_type1]", "tests/test_types.py::test_pattern_error[Pattern]", "tests/test_types.py::test_pattern_error[pattern_type1]", "tests/test_types.py::test_secretfield", "tests/test_types.py::test_secretstr", "tests/test_types.py::test_secretstr_is_secret_field", "tests/test_types.py::test_secretstr_equality", "tests/test_types.py::test_secretstr_idempotent", "tests/test_types.py::test_secretstr_is_hashable", "tests/test_types.py::test_secretstr_error", "tests/test_types.py::test_secretstr_min_max_length", "tests/test_types.py::test_secretbytes", "tests/test_types.py::test_secretbytes_is_secret_field", "tests/test_types.py::test_secretbytes_equality", "tests/test_types.py::test_secretbytes_idempotent", "tests/test_types.py::test_secretbytes_is_hashable", "tests/test_types.py::test_secretbytes_error", "tests/test_types.py::test_secretbytes_min_max_length", "tests/test_types.py::test_secrets_schema[no-constrains-SecretStr]", "tests/test_types.py::test_secrets_schema[no-constrains-SecretBytes]", "tests/test_types.py::test_secrets_schema[min-constraint-SecretStr]", "tests/test_types.py::test_secrets_schema[min-constraint-SecretBytes]", "tests/test_types.py::test_secrets_schema[max-constraint-SecretStr]", "tests/test_types.py::test_secrets_schema[max-constraint-SecretBytes]", "tests/test_types.py::test_secrets_schema[min-max-constraints-SecretStr]", "tests/test_types.py::test_secrets_schema[min-max-constraints-SecretBytes]", "tests/test_types.py::test_generic_without_params", "tests/test_types.py::test_generic_without_params_error", "tests/test_types.py::test_literal_single", "tests/test_types.py::test_literal_multiple", "tests/test_types.py::test_unsupported_field_type", "tests/test_types.py::test_frozenset_field", "tests/test_types.py::test_frozenset_field_conversion[value0-result0]", "tests/test_types.py::test_frozenset_field_conversion[value1-result1]", "tests/test_types.py::test_frozenset_field_conversion[value2-result2]", "tests/test_types.py::test_frozenset_field_conversion[value3-result3]", "tests/test_types.py::test_frozenset_field_not_convertible", "tests/test_types.py::test_bytesize_conversions[1-1-1.0B-1.0B]", "tests/test_types.py::test_bytesize_conversions[1.0-1-1.0B-1.0B]", "tests/test_types.py::test_bytesize_conversions[1b-1-1.0B-1.0B]", "tests/test_types.py::test_bytesize_conversions[1.5", "tests/test_types.py::test_bytesize_conversions[5.1kib-5222-5.1KiB-5.2KB]", "tests/test_types.py::test_bytesize_conversions[6.2EiB-7148113328562451456-6.2EiB-7.1EB]", "tests/test_types.py::test_bytesize_to", "tests/test_types.py::test_bytesize_raises", "tests/test_types.py::test_deque_success", "tests/test_types.py::test_deque_generic_success[int-value0-result0]", "tests/test_types.py::test_deque_generic_success[int-value1-result1]", "tests/test_types.py::test_deque_generic_success[int-value2-result2]", "tests/test_types.py::test_deque_generic_success[float-value3-result3]", "tests/test_types.py::test_deque_generic_success[cls4-value4-result4]", "tests/test_types.py::test_deque_generic_success[cls5-value5-result5]", "tests/test_types.py::test_deque_generic_success[str-value6-result6]", "tests/test_types.py::test_deque_generic_success[int-value7-result7]", "tests/test_types.py::test_deque_fails[int-value0-errors0]", "tests/test_types.py::test_deque_fails[int-value1-errors1]", "tests/test_types.py::test_deque_fails[float-value2-errors2]", "tests/test_types.py::test_deque_fails[float-value3-errors3]", "tests/test_types.py::test_deque_fails[float-value4-errors4]", "tests/test_types.py::test_deque_fails[cls5-value5-errors5]", "tests/test_types.py::test_deque_fails[cls6-value6-errors6]", "tests/test_types.py::test_deque_fails[cls7-value7-errors7]", "tests/test_types.py::test_deque_model", "tests/test_types.py::test_deque_json", "tests/test_types.py::test_none[None]", "tests/test_types.py::test_none[NoneType0]", "tests/test_types.py::test_none[NoneType1]", "tests/test_types.py::test_none[value_type3]", "tests/test_types.py::test_default_union_types", "tests/test_types.py::test_smart_union_types", "tests/test_types.py::test_default_union_class", "tests/test_types.py::test_smart_union_class", "tests/test_types.py::test_default_union_subclass", "tests/test_types.py::test_smart_union_subclass", "tests/test_types.py::test_default_union_compound_types", "tests/test_types.py::test_smart_union_compound_types", "tests/test_types.py::test_smart_union_compouned_types_edge_case", "tests/test_types.py::test_smart_union_typeddict", "tests/test_types.py::test_past_date_validation_success[1996-01-22-result0]", "tests/test_types.py::test_past_date_validation_success[value1-result1]", "tests/test_types.py::test_past_date_validation_fails[value0]", "tests/test_types.py::test_past_date_validation_fails[value1]", "tests/test_types.py::test_past_date_validation_fails[value2]", "tests/test_types.py::test_past_date_validation_fails[value3]", "tests/test_types.py::test_past_date_validation_fails[2064-06-01]", "tests/test_types.py::test_future_date_validation_success[value0-result0]", "tests/test_types.py::test_future_date_validation_success[value1-result1]", "tests/test_types.py::test_future_date_validation_success[2064-06-01-result2]", "tests/test_types.py::test_future_date_validation_fails[value0]", "tests/test_types.py::test_future_date_validation_fails[value1]", "tests/test_types.py::test_future_date_validation_fails[value2]", "tests/test_types.py::test_future_date_validation_fails[value3]", "tests/test_types.py::test_future_date_validation_fails[1996-01-22]", "tests/test_types.py::test_typing_extension_literal_field" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2023-07-11 12:02:38+00:00
mit
4,899
pydantic__pydantic-738
diff --git a/pydantic/error_wrappers.py b/pydantic/error_wrappers.py --- a/pydantic/error_wrappers.py +++ b/pydantic/error_wrappers.py @@ -42,6 +42,9 @@ def dict(self, *, loc_prefix: Optional[Tuple[str, ...]] = None) -> Dict[str, Any return d + def __repr__(self) -> str: + return f'<ErrorWrapper {self.dict()}>' + # ErrorList is something like Union[List[Union[List[ErrorWrapper], ErrorWrapper]], ErrorWrapper] # but recursive, therefore just use:
pydantic/pydantic
929dab6cda28ebb623f6e35676faaf4661053959
I'll look, if this requires breaking changes it can go in v1, if not I guess it could go in v0.32.2 Weirdly doesn't happen if you remove remove `Optional[]`.
diff --git a/tests/test_errors.py b/tests/test_errors.py --- a/tests/test_errors.py +++ b/tests/test_errors.py @@ -1,6 +1,13 @@ +from typing import Optional, Union + import pytest -from pydantic import PydanticTypeError +from pydantic import BaseModel, PydanticTypeError, ValidationError, validator + +try: + from typing_extensions import Literal +except ImportError: + Literal = None def test_pydantic_error(): @@ -14,3 +21,61 @@ def __init__(self, *, test_ctx: int) -> None: with pytest.raises(TestError) as exc_info: raise TestError(test_ctx='test_value') assert str(exc_info.value) == 'test message template "test_value"' + + [email protected](not Literal, reason='typing_extensions not installed') +def test_interval_validation_error(): + class Foo(BaseModel): + model_type: Literal['foo'] + f: int + + class Bar(BaseModel): + model_type: Literal['bar'] + b: int + + class MyModel(BaseModel): + foobar: Union[Foo, Bar] + + @validator('foobar', pre=True, whole=True) + def check_action(cls, v): + if isinstance(v, dict): + model_type = v.get('model_type') + if model_type == 'foo': + return Foo(**v) + if model_type == 'bar': + return Bar(**v) + raise ValueError('not valid Foo or Bar') + + m1 = MyModel(foobar={'model_type': 'foo', 'f': '1'}) + assert m1.foobar.f == 1 + assert isinstance(m1.foobar, Foo) + + m2 = MyModel(foobar={'model_type': 'bar', 'b': '2'}) + assert m2.foobar.b == 2 + assert isinstance(m2.foobar, BaseModel) + + with pytest.raises(ValidationError) as exc_info: + MyModel(foobar={'model_type': 'foo', 'f': 'x'}) + assert exc_info.value.errors() == [ + {'loc': ('foobar', 'f'), 'msg': 'value is not a valid integer', 'type': 'type_error.integer'} + ] + + +def test_error_on_optional(): + class Foobar(BaseModel): + foo: Optional[str] = None + + @validator('foo', always=True, whole=True) + def check_foo(cls, v): + raise ValueError('custom error') + + with pytest.raises(ValidationError) as exc_info: + Foobar(foo='x') + assert exc_info.value.errors() == [{'loc': ('foo',), 'msg': 'custom error', 'type': 'value_error'}] + assert repr(exc_info.value.raw_errors[0]) == ( + "<ErrorWrapper {'loc': ('foo',), 'msg': 'custom error', 'type': 'value_error'}>" + ) + + with pytest.raises(ValidationError) as exc_info: + Foobar(foo=None) + assert exc_info.value.errors() == [{'loc': ('foo',), 'msg': 'custom error', 'type': 'value_error'}]
duplicated errors when validators raise ValidationError # Bug As a work around for #619 I tried the following ```py from pydantic import VERSION, BaseModel, Union, validator from typing_extensions import Literal print('pydantic version:', VERSION) class Foo(BaseModel): model_type: Literal['foo'] f: int class Bar(BaseModel): model_type: Literal['bar'] b: int class MyModel(BaseModel): foobar: Union[Foo, Bar] @validator('foobar', pre=True) def check_action(cls, v): if isinstance(v, dict): model_type = v.get('model_type') if model_type == 'foo': return Foo(**v) if model_type == 'var': return Bar(**v) return v MyModel(foobar={'model_type': 'foo', 'f': 'x'}) ``` Output: ``` pydantic version: 0.32.1 Traceback (most recent call last): File "test.py", line 31, in <module> MyModel(foobar={'model_type': 'foo', 'f': 'x'}) File "pydantic/main.py", line 275, in pydantic.main.BaseModel.__init__ File "pydantic/main.py", line 785, in pydantic.main.validate_model pydantic.error_wrappers.ValidationError: 2 validation errors for MyModel foobar -> f value is not a valid integer (type=type_error.integer) foobar -> f value is not a valid integer (type=type_error.integer) ``` When validators raise `ValidationError` the errors are duplicated. Won't be that common, but should be fixed. Repeated error when validator raises an exception # Bug Please complete: * OS: **Ubuntu** * Python version `import sys; print(sys.version)`: **3.7.4** * Pydantic version `import pydantic; print(pydantic.VERSION)`: **v0.32.1** ```py from typing import Optional from pydantic import BaseModel, validator class Foobar(BaseModel): foo: Optional[str] = None @validator('foo', always=True) def check_foo(cls, v): if not v: raise ValueError('custom error, foo is required') return v print(Foobar(foo='x')) print(Foobar()) ``` Outputs: ``` pydantic.error_wrappers.ValidationError: 2 validation errors for Foobar foo none is not an allowed value (type=type_error.none.not_allowed) foo custom error, foo is required (type=value_error) ``` If i add `pre=True`, the error is even weirder: ``` pydantic.error_wrappers.ValidationError: 2 validation errors for Foobar foo custom error, foo is required (type=value_error) foo custom error, foo is required (type=value_error) ```
0.0
929dab6cda28ebb623f6e35676faaf4661053959
[ "tests/test_errors.py::test_error_on_optional" ]
[ "tests/test_errors.py::test_pydantic_error", "tests/test_errors.py::test_interval_validation_error" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2019-08-11 12:32:10+00:00
mit
4,900
pydantic__pydantic-740
diff --git a/pydantic/dataclasses.py b/pydantic/dataclasses.py --- a/pydantic/dataclasses.py +++ b/pydantic/dataclasses.py @@ -62,9 +62,12 @@ def _process_class( config: Type['BaseConfig'], ) -> 'DataclassType': post_init_original = getattr(_cls, '__post_init__', None) - post_init_post_parse = getattr(_cls, '__post_init_post_parse__', None) if post_init_original and post_init_original.__name__ == '_pydantic_post_init': post_init_original = None + if not post_init_original: + post_init_original = getattr(_cls, '__post_init_original__', None) + + post_init_post_parse = getattr(_cls, '__post_init_post_parse__', None) def _pydantic_post_init(self: 'DataclassType', *initvars: Any) -> None: if post_init_original is not None: @@ -91,6 +94,8 @@ def _pydantic_post_init(self: 'DataclassType', *initvars: Any) -> None: cls.__initialised__ = False cls.__validate__ = classmethod(_validate_dataclass) cls.__get_validators__ = classmethod(_get_validators) + if post_init_original: + cls.__post_init_original__ = post_init_original if cls.__pydantic_model__.__config__.validate_assignment and not frozen: cls.__setattr__ = setattr_validate_assignment
pydantic/pydantic
beaa902d04bd9d9c600ba61cc91a826cb116a4e5
Update: after adding missing `z: float = field(init=False)` in the `Base` class the z attribute is properly preserved (does not get lost between the `__post_init__` and instance completion). But the first issue - `__post_init__` not being called in the first place still stands.
diff --git a/tests/test_dataclasses.py b/tests/test_dataclasses.py --- a/tests/test_dataclasses.py +++ b/tests/test_dataclasses.py @@ -486,3 +486,22 @@ class TestClassVar: tcv = TestClassVar(2) assert tcv.klassvar == "I'm a Class variable" + + +def test_inheritance_post_init(): + post_init_called = False + + @pydantic.dataclasses.dataclass + class Base: + a: int + + def __post_init__(self): + nonlocal post_init_called + post_init_called = True + + @pydantic.dataclasses.dataclass + class Child(Base): + b: int + + Child(a=1, b=2) + assert post_init_called
__post_init__ is not triggered for descendant dataclass The `__post_init__` method of parent is not called in child classes. * OS: **Ubuntu** * Python version `import sys; print(sys.version)`: **3.7.2 (default, Mar 25 2019, 19:29:53) ** * Pydantic version `import pydantic; print(pydantic.VERSION)`: **0.32.1** ```py from dataclasses import dataclass, field from typing import Any # comment the pydantinc import below to see the expected result from pydantic.dataclasses import dataclass @dataclass class Base: x: float y: float def __post_init__(self): print('Called!') self.z = self.x + self.y @dataclass class Child(Base): a: int obj = Child(a=0, x=1.5, y=2.5) print(obj.z) ``` Everything works fine when using the `dataclass` from standard library. After looking through the code I expected that an easy workaround would be to add simple `__post_init__` in child: ```python @dataclass class Child(Base): a: int def __post_init__(self): super().__post_init__() ``` Now I do get 'Called!' message, but the 'z' attribute is not preserved anyway... Do I miss something obvious in the usage of pydantic?
0.0
beaa902d04bd9d9c600ba61cc91a826cb116a4e5
[ "tests/test_dataclasses.py::test_inheritance_post_init" ]
[ "tests/test_dataclasses.py::test_simple", "tests/test_dataclasses.py::test_value_error", "tests/test_dataclasses.py::test_frozen", "tests/test_dataclasses.py::test_validate_assignment", "tests/test_dataclasses.py::test_validate_assignment_error", "tests/test_dataclasses.py::test_not_validate_assignment", "tests/test_dataclasses.py::test_validate_assignment_value_change", "tests/test_dataclasses.py::test_validate_assignment_extra", "tests/test_dataclasses.py::test_post_init", "tests/test_dataclasses.py::test_post_init_inheritance_chain", "tests/test_dataclasses.py::test_post_init_post_parse", "tests/test_dataclasses.py::test_post_init_post_parse_types", "tests/test_dataclasses.py::test_post_init_assignment", "tests/test_dataclasses.py::test_inheritance", "tests/test_dataclasses.py::test_validate_long_string_error", "tests/test_dataclasses.py::test_validate_assigment_long_string_error", "tests/test_dataclasses.py::test_no_validate_assigment_long_string_error", "tests/test_dataclasses.py::test_nested_dataclass", "tests/test_dataclasses.py::test_arbitrary_types_allowed", "tests/test_dataclasses.py::test_nested_dataclass_model", "tests/test_dataclasses.py::test_fields", "tests/test_dataclasses.py::test_schema", "tests/test_dataclasses.py::test_nested_schema", "tests/test_dataclasses.py::test_initvar", "tests/test_dataclasses.py::test_derived_field_from_initvar", "tests/test_dataclasses.py::test_classvar" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2019-08-11 17:19:02+00:00
mit
4,901
pydantic__pydantic-758
diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -151,7 +151,7 @@ def validate_custom_root_type(fields: Dict[str, Field]) -> None: class MetaModel(ABCMeta): - @no_type_check + @no_type_check # noqa C901 def __new__(mcs, name, bases, namespace): fields: Dict[str, Field] = {} config = BaseConfig @@ -205,13 +205,19 @@ def __new__(mcs, name, bases, namespace): and var_name not in class_vars ): validate_field_name(bases, var_name) - fields[var_name] = Field.infer( + inferred = Field.infer( name=var_name, value=value, annotation=annotations.get(var_name), class_validators=vg.get_validators(var_name), config=config, ) + if var_name in fields and inferred.type_ != fields[var_name].type_: + raise TypeError( + f'The type of {name}.{var_name} differs from the new default value; ' + f'if you wish to change the type of this field, please use a type annotation' + ) + fields[var_name] = inferred _custom_root_type = '__root__' in fields if _custom_root_type:
pydantic/pydantic
65d838aa88beed06dd31a798b6ffe37773c66aef
I think I’ve noticed this before with slightly different resulting issues but thought it might just be a limitation of python. Thanks for breaking this down. I think there doesn’t need to be a config value, parent annotations should probably just be used if they exist; if you want to override you should probably just have to do it explicitly. I’m not sure if this would be hard to implement though.
diff --git a/tests/test_edge_cases.py b/tests/test_edge_cases.py --- a/tests/test_edge_cases.py +++ b/tests/test_edge_cases.py @@ -527,9 +527,9 @@ class Foo(BaseModel): class Bar(Foo): x: float = 12.3 - a = 123 + a = 123.0 - assert Bar().dict() == {'x': 12.3, 'a': 123} + assert Bar().dict() == {'x': 12.3, 'a': 123.0} def test_invalid_type(): @@ -615,6 +615,33 @@ class Config: assert str(m) == "Child a=1 b='s'" +def test_annotation_inheritance(): + class A(BaseModel): + integer: int = 1 + + class B(A): + integer = 2 + + assert B.__annotations__['integer'] == int + assert B.__fields__['integer'].type_ == int + + class C(A): + integer: str = 'G' + + assert C.__annotations__['integer'] == str + assert C.__fields__['integer'].type_ == str + + with pytest.raises(TypeError) as exc_info: + + class D(A): + integer = 'G' + + assert str(exc_info.value) == ( + 'The type of D.integer differs from the new default value; ' + 'if you wish to change the type of this field, please use a type annotation' + ) + + def test_string_none(): class Model(BaseModel): a: constr(min_length=20, max_length=1000) = ...
Overriding default value makes __fields__ inconsistent with __annotations__ # Bug Please complete: * OS: **OSX** * Python version `import sys; print(sys.version)`: **3.7.3 | packaged by conda-forge | (default, Jul 1 2019, 14:38:56)** * Pydantic version `import pydantic; print(pydantic.VERSION)`: **0.32.1** **Please read the [docs](https://pydantic-docs.helpmanual.io/) and search through issues to confirm your bug hasn't already been reported before.** Where possible please include a self contained code snippet describing your bug: ```py from pydantic import BaseModel class A(BaseModel): value: int = 1 class B(A): value = 'G' print(A.__annotations__, A.__fields__) # ({'value': int}, {'value': <Field(value type=int default=1)>}) print(A.__annotations__, A.__fields__) # ({'value': int}, {'value': <Field(value type=str default='G')>}) ``` The film type should be int in both cases. [`__annotations__`](https://github.com/samuelcolvin/pydantic/blob/master/pydantic/main.py#L181) is empty in the metaclass so a type will be [inferred](https://github.com/samuelcolvin/pydantic/blob/master/pydantic/fields.py#L169) for the field even [without a type hint](https://github.com/samuelcolvin/pydantic/blob/master/pydantic/main.py#L202). A solution would be to take the parents' annotations into consideration as well, or to introduce another config option to prevent inferring the type of the default value as the type hint for the field. I'm not sure how would the former one affect the rest of the features.
0.0
65d838aa88beed06dd31a798b6ffe37773c66aef
[ "tests/test_edge_cases.py::test_annotation_inheritance" ]
[ "tests/test_edge_cases.py::test_str_bytes", "tests/test_edge_cases.py::test_str_bytes_none", "tests/test_edge_cases.py::test_union_int_str", "tests/test_edge_cases.py::test_union_priority", "tests/test_edge_cases.py::test_typed_list", "tests/test_edge_cases.py::test_typed_set", "tests/test_edge_cases.py::test_dict_dict", "tests/test_edge_cases.py::test_typed_dict[value0-result0]", "tests/test_edge_cases.py::test_typed_dict[value1-result1]", "tests/test_edge_cases.py::test_typed_dict[value2-result2]", "tests/test_edge_cases.py::test_typed_dict_error[1-errors0]", "tests/test_edge_cases.py::test_typed_dict_error[value1-errors1]", "tests/test_edge_cases.py::test_typed_dict_error[value2-errors2]", "tests/test_edge_cases.py::test_dict_key_error", "tests/test_edge_cases.py::test_tuple", "tests/test_edge_cases.py::test_tuple_more", "tests/test_edge_cases.py::test_tuple_length_error", "tests/test_edge_cases.py::test_tuple_invalid", "tests/test_edge_cases.py::test_tuple_value_error", "tests/test_edge_cases.py::test_recursive_list", "tests/test_edge_cases.py::test_recursive_list_error", "tests/test_edge_cases.py::test_list_unions", "tests/test_edge_cases.py::test_recursive_lists", "tests/test_edge_cases.py::test_str_enum", "tests/test_edge_cases.py::test_any_dict", "tests/test_edge_cases.py::test_infer_alias", "tests/test_edge_cases.py::test_alias_error", "tests/test_edge_cases.py::test_annotation_config", "tests/test_edge_cases.py::test_success_values_include", "tests/test_edge_cases.py::test_include_exclude_default", "tests/test_edge_cases.py::test_advanced_exclude", "tests/test_edge_cases.py::test_advanced_value_inclide", "tests/test_edge_cases.py::test_advanced_value_exclude_include", "tests/test_edge_cases.py::test_field_set_ignore_extra", "tests/test_edge_cases.py::test_field_set_allow_extra", "tests/test_edge_cases.py::test_field_set_field_name", "tests/test_edge_cases.py::test_values_order", "tests/test_edge_cases.py::test_inheritance", "tests/test_edge_cases.py::test_invalid_type", "tests/test_edge_cases.py::test_valid_string_types[a", "tests/test_edge_cases.py::test_valid_string_types[some", "tests/test_edge_cases.py::test_valid_string_types[value2-foobar]", "tests/test_edge_cases.py::test_valid_string_types[123-123]", "tests/test_edge_cases.py::test_valid_string_types[123.45-123.45]", "tests/test_edge_cases.py::test_valid_string_types[value5-12.45]", "tests/test_edge_cases.py::test_valid_string_types[True-True]", "tests/test_edge_cases.py::test_valid_string_types[False-False]", "tests/test_edge_cases.py::test_valid_string_types[a10-a10]", "tests/test_edge_cases.py::test_valid_string_types[whatever-whatever]", "tests/test_edge_cases.py::test_invalid_string_types[value0-errors0]", "tests/test_edge_cases.py::test_invalid_string_types[value1-errors1]", "tests/test_edge_cases.py::test_inheritance_config", "tests/test_edge_cases.py::test_partial_inheritance_config", "tests/test_edge_cases.py::test_string_none", "tests/test_edge_cases.py::test_alias_camel_case", "tests/test_edge_cases.py::test_get_field_schema_inherit", "tests/test_edge_cases.py::test_return_errors_ok", "tests/test_edge_cases.py::test_return_errors_error", "tests/test_edge_cases.py::test_optional_required", "tests/test_edge_cases.py::test_invalid_validator", "tests/test_edge_cases.py::test_unable_to_infer", "tests/test_edge_cases.py::test_multiple_errors", "tests/test_edge_cases.py::test_pop_by_alias", "tests/test_edge_cases.py::test_validate_all", "tests/test_edge_cases.py::test_force_extra", "tests/test_edge_cases.py::test_illegal_extra_value", "tests/test_edge_cases.py::test_multiple_inheritance_config", "tests/test_edge_cases.py::test_submodel_different_type", "tests/test_edge_cases.py::test_self", "tests/test_edge_cases.py::test_self_recursive[BaseModel]", "tests/test_edge_cases.py::test_self_recursive[BaseSettings]", "tests/test_edge_cases.py::test_nested_init[BaseModel]", "tests/test_edge_cases.py::test_nested_init[BaseSettings]", "tests/test_edge_cases.py::test_values_attr_deprecation", "tests/test_edge_cases.py::test_init_inspection", "tests/test_edge_cases.py::test_ignored_type" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2019-08-17 08:14:47+00:00
mit
4,902
pydantic__pydantic-761
diff --git a/pydantic/class_validators.py b/pydantic/class_validators.py --- a/pydantic/class_validators.py +++ b/pydantic/class_validators.py @@ -6,7 +6,8 @@ from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Set, Type from .errors import ConfigError -from .utils import AnyCallable, in_ipython +from .typing import AnyCallable +from .utils import in_ipython if TYPE_CHECKING: # pragma: no cover from .main import BaseConfig diff --git a/pydantic/color.py b/pydantic/color.py --- a/pydantic/color.py +++ b/pydantic/color.py @@ -18,7 +18,7 @@ from .utils import almost_equal_floats if TYPE_CHECKING: # pragma: no cover - from .types import CallableGenerator + from .typing import CallableGenerator ColorTuple = Union[Tuple[int, int, int], Tuple[int, int, int, float]] ColorType = Union[ColorTuple, str] diff --git a/pydantic/dataclasses.py b/pydantic/dataclasses.py --- a/pydantic/dataclasses.py +++ b/pydantic/dataclasses.py @@ -6,7 +6,7 @@ from .errors import DataclassTypeError from .fields import Required from .main import create_model, validate_model -from .utils import AnyType +from .typing import AnyType if TYPE_CHECKING: # pragma: no cover from .main import BaseConfig, BaseModel # noqa: F401 diff --git a/pydantic/errors.py b/pydantic/errors.py --- a/pydantic/errors.py +++ b/pydantic/errors.py @@ -2,7 +2,7 @@ from pathlib import Path from typing import Any, Union -from .utils import AnyType, display_as_type +from .typing import AnyType, display_as_type class PydanticErrorMixin: diff --git a/pydantic/fields.py b/pydantic/fields.py --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -22,7 +22,7 @@ from .class_validators import Validator, make_generic_validator from .error_wrappers import ErrorWrapper from .types import Json, JsonWrapper -from .utils import ( +from .typing import ( AnyCallable, AnyType, Callable, @@ -31,8 +31,8 @@ is_literal_type, lenient_issubclass, literal_values, - sequence_like, ) +from .utils import sequence_like from .validators import NoneType, constant_validator, dict_validator, find_validators try: diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -7,22 +7,7 @@ from functools import partial from pathlib import Path from types import FunctionType -from typing import ( - TYPE_CHECKING, - Any, - Callable, - Dict, - Generator, - List, - Optional, - Set, - Tuple, - Type, - TypeVar, - Union, - cast, - no_type_check, -) +from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, Tuple, Type, TypeVar, Union, cast, no_type_check from .class_validators import ValidatorGroup, extract_validators, inherit_validators from .error_wrappers import ErrorWrapper, ValidationError @@ -32,36 +17,18 @@ from .parse import Protocol, load_file, load_str_bytes from .schema import model_schema from .types import PyObject, StrBytes -from .utils import ( - AnyCallable, - AnyType, - ForwardRef, - GetterDict, - ValueItems, - change_exception, - is_classvar, - resolve_annotations, - truncate, - update_field_forward_refs, - validate_field_name, -) +from .typing import AnyCallable, AnyType, ForwardRef, is_classvar, resolve_annotations, update_field_forward_refs +from .utils import GetterDict, ValueItems, change_exception, truncate, validate_field_name if TYPE_CHECKING: # pragma: no cover from .dataclasses import DataclassType # noqa: F401 from .types import CallableGenerator, ModelOrDc from .class_validators import ValidatorListDict - AnyGenerator = Generator[Any, None, None] - TupleGenerator = Generator[Tuple[str, Any], None, None] - DictStrAny = Dict[str, Any] + from .typing import TupleGenerator, DictStrAny, DictAny, SetStr, SetIntStr, DictIntStrAny # noqa: F401 + ConfigType = Type['BaseConfig'] - DictAny = Dict[Any, Any] - SetStr = Set[str] - ListStr = List[str] Model = TypeVar('Model', bound='BaseModel') - IntStr = Union[int, str] - SetIntStr = Set[IntStr] - DictIntStrAny = Dict[IntStr, Any] try: import cython # type: ignore diff --git a/pydantic/schema.py b/pydantic/schema.py --- a/pydantic/schema.py +++ b/pydantic/schema.py @@ -48,7 +48,7 @@ conlist, constr, ) -from .utils import ( +from .typing import ( is_callable_type, is_literal_type, is_new_type, diff --git a/pydantic/types.py b/pydantic/types.py --- a/pydantic/types.py +++ b/pydantic/types.py @@ -13,26 +13,12 @@ ) from pathlib import Path from types import new_class -from typing import ( - TYPE_CHECKING, - Any, - Callable, - Dict, - Generator, - List, - Optional, - Pattern, - Set, - Tuple, - Type, - TypeVar, - Union, - cast, -) +from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Pattern, Set, Tuple, Type, TypeVar, Union, cast from uuid import UUID from . import errors -from .utils import AnyType, change_exception, import_string, make_dsn, url_regex_generator, validate_email +from .typing import AnyType +from .utils import change_exception, import_string, make_dsn, url_regex_generator, validate_email from .validators import ( bytes_validator, decimal_validator, @@ -108,9 +94,8 @@ from .fields import Field from .dataclasses import DataclassType # noqa: F401 from .main import BaseModel, BaseConfig # noqa: F401 - from .utils import AnyCallable + from .typing import CallableGenerator - CallableGenerator = Generator[AnyCallable, None, None] ModelOrDc = Type[Union['BaseModel', 'DataclassType']] diff --git a/pydantic/typing.py b/pydantic/typing.py new file mode 100644 --- /dev/null +++ b/pydantic/typing.py @@ -0,0 +1,200 @@ +import sys +from enum import Enum +from typing import ( # type: ignore + TYPE_CHECKING, + Any, + ClassVar, + Dict, + Generator, + List, + NewType, + Optional, + Set, + Tuple, + Type, + Union, + _eval_type, +) + +try: + from typing import _TypingBase as typing_base # type: ignore +except ImportError: + from typing import _Final as typing_base # type: ignore + +try: + from typing import ForwardRef # type: ignore + + def evaluate_forwardref(type_, globalns, localns): # type: ignore + return type_._evaluate(globalns, localns) + + +except ImportError: + # python 3.6 + from typing import _ForwardRef as ForwardRef # type: ignore + + def evaluate_forwardref(type_, globalns, localns): # type: ignore + return type_._eval_type(globalns, localns) + + +if sys.version_info < (3, 7): + from typing import Callable + + AnyCallable = Callable[..., Any] +else: + from collections.abc import Callable + from typing import Callable as TypingCallable + + AnyCallable = TypingCallable[..., Any] + +try: + from typing_extensions import Literal +except ImportError: + Literal = None # type: ignore + + +if TYPE_CHECKING: # pragma: no cover + from .fields import Field + + TupleGenerator = Generator[Tuple[str, Any], None, None] + DictStrAny = Dict[str, Any] + DictAny = Dict[Any, Any] + SetStr = Set[str] + ListStr = List[str] + IntStr = Union[int, str] + SetIntStr = Set[IntStr] + DictIntStrAny = Dict[IntStr, Any] + CallableGenerator = Generator[AnyCallable, None, None] + +__all__ = ( + 'ForwardRef', + 'Callable', + 'AnyCallable', + 'AnyType', + 'display_as_type', + 'lenient_issubclass', + 'resolve_annotations', + 'is_callable_type', + 'is_literal_type', + 'literal_values', + 'Literal', + 'is_new_type', + 'new_type_supertype', + 'is_classvar', + 'update_field_forward_refs', + 'TupleGenerator', + 'DictStrAny', + 'DictAny', + 'SetStr', + 'ListStr', + 'IntStr', + 'SetIntStr', + 'DictIntStrAny', + 'CallableGenerator', +) + + +AnyType = Type[Any] + + +def display_as_type(v: AnyType) -> str: + if not isinstance(v, typing_base) and not isinstance(v, type): + v = type(v) + + if lenient_issubclass(v, Enum): + if issubclass(v, int): + return 'int' + elif issubclass(v, str): + return 'str' + else: + return 'enum' + + try: + return v.__name__ + except AttributeError: + # happens with unions + return str(v) + + +def lenient_issubclass(cls: Any, class_or_tuple: Union[AnyType, Tuple[AnyType, ...]]) -> bool: + return isinstance(cls, type) and issubclass(cls, class_or_tuple) + + +def resolve_annotations(raw_annotations: Dict[str, AnyType], module_name: Optional[str]) -> Dict[str, AnyType]: + """ + Partially taken from typing.get_type_hints. + + Resolve string or ForwardRef annotations into type objects if possible. + """ + if module_name: + base_globals: Optional[Dict[str, Any]] = sys.modules[module_name].__dict__ + else: + base_globals = None + annotations = {} + for name, value in raw_annotations.items(): + if isinstance(value, str): + if sys.version_info >= (3, 7): + value = ForwardRef(value, is_argument=False) + else: + value = ForwardRef(value) + try: + value = _eval_type(value, base_globals, None) + except NameError: + # this is ok, it can be fixed with update_forward_refs + pass + annotations[name] = value + return annotations + + +def is_callable_type(type_: AnyType) -> bool: + return type_ is Callable or getattr(type_, '__origin__', None) is Callable + + +if sys.version_info >= (3, 7): + + def is_literal_type(type_: AnyType) -> bool: + return Literal is not None and getattr(type_, '__origin__', None) is Literal + + def literal_values(type_: AnyType) -> Tuple[Any, ...]: + return type_.__args__ + + +else: + + def is_literal_type(type_: AnyType) -> bool: + return Literal is not None and hasattr(type_, '__values__') and type_ == Literal[type_.__values__] + + def literal_values(type_: AnyType) -> Tuple[Any, ...]: + return type_.__values__ + + +test_type = NewType('test_type', str) + + +def is_new_type(type_: AnyType) -> bool: + return isinstance(type_, type(test_type)) and hasattr(type_, '__supertype__') + + +def new_type_supertype(type_: AnyType) -> AnyType: + while hasattr(type_, '__supertype__'): + type_ = type_.__supertype__ + return type_ + + +def _check_classvar(v: AnyType) -> bool: + return type(v) == type(ClassVar) and (sys.version_info < (3, 7) or getattr(v, '_name', None) == 'ClassVar') + + +def is_classvar(ann_type: AnyType) -> bool: + return _check_classvar(ann_type) or _check_classvar(getattr(ann_type, '__origin__', None)) + + +def update_field_forward_refs(field: 'Field', globalns: Any, localns: Any) -> None: + """ + Try to update ForwardRefs on fields based on this Field, globalns and localns. + """ + if type(field.type_) == ForwardRef: + field.type_ = evaluate_forwardref(field.type_, globalns, localns or None) + field.prepare() + if field.sub_fields: + for sub_f in field.sub_fields: + update_field_forward_refs(sub_f, globalns=globalns, localns=localns) diff --git a/pydantic/utils.py b/pydantic/utils.py --- a/pydantic/utils.py +++ b/pydantic/utils.py @@ -1,79 +1,24 @@ import inspect import re -import sys from contextlib import contextmanager -from enum import Enum from functools import lru_cache from importlib import import_module -from typing import ( # type: ignore - TYPE_CHECKING, - Any, - ClassVar, - Dict, - Generator, - List, - NewType, - Optional, - Pattern, - Set, - Tuple, - Type, - Union, - _eval_type, - no_type_check, -) - -import pydantic +from typing import TYPE_CHECKING, Any, Dict, Generator, List, Optional, Pattern, Set, Tuple, Type, Union, no_type_check -try: - from typing_extensions import Literal -except ImportError: - Literal = None # type: ignore +from . import errors +from .typing import AnyType try: import email_validator except ImportError: email_validator = None -try: - from typing import _TypingBase as typing_base # type: ignore -except ImportError: - from typing import _Final as typing_base # type: ignore - -try: - from typing import ForwardRef # type: ignore - - def evaluate_forwardref(type_, globalns, localns): # type: ignore - return type_._evaluate(globalns, localns) - - -except ImportError: - # python 3.6 - from typing import _ForwardRef as ForwardRef # type: ignore - - def evaluate_forwardref(type_, globalns, localns): # type: ignore - return type_._eval_type(globalns, localns) - - if TYPE_CHECKING: # pragma: no cover from .main import BaseModel # noqa: F401 - from .main import Field # noqa: F401 - from .main import SetIntStr, DictIntStrAny, IntStr # noqa: F401 - from . import errors # noqa: F401 - -if sys.version_info < (3, 7): - from typing import Callable - - AnyCallable = Callable[..., Any] -else: - from collections.abc import Callable - from typing import Callable as TypingCallable - - AnyCallable = TypingCallable[..., Any] + from .typing import SetIntStr, DictIntStrAny, IntStr # noqa: F401 PRETTY_REGEX = re.compile(r'([\w ]*?) *<(.*)> *') -AnyType = Type[Any] def validate_email(value: str) -> Tuple[str, str]: @@ -100,7 +45,7 @@ def validate_email(value: str) -> Tuple[str, str]: try: email_validator.validate_email(email, check_deliverability=False) except email_validator.EmailNotValidError as e: - raise pydantic.errors.EmailError() from e + raise errors.EmailError() from e return name or email[: email.index('@')], email.lower() @@ -180,25 +125,6 @@ def truncate(v: Union[str], *, max_len: int = 80) -> str: return v -def display_as_type(v: AnyType) -> str: - if not isinstance(v, typing_base) and not isinstance(v, type): - v = type(v) - - if lenient_issubclass(v, Enum): - if issubclass(v, int): - return 'int' - elif issubclass(v, str): - return 'str' - else: - return 'enum' - - try: - return v.__name__ - except AttributeError: - # happens with unions - return str(v) - - ExcType = Type[Exception] @@ -257,10 +183,6 @@ def url_regex_generator(*, relative: bool, require_tld: bool) -> Pattern[str]: ) -def lenient_issubclass(cls: Any, class_or_tuple: Union[AnyType, Tuple[AnyType, ...]]) -> bool: - return isinstance(cls, type) and issubclass(cls, class_or_tuple) - - def in_ipython() -> bool: """ Check whether we're in an ipython environment, including jupyter notebooks. @@ -273,87 +195,6 @@ def in_ipython() -> bool: return True -def resolve_annotations(raw_annotations: Dict[str, AnyType], module_name: Optional[str]) -> Dict[str, AnyType]: - """ - Partially taken from typing.get_type_hints. - - Resolve string or ForwardRef annotations into type objects if possible. - """ - if module_name: - base_globals: Optional[Dict[str, Any]] = sys.modules[module_name].__dict__ - else: - base_globals = None - annotations = {} - for name, value in raw_annotations.items(): - if isinstance(value, str): - if sys.version_info >= (3, 7): - value = ForwardRef(value, is_argument=False) - else: - value = ForwardRef(value) - try: - value = _eval_type(value, base_globals, None) - except NameError: - # this is ok, it can be fixed with update_forward_refs - pass - annotations[name] = value - return annotations - - -def is_callable_type(type_: AnyType) -> bool: - return type_ is Callable or getattr(type_, '__origin__', None) is Callable - - -if sys.version_info >= (3, 7): - - def is_literal_type(type_: AnyType) -> bool: - return Literal is not None and getattr(type_, '__origin__', None) is Literal - - def literal_values(type_: AnyType) -> Tuple[Any, ...]: - return type_.__args__ - - -else: - - def is_literal_type(type_: AnyType) -> bool: - return Literal is not None and hasattr(type_, '__values__') and type_ == Literal[type_.__values__] - - def literal_values(type_: AnyType) -> Tuple[Any, ...]: - return type_.__values__ - - -test_type = NewType('test_type', str) - - -def is_new_type(type_: AnyType) -> bool: - return isinstance(type_, type(test_type)) and hasattr(type_, '__supertype__') - - -def new_type_supertype(type_: AnyType) -> AnyType: - while hasattr(type_, '__supertype__'): - type_ = type_.__supertype__ - return type_ - - -def _check_classvar(v: AnyType) -> bool: - return type(v) == type(ClassVar) and (sys.version_info < (3, 7) or getattr(v, '_name', None) == 'ClassVar') - - -def is_classvar(ann_type: AnyType) -> bool: - return _check_classvar(ann_type) or _check_classvar(getattr(ann_type, '__origin__', None)) - - -def update_field_forward_refs(field: 'Field', globalns: Any, localns: Any) -> None: - """ - Try to update ForwardRefs on fields based on this Field, globalns and localns. - """ - if type(field.type_) == ForwardRef: - field.type_ = evaluate_forwardref(field.type_, globalns, localns or None) - field.prepare() - if field.sub_fields: - for sub_f in field.sub_fields: - update_field_forward_refs(sub_f, globalns=globalns, localns=localns) - - def almost_equal_floats(value_1: float, value_2: float, *, delta: float = 1e-8) -> bool: """ Return True if two floats are almost equal diff --git a/pydantic/validators.py b/pydantic/validators.py --- a/pydantic/validators.py +++ b/pydantic/validators.py @@ -25,17 +25,8 @@ from . import errors from .datetime_parse import parse_date, parse_datetime, parse_duration, parse_time -from .utils import ( - AnyCallable, - AnyType, - ForwardRef, - almost_equal_floats, - change_exception, - display_as_type, - is_callable_type, - is_literal_type, - sequence_like, -) +from .typing import AnyCallable, AnyType, ForwardRef, display_as_type, is_callable_type, is_literal_type +from .utils import almost_equal_floats, change_exception, sequence_like if TYPE_CHECKING: # pragma: no cover from .fields import Field
pydantic/pydantic
65d838aa88beed06dd31a798b6ffe37773c66aef
diff --git a/tests/test_forward_ref.py b/tests/test_forward_ref.py --- a/tests/test_forward_ref.py +++ b/tests/test_forward_ref.py @@ -43,7 +43,7 @@ def test_basic_forward_ref(create_module): """ from typing import Optional from pydantic import BaseModel -from pydantic.utils import ForwardRef +from pydantic.typing import ForwardRef class Foo(BaseModel): a: int @@ -63,7 +63,7 @@ def test_self_forward_ref_module(create_module): module = create_module( """ from pydantic import BaseModel -from pydantic.utils import ForwardRef +from pydantic.typing import ForwardRef Foo = ForwardRef('Foo') @@ -84,7 +84,7 @@ def test_self_forward_ref_collection(create_module): """ from typing import List, Dict from pydantic import BaseModel -from pydantic.utils import ForwardRef +from pydantic.typing import ForwardRef Foo = ForwardRef('Foo') @@ -117,7 +117,7 @@ def test_self_forward_ref_local(create_module): module = create_module( """ from pydantic import BaseModel -from pydantic.utils import ForwardRef +from pydantic.typing import ForwardRef def main(): Foo = ForwardRef('Foo') @@ -139,7 +139,7 @@ def test_missing_update_forward_refs(create_module): module = create_module( """ from pydantic import BaseModel -from pydantic.utils import ForwardRef +from pydantic.typing import ForwardRef Foo = ForwardRef('Foo') @@ -190,7 +190,7 @@ def test_forward_ref_sub_types(create_module): """ from typing import Union from pydantic import BaseModel -from pydantic.utils import ForwardRef +from pydantic.typing import ForwardRef class Leaf(BaseModel): a: str @@ -222,7 +222,7 @@ def test_forward_ref_nested_sub_types(create_module): """ from typing import Tuple, Union from pydantic import BaseModel -from pydantic.utils import ForwardRef +from pydantic.typing import ForwardRef class Leaf(BaseModel): a: str diff --git a/tests/test_schema.py b/tests/test_schema.py --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -65,7 +65,7 @@ constr, urlstr, ) -from pydantic.utils import Literal +from pydantic.typing import Literal try: import email_validator diff --git a/tests/test_utils.py b/tests/test_utils.py --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -4,17 +4,8 @@ import pytest -from pydantic.utils import ( - ValueItems, - display_as_type, - import_string, - is_new_type, - lenient_issubclass, - make_dsn, - new_type_supertype, - truncate, - validate_email, -) +from pydantic.typing import display_as_type, is_new_type, lenient_issubclass, new_type_supertype +from pydantic.utils import ValueItems, import_string, make_dsn, truncate, validate_email try: import email_validator
typing aliases should go in to pydantic.typing We have quite a few aliases for standard lib `typing` to support both 3.6 and 3.7. Upon version 1 we should move all these into a new module `pydantic.typing`.
0.0
65d838aa88beed06dd31a798b6ffe37773c66aef
[ "tests/test_forward_ref.py::test_postponed_annotations", "tests/test_forward_ref.py::test_postponed_annotations_optional", "tests/test_forward_ref.py::test_basic_forward_ref", "tests/test_forward_ref.py::test_missing_update_forward_refs", "tests/test_forward_ref.py::test_forward_ref_dataclass", "tests/test_forward_ref.py::test_forward_ref_dataclass_with_future_annotations", "tests/test_schema.py::test_key", "tests/test_schema.py::test_by_alias", "tests/test_schema.py::test_sub_model", "tests/test_schema.py::test_schema_class", "tests/test_schema.py::test_schema_repr", "tests/test_schema.py::test_schema_class_by_alias", "tests/test_schema.py::test_choices", "tests/test_schema.py::test_json_schema", "tests/test_schema.py::test_list_sub_model", "tests/test_schema.py::test_optional", "tests/test_schema.py::test_any", "tests/test_schema.py::test_set", "tests/test_schema.py::test_const_str", "tests/test_schema.py::test_const_false", "tests/test_schema.py::test_tuple[tuple-expected_schema0]", "tests/test_schema.py::test_tuple[field_type1-expected_schema1]", "tests/test_schema.py::test_tuple[field_type2-expected_schema2]", "tests/test_schema.py::test_bool", "tests/test_schema.py::test_strict_bool", "tests/test_schema.py::test_dict", "tests/test_schema.py::test_list", "tests/test_schema.py::test_list_union_dict[field_type0-expected_schema0]", "tests/test_schema.py::test_list_union_dict[field_type1-expected_schema1]", "tests/test_schema.py::test_list_union_dict[field_type2-expected_schema2]", "tests/test_schema.py::test_list_union_dict[field_type3-expected_schema3]", "tests/test_schema.py::test_list_union_dict[field_type4-expected_schema4]", "tests/test_schema.py::test_date_types[datetime-expected_schema0]", "tests/test_schema.py::test_date_types[date-expected_schema1]", "tests/test_schema.py::test_date_types[time-expected_schema2]", "tests/test_schema.py::test_date_types[timedelta-expected_schema3]", "tests/test_schema.py::test_str_basic_types[field_type0-expected_schema0]", "tests/test_schema.py::test_str_basic_types[field_type1-expected_schema1]", "tests/test_schema.py::test_str_basic_types[field_type2-expected_schema2]", "tests/test_schema.py::test_str_basic_types[field_type3-expected_schema3]", "tests/test_schema.py::test_str_constrained_types[StrictStr-expected_schema0]", "tests/test_schema.py::test_str_constrained_types[ConstrainedStr-expected_schema1]", "tests/test_schema.py::test_str_constrained_types[ConstrainedStrValue-expected_schema2]", "tests/test_schema.py::test_special_str_types[UrlStr-expected_schema0]", "tests/test_schema.py::test_special_str_types[UrlStrValue-expected_schema1]", "tests/test_schema.py::test_special_str_types[DSN-expected_schema2]", "tests/test_schema.py::test_email_str_types[EmailStr-email]", "tests/test_schema.py::test_email_str_types[NameEmail-name-email]", "tests/test_schema.py::test_secret_types[SecretBytes-string]", "tests/test_schema.py::test_secret_types[SecretStr-string]", "tests/test_schema.py::test_special_int_types[ConstrainedInt-expected_schema0]", "tests/test_schema.py::test_special_int_types[ConstrainedIntValue-expected_schema1]", "tests/test_schema.py::test_special_int_types[ConstrainedIntValue-expected_schema2]", "tests/test_schema.py::test_special_int_types[ConstrainedIntValue-expected_schema3]", "tests/test_schema.py::test_special_int_types[PositiveInt-expected_schema4]", "tests/test_schema.py::test_special_int_types[NegativeInt-expected_schema5]", "tests/test_schema.py::test_special_float_types[ConstrainedFloat-expected_schema0]", "tests/test_schema.py::test_special_float_types[ConstrainedFloatValue-expected_schema1]", "tests/test_schema.py::test_special_float_types[ConstrainedFloatValue-expected_schema2]", "tests/test_schema.py::test_special_float_types[ConstrainedFloatValue-expected_schema3]", "tests/test_schema.py::test_special_float_types[PositiveFloat-expected_schema4]", "tests/test_schema.py::test_special_float_types[NegativeFloat-expected_schema5]", "tests/test_schema.py::test_special_float_types[ConstrainedDecimal-expected_schema6]", "tests/test_schema.py::test_special_float_types[ConstrainedDecimalValue-expected_schema7]", "tests/test_schema.py::test_special_float_types[ConstrainedDecimalValue-expected_schema8]", "tests/test_schema.py::test_special_float_types[ConstrainedDecimalValue-expected_schema9]", "tests/test_schema.py::test_uuid_types[UUID-uuid]", "tests/test_schema.py::test_uuid_types[UUID1-uuid1]", "tests/test_schema.py::test_uuid_types[UUID3-uuid3]", "tests/test_schema.py::test_uuid_types[UUID4-uuid4]", "tests/test_schema.py::test_uuid_types[UUID5-uuid5]", "tests/test_schema.py::test_path_types[FilePath-file-path]", "tests/test_schema.py::test_path_types[DirectoryPath-directory-path]", "tests/test_schema.py::test_path_types[Path-path]", "tests/test_schema.py::test_json_type", "tests/test_schema.py::test_ipv4address_type", "tests/test_schema.py::test_ipv6address_type", "tests/test_schema.py::test_ipvanyaddress_type", "tests/test_schema.py::test_ipv4interface_type", "tests/test_schema.py::test_ipv6interface_type", "tests/test_schema.py::test_ipvanyinterface_type", "tests/test_schema.py::test_ipv4network_type", "tests/test_schema.py::test_ipv6network_type", "tests/test_schema.py::test_ipvanynetwork_type", "tests/test_schema.py::test_callable_type[annotation0]", "tests/test_schema.py::test_callable_type[annotation1]", "tests/test_schema.py::test_error_non_supported_types", "tests/test_schema.py::test_flat_models_unique_models", "tests/test_schema.py::test_flat_models_with_submodels", "tests/test_schema.py::test_flat_models_with_submodels_from_sequence", "tests/test_schema.py::test_model_name_maps", "tests/test_schema.py::test_schema_overrides", "tests/test_schema.py::test_schema_from_models", "tests/test_schema.py::test_schema_with_ref_prefix", "tests/test_schema.py::test_schema_no_definitions", "tests/test_schema.py::test_list_default", "tests/test_schema.py::test_dict_default", "tests/test_schema.py::test_constraints_schema[kwargs0-str-expected_extra0]", "tests/test_schema.py::test_constraints_schema[kwargs1-ConstrainedStrValue-expected_extra1]", "tests/test_schema.py::test_constraints_schema[kwargs2-str-expected_extra2]", "tests/test_schema.py::test_constraints_schema[kwargs3-bytes-expected_extra3]", "tests/test_schema.py::test_constraints_schema[kwargs4-str-expected_extra4]", "tests/test_schema.py::test_constraints_schema[kwargs5-int-expected_extra5]", "tests/test_schema.py::test_constraints_schema[kwargs6-int-expected_extra6]", "tests/test_schema.py::test_constraints_schema[kwargs7-int-expected_extra7]", "tests/test_schema.py::test_constraints_schema[kwargs8-int-expected_extra8]", "tests/test_schema.py::test_constraints_schema[kwargs9-int-expected_extra9]", "tests/test_schema.py::test_constraints_schema[kwargs10-float-expected_extra10]", "tests/test_schema.py::test_constraints_schema[kwargs11-float-expected_extra11]", "tests/test_schema.py::test_constraints_schema[kwargs12-float-expected_extra12]", "tests/test_schema.py::test_constraints_schema[kwargs13-float-expected_extra13]", "tests/test_schema.py::test_constraints_schema[kwargs14-float-expected_extra14]", "tests/test_schema.py::test_constraints_schema[kwargs15-Decimal-expected_extra15]", "tests/test_schema.py::test_constraints_schema[kwargs16-Decimal-expected_extra16]", "tests/test_schema.py::test_constraints_schema[kwargs17-Decimal-expected_extra17]", "tests/test_schema.py::test_constraints_schema[kwargs18-Decimal-expected_extra18]", "tests/test_schema.py::test_constraints_schema[kwargs19-Decimal-expected_extra19]", "tests/test_schema.py::test_not_constraints_schema[kwargs0-int-expected0]", "tests/test_schema.py::test_not_constraints_schema[kwargs1-float-expected1]", "tests/test_schema.py::test_not_constraints_schema[kwargs2-Decimal-expected2]", "tests/test_schema.py::test_not_constraints_schema[kwargs3-int-expected3]", "tests/test_schema.py::test_not_constraints_schema[kwargs4-str-expected4]", "tests/test_schema.py::test_not_constraints_schema[kwargs5-bytes-expected5]", "tests/test_schema.py::test_not_constraints_schema[kwargs6-str-expected6]", "tests/test_schema.py::test_not_constraints_schema[kwargs7-bool-expected7]", "tests/test_schema.py::test_constraints_schema_validation[kwargs0-str-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs1-ConstrainedStrValue-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs2-str-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs3-bytes-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs4-str-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs5-bool-True]", "tests/test_schema.py::test_constraints_schema_validation[kwargs6-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs7-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs8-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs9-int-2]", "tests/test_schema.py::test_constraints_schema_validation[kwargs10-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs11-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs12-int-5]", "tests/test_schema.py::test_constraints_schema_validation[kwargs13-float-3.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs14-float-2.1]", "tests/test_schema.py::test_constraints_schema_validation[kwargs15-float-3.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs16-float-4.9]", "tests/test_schema.py::test_constraints_schema_validation[kwargs17-float-3.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs18-float-2.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs19-float-3.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs20-float-5.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs21-float-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs22-float-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs23-Decimal-value23]", "tests/test_schema.py::test_constraints_schema_validation[kwargs24-Decimal-value24]", "tests/test_schema.py::test_constraints_schema_validation[kwargs25-Decimal-value25]", "tests/test_schema.py::test_constraints_schema_validation[kwargs26-Decimal-value26]", "tests/test_schema.py::test_constraints_schema_validation[kwargs27-Decimal-value27]", "tests/test_schema.py::test_constraints_schema_validation[kwargs28-Decimal-value28]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs0-str-foobar]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs1-str-f]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs2-str-bar]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs3-int-2]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs4-int-5]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs5-int-1]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs6-int-6]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs7-float-2.0]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs8-float-5.0]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs9-float-1.9]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs10-float-5.1]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs11-Decimal-value11]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs12-Decimal-value12]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs13-Decimal-value13]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs14-Decimal-value14]", "tests/test_schema.py::test_schema_kwargs", "tests/test_schema.py::test_schema_dict_constr", "tests/test_schema.py::test_bytes_constrained_types[ConstrainedBytes-expected_schema0]", "tests/test_schema.py::test_bytes_constrained_types[ConstrainedBytesValue-expected_schema1]", "tests/test_schema.py::test_optional_dict", "tests/test_schema.py::test_field_with_validator", "tests/test_schema.py::test_known_model_optimization", "tests/test_schema.py::test_root", "tests/test_schema.py::test_root_list", "tests/test_schema.py::test_root_nested_model", "tests/test_schema.py::test_new_type_schema", "tests/test_schema.py::test_literal_schema", "tests/test_schema.py::test_color_type", "tests/test_schema.py::test_model_with_schema_extra", "tests/test_utils.py::test_address_valid[[email protected]@example.com]", "tests/test_utils.py::test_address_valid[[email protected]@muelcolvin.com]", "tests/test_utils.py::test_address_valid[Samuel", "tests/test_utils.py::test_address_valid[foobar", "tests/test_utils.py::test_address_valid[", "tests/test_utils.py::test_address_valid[[email protected]", "tests/test_utils.py::test_address_valid[foo", "tests/test_utils.py::test_address_valid[FOO", "tests/test_utils.py::test_address_valid[<[email protected]>", "tests/test_utils.py::test_address_valid[\\xf1o\\xf1\\[email protected]\\xf1o\\xf1\\xf3-\\xf1o\\xf1\\[email protected]]", "tests/test_utils.py::test_address_valid[\\u6211\\[email protected]\\u6211\\u8cb7-\\u6211\\[email protected]]", "tests/test_utils.py::test_address_valid[\\u7532\\u6590\\u9ed2\\u5ddd\\u65e5\\[email protected]\\u7532\\u6590\\u9ed2\\u5ddd\\u65e5\\u672c-\\u7532\\u6590\\u9ed2\\u5ddd\\u65e5\\[email protected]]", "tests/test_utils.py::test_address_valid[\\u0447\\u0435\\u0431\\u0443\\u0440\\u0430\\u0448\\u043a\\u0430\\u044f\\u0449\\u0438\\u043a-\\u0441-\\u0430\\u043f\\u0435\\u043b\\u044c\\u0441\\u0438\\u043d\\u0430\\u043c\\u0438.\\u0440\\[email protected]\\u0447\\u0435\\u0431\\u0443\\u0440\\u0430\\u0448\\u043a\\u0430\\u044f\\u0449\\u0438\\u043a-\\u0441-\\u0430\\u043f\\u0435\\u043b\\u044c\\u0441\\u0438\\u043d\\u0430\\u043c\\u0438.\\u0440\\u0444-\\u0447\\u0435\\u0431\\u0443\\u0440\\u0430\\u0448\\u043a\\u0430\\u044f\\u0449\\u0438\\u043a-\\u0441-\\u0430\\u043f\\u0435\\u043b\\u044c\\u0441\\u0438\\u043d\\u0430\\u043c\\u0438.\\u0440\\[email protected]]", "tests/test_utils.py::test_address_valid[\\u0909\\u0926\\u093e\\u0939\\u0930\\u0923.\\u092a\\u0930\\u0940\\u0915\\u094d\\[email protected]\\u0909\\u0926\\u093e\\u0939\\u0930\\u0923.\\u092a\\u0930\\u0940\\u0915\\u094d\\u0937-\\u0909\\u0926\\u093e\\u0939\\u0930\\u0923.\\u092a\\u0930\\u0940\\u0915\\u094d\\[email protected]]", "tests/test_utils.py::test_address_valid[[email protected]@example.com]", "tests/test_utils.py::test_address_valid[[email protected]", "tests/test_utils.py::test_address_valid[\\u03b9\\u03c9\\u03ac\\u03bd\\u03bd\\u03b7\\u03c2@\\u03b5\\u03b5\\u03c4\\u03c4.gr-\\u03b9\\u03c9\\u03ac\\u03bd\\u03bd\\u03b7\\u03c2-\\u03b9\\u03c9\\u03ac\\u03bd\\u03bd\\u03b7\\u03c2@\\u03b5\\u03b5\\u03c4\\u03c4.gr]", "tests/test_utils.py::test_address_invalid[f", "tests/test_utils.py::test_address_invalid[foo.bar@exam\\nple.com", "tests/test_utils.py::test_address_invalid[foobar]", "tests/test_utils.py::test_address_invalid[foobar", "tests/test_utils.py::test_address_invalid[@example.com]", "tests/test_utils.py::test_address_invalid[[email protected]]", "tests/test_utils.py::test_address_invalid[[email protected]]", "tests/test_utils.py::test_address_invalid[foo", "tests/test_utils.py::test_address_invalid[foo@[email protected]]", "tests/test_utils.py::test_address_invalid[\\[email protected]]", "tests/test_utils.py::test_address_invalid[\\[email protected]]", "tests/test_utils.py::test_address_invalid[\\[email protected]]", "tests/test_utils.py::test_address_invalid[", "tests/test_utils.py::test_address_invalid[\\[email protected]]", "tests/test_utils.py::test_address_invalid[\"@example.com0]", "tests/test_utils.py::test_address_invalid[\"@example.com1]", "tests/test_utils.py::test_address_invalid[,@example.com]", "tests/test_utils.py::test_empty_dsn", "tests/test_utils.py::test_dsn_odd_user", "tests/test_utils.py::test_import_module", "tests/test_utils.py::test_import_module_invalid", "tests/test_utils.py::test_import_no_attr", "tests/test_utils.py::test_display_as_type[str-str]", "tests/test_utils.py::test_display_as_type[string-str]", "tests/test_utils.py::test_display_as_type[value2-typing.Union[str,", "tests/test_utils.py::test_display_as_type_enum", "tests/test_utils.py::test_display_as_type_enum_int", "tests/test_utils.py::test_display_as_type_enum_str", "tests/test_utils.py::test_lenient_issubclass", "tests/test_utils.py::test_lenient_issubclass_is_lenient", "tests/test_utils.py::test_truncate_type", "tests/test_utils.py::test_value_items", "tests/test_utils.py::test_value_items_error", "tests/test_utils.py::test_is_new_type", "tests/test_utils.py::test_new_type_supertype" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-08-17 18:31:57+00:00
mit
4,903
pydantic__pydantic-770
diff --git a/pydantic/fields.py b/pydantic/fields.py --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -31,7 +31,6 @@ display_as_type, is_literal_type, lenient_issubclass, - literal_values, sequence_like, ) from .validators import NoneType, constant_validator, dict_validator, find_validators @@ -197,11 +196,7 @@ def _populate_sub_fields(self) -> None: # noqa: C901 (ignore complexity) # python 3.7 only, Pattern is a typing object but without sub fields return if is_literal_type(self.type_): - values = literal_values(self.type_) - if len(values) > 1: - self.type_ = Union[tuple(Literal[value] for value in values)] - else: - return + return origin = getattr(self.type_, '__origin__', None) if origin is None: # field is not "typing" object eg. Union, Dict, List etc. diff --git a/pydantic/schema.py b/pydantic/schema.py --- a/pydantic/schema.py +++ b/pydantic/schema.py @@ -49,6 +49,7 @@ constr, ) from .utils import ( + Literal, is_callable_type, is_literal_type, is_new_type, @@ -758,8 +759,16 @@ def field_singleton_schema( # noqa: C901 (ignore complexity) if is_new_type(field_type): field_type = new_type_supertype(field_type) if is_literal_type(field_type): - # If there were multiple literal values, field.sub_fields would not be falsy - literal_value = literal_values(field_type)[0] + values = literal_values(field_type) + if len(values) > 1: + return field_schema( + multivalue_literal_field_for_schema(values, field), + by_alias=by_alias, + model_name_map=model_name_map, + ref_prefix=ref_prefix, + known_models=known_models, + ) + literal_value = values[0] field_type = type(literal_value) f_schema['const'] = literal_value if issubclass(field_type, Enum): @@ -807,6 +816,19 @@ def field_singleton_schema( # noqa: C901 (ignore complexity) raise ValueError(f'Value not declarable with JSON Schema, field: {field}') +def multivalue_literal_field_for_schema(values: Tuple[Any, ...], field: Field) -> Field: + return Field( + name=field.name, + type_=Union[tuple(Literal[value] for value in values)], + class_validators=field.class_validators, + model_config=field.model_config, + default=field.default, + required=field.required, + alias=field.alias, + schema=field.schema, + ) + + def encode_default(dft: Any) -> Any: if isinstance(dft, (int, float, str)): return dft
pydantic/pydantic
dbe9514e0df1bea1a8ce9df8defd8f170a633116
Thanks for making an issue, I’ll take a look.
diff --git a/tests/test_types.py b/tests/test_types.py --- a/tests/test_types.py +++ b/tests/test_types.py @@ -1730,14 +1730,8 @@ class Model(BaseModel): assert exc_info.value.errors() == [ { 'loc': ('a_or_b',), - 'msg': "unexpected value; permitted: 'a'", + 'msg': "unexpected value; permitted: 'a', 'b'", 'type': 'value_error.const', - 'ctx': {'given': 'c', 'permitted': ('a',)}, - }, - { - 'loc': ('a_or_b',), - 'msg': "unexpected value; permitted: 'b'", - 'type': 'value_error.const', - 'ctx': {'given': 'c', 'permitted': ('b',)}, - }, + 'ctx': {'given': 'c', 'permitted': ('a', 'b')}, + } ]
Duplicated errors when using a Literal choice # Bug Please complete: * OS: macOS Mojave 10.14.6 (18G87) * Python version `import sys; print(sys.version)`: 3.7.4 (default, Jul 9 2019, 18:13:23) [Clang 10.0.1 (clang-1001.0.46.4)] * Pydantic version `import pydantic; print(pydantic.VERSION)`: 0.32.2 I tried looking for an existing issue, [found this](https://www.amazon.com/Low-Culture-Everything-Around-Computer/dp/B07381HM47), but didn't seem appropriate. In #651, examples on how to use the `Literal` option were introduced, including [this example](https://github.com/samuelcolvin/pydantic/blob/bc600145184979d774e40c5d98f7a76d90ca616a/docs/examples/literal1.py) showing a single validation error, and the acceptable choices. Running this file today produces two errors, instead of one, and doesn't populate the `permitted` value correctly. ```shellsession $ python docs/examples/literal1.py 2 validation errors for Pie flavor unexpected value; permitted: 'apple' (type=value_error.const; given=cherry; permitted=('apple',)) flavor unexpected value; permitted: 'pumpkin' (type=value_error.const; given=cherry; permitted=('pumpkin',)) ```
0.0
dbe9514e0df1bea1a8ce9df8defd8f170a633116
[ "tests/test_types.py::test_literal_multiple" ]
[ "tests/test_types.py::test_constrained_bytes_good", "tests/test_types.py::test_constrained_bytes_default", "tests/test_types.py::test_constrained_bytes_too_long", "tests/test_types.py::test_constrained_list_good", "tests/test_types.py::test_constrained_list_default", "tests/test_types.py::test_constrained_list_too_long", "tests/test_types.py::test_constrained_list_too_short", "tests/test_types.py::test_constrained_list_constraints", "tests/test_types.py::test_constrained_list_item_type_fails", "tests/test_types.py::test_constrained_str_good", "tests/test_types.py::test_constrained_str_default", "tests/test_types.py::test_constrained_str_too_long", "tests/test_types.py::test_dsn_compute", "tests/test_types.py::test_dsn_define", "tests/test_types.py::test_dsn_pw_host", "tests/test_types.py::test_dsn_no_driver", "tests/test_types.py::test_module_import", "tests/test_types.py::test_pyobject_none", "tests/test_types.py::test_pyobject_callable", "tests/test_types.py::test_default_validators[bool_check-True-True]", "tests/test_types.py::test_default_validators[bool_check-False-False]", "tests/test_types.py::test_default_validators[bool_check-None-False]", "tests/test_types.py::test_default_validators[bool_check--False]", "tests/test_types.py::test_default_validators[bool_check-1-True0]", "tests/test_types.py::test_default_validators[bool_check-TRUE-True0]", "tests/test_types.py::test_default_validators[bool_check-TRUE-True1]", "tests/test_types.py::test_default_validators[bool_check-true-True]", "tests/test_types.py::test_default_validators[bool_check-1-True1]", "tests/test_types.py::test_default_validators[bool_check-2-False]", "tests/test_types.py::test_default_validators[bool_check-2-True]", "tests/test_types.py::test_default_validators[bool_check-on-True]", "tests/test_types.py::test_default_validators[bool_check-yes-True]", "tests/test_types.py::test_default_validators[str_check-s-s0]", "tests/test_types.py::test_default_validators[str_check-", "tests/test_types.py::test_default_validators[str_check-s-s1]", "tests/test_types.py::test_default_validators[str_check-1-1]", "tests/test_types.py::test_default_validators[str_check-xxxxxxxxxxx-ValidationError0]", "tests/test_types.py::test_default_validators[str_check-xxxxxxxxxxx-ValidationError1]", "tests/test_types.py::test_default_validators[bytes_check-s-s0]", "tests/test_types.py::test_default_validators[bytes_check-", "tests/test_types.py::test_default_validators[bytes_check-s-s1]", "tests/test_types.py::test_default_validators[bytes_check-1-1]", "tests/test_types.py::test_default_validators[bytes_check-value25-xx]", "tests/test_types.py::test_default_validators[bytes_check-True-True]", "tests/test_types.py::test_default_validators[bytes_check-False-False]", "tests/test_types.py::test_default_validators[bytes_check-value28-ValidationError]", "tests/test_types.py::test_default_validators[bytes_check-xxxxxxxxxxx-ValidationError0]", "tests/test_types.py::test_default_validators[bytes_check-xxxxxxxxxxx-ValidationError1]", "tests/test_types.py::test_default_validators[int_check-1-10]", "tests/test_types.py::test_default_validators[int_check-1.9-1]", "tests/test_types.py::test_default_validators[int_check-1-11]", "tests/test_types.py::test_default_validators[int_check-1.9-ValidationError]", "tests/test_types.py::test_default_validators[int_check-1-12]", "tests/test_types.py::test_default_validators[int_check-12-120]", "tests/test_types.py::test_default_validators[int_check-12-121]", "tests/test_types.py::test_default_validators[int_check-12-122]", "tests/test_types.py::test_default_validators[float_check-1-1.00]", "tests/test_types.py::test_default_validators[float_check-1.0-1.00]", "tests/test_types.py::test_default_validators[float_check-1.0-1.01]", "tests/test_types.py::test_default_validators[float_check-1-1.01]", "tests/test_types.py::test_default_validators[float_check-1.0-1.02]", "tests/test_types.py::test_default_validators[float_check-1-1.02]", "tests/test_types.py::test_default_validators[uuid_check-ebcdab58-6eb8-46fb-a190-d07a33e9eac8-result45]", "tests/test_types.py::test_default_validators[uuid_check-value46-result46]", "tests/test_types.py::test_default_validators[uuid_check-ebcdab58-6eb8-46fb-a190-d07a33e9eac8-result47]", "tests/test_types.py::test_default_validators[uuid_check-ebcdab58-6eb8-46fb-a190--ValidationError]", "tests/test_types.py::test_default_validators[uuid_check-123-ValidationError]", "tests/test_types.py::test_default_validators[decimal_check-42.24-result50]", "tests/test_types.py::test_default_validators[decimal_check-42.24-result51]", "tests/test_types.py::test_default_validators[decimal_check-42.24-result52]", "tests/test_types.py::test_default_validators[decimal_check-", "tests/test_types.py::test_default_validators[decimal_check-value54-result54]", "tests/test_types.py::test_default_validators[decimal_check-not", "tests/test_types.py::test_default_validators[decimal_check-NaN-ValidationError]", "tests/test_types.py::test_string_too_long", "tests/test_types.py::test_string_too_short", "tests/test_types.py::test_datetime_successful", "tests/test_types.py::test_datetime_errors", "tests/test_types.py::test_enum_successful", "tests/test_types.py::test_enum_fails", "tests/test_types.py::test_int_enum_successful_for_str_int", "tests/test_types.py::test_string_success", "tests/test_types.py::test_string_fails", "tests/test_types.py::test_dict", "tests/test_types.py::test_list_success[value0-result0]", "tests/test_types.py::test_list_success[value1-result1]", "tests/test_types.py::test_list_success[value2-result2]", "tests/test_types.py::test_list_success[value3-result3]", "tests/test_types.py::test_list_fails[1230]", "tests/test_types.py::test_list_fails[1231]", "tests/test_types.py::test_ordered_dict", "tests/test_types.py::test_tuple_success[value0-result0]", "tests/test_types.py::test_tuple_success[value1-result1]", "tests/test_types.py::test_tuple_success[value2-result2]", "tests/test_types.py::test_tuple_success[value3-result3]", "tests/test_types.py::test_tuple_fails[1230]", "tests/test_types.py::test_tuple_fails[1231]", "tests/test_types.py::test_tuple_variable_len_success[value0-int-result0]", "tests/test_types.py::test_tuple_variable_len_success[value1-int-result1]", "tests/test_types.py::test_tuple_variable_len_success[value2-int-result2]", "tests/test_types.py::test_tuple_variable_len_success[value3-str-result3]", "tests/test_types.py::test_tuple_variable_len_fails[value0-str-exc0]", "tests/test_types.py::test_tuple_variable_len_fails[value1-str-exc1]", "tests/test_types.py::test_set_success[value0-result0]", "tests/test_types.py::test_set_success[value1-result1]", "tests/test_types.py::test_set_success[value2-result2]", "tests/test_types.py::test_set_success[value3-result3]", "tests/test_types.py::test_set_fails[1230]", "tests/test_types.py::test_set_fails[1231]", "tests/test_types.py::test_list_type_fails", "tests/test_types.py::test_set_type_fails", "tests/test_types.py::test_sequence_success[int-value0-result0]", "tests/test_types.py::test_sequence_success[int-value1-result1]", "tests/test_types.py::test_sequence_success[float-value2-result2]", "tests/test_types.py::test_sequence_success[cls3-value3-result3]", "tests/test_types.py::test_sequence_success[cls4-value4-result4]", "tests/test_types.py::test_sequence_generator_success[int-value0-result0]", "tests/test_types.py::test_sequence_generator_success[float-value1-result1]", "tests/test_types.py::test_sequence_generator_success[str-value2-result2]", "tests/test_types.py::test_sequence_generator_fails[int-value0-errors0]", "tests/test_types.py::test_sequence_generator_fails[float-value1-errors1]", "tests/test_types.py::test_sequence_fails[int-value0-errors0]", "tests/test_types.py::test_sequence_fails[int-value1-errors1]", "tests/test_types.py::test_sequence_fails[float-value2-errors2]", "tests/test_types.py::test_sequence_fails[float-value3-errors3]", "tests/test_types.py::test_sequence_fails[float-value4-errors4]", "tests/test_types.py::test_sequence_fails[cls5-value5-errors5]", "tests/test_types.py::test_sequence_fails[cls6-value6-errors6]", "tests/test_types.py::test_sequence_fails[cls7-value7-errors7]", "tests/test_types.py::test_int_validation", "tests/test_types.py::test_float_validation", "tests/test_types.py::test_strict_str", "tests/test_types.py::test_strict_bool", "tests/test_types.py::test_uuid_error", "tests/test_types.py::test_uuid_validation", "tests/test_types.py::test_anystr_strip_whitespace_enabled", "tests/test_types.py::test_anystr_strip_whitespace_disabled", "tests/test_types.py::test_decimal_validation[ConstrainedDecimalValue-value0-result0]", "tests/test_types.py::test_decimal_validation[ConstrainedDecimalValue-value1-result1]", "tests/test_types.py::test_decimal_validation[ConstrainedDecimalValue-value2-result2]", "tests/test_types.py::test_decimal_validation[ConstrainedDecimalValue-value3-result3]", "tests/test_types.py::test_decimal_validation[ConstrainedDecimalValue-value4-result4]", "tests/test_types.py::test_decimal_validation[ConstrainedDecimalValue-value5-result5]", "tests/test_types.py::test_decimal_validation[ConstrainedDecimalValue-value6-result6]", "tests/test_types.py::test_decimal_validation[ConstrainedDecimalValue-value7-result7]", "tests/test_types.py::test_decimal_validation[ConstrainedDecimalValue-value8-result8]", "tests/test_types.py::test_decimal_validation[ConstrainedDecimalValue-value9-result9]", "tests/test_types.py::test_decimal_validation[ConstrainedDecimalValue-value10-result10]", "tests/test_types.py::test_decimal_validation[ConstrainedDecimalValue-value11-result11]", "tests/test_types.py::test_decimal_validation[ConstrainedDecimalValue-value12-result12]", "tests/test_types.py::test_decimal_validation[ConstrainedDecimalValue-value13-result13]", "tests/test_types.py::test_decimal_validation[ConstrainedDecimalValue-value14-result14]", "tests/test_types.py::test_decimal_validation[ConstrainedDecimalValue-value15-result15]", "tests/test_types.py::test_decimal_validation[ConstrainedDecimalValue-value16-result16]", "tests/test_types.py::test_decimal_validation[ConstrainedDecimalValue-value17-result17]", "tests/test_types.py::test_decimal_validation[ConstrainedDecimalValue-value18-result18]", "tests/test_types.py::test_decimal_validation[ConstrainedDecimalValue-value19-result19]", "tests/test_types.py::test_decimal_validation[ConstrainedDecimalValue-value20-result20]", "tests/test_types.py::test_decimal_validation[ConstrainedDecimalValue-NaN-result21]", "tests/test_types.py::test_decimal_validation[ConstrainedDecimalValue--NaN-result22]", "tests/test_types.py::test_decimal_validation[ConstrainedDecimalValue-+NaN-result23]", "tests/test_types.py::test_decimal_validation[ConstrainedDecimalValue-sNaN-result24]", "tests/test_types.py::test_decimal_validation[ConstrainedDecimalValue--sNaN-result25]", "tests/test_types.py::test_decimal_validation[ConstrainedDecimalValue-+sNaN-result26]", "tests/test_types.py::test_decimal_validation[ConstrainedDecimalValue-Inf-result27]", "tests/test_types.py::test_decimal_validation[ConstrainedDecimalValue--Inf-result28]", "tests/test_types.py::test_decimal_validation[ConstrainedDecimalValue-+Inf-result29]", "tests/test_types.py::test_decimal_validation[ConstrainedDecimalValue-Infinity-result30]", "tests/test_types.py::test_decimal_validation[ConstrainedDecimalValue--Infinity-result31]", "tests/test_types.py::test_decimal_validation[ConstrainedDecimalValue--Infinity-result32]", "tests/test_types.py::test_decimal_validation[ConstrainedDecimalValue-value33-result33]", "tests/test_types.py::test_decimal_validation[ConstrainedDecimalValue-value34-result34]", "tests/test_types.py::test_decimal_validation[ConstrainedDecimalValue-value35-result35]", "tests/test_types.py::test_decimal_validation[ConstrainedDecimalValue-value36-result36]", "tests/test_types.py::test_decimal_validation[ConstrainedDecimalValue-value37-result37]", "tests/test_types.py::test_decimal_validation[ConstrainedDecimalValue-value38-result38]", "tests/test_types.py::test_decimal_validation[ConstrainedDecimalValue-value39-result39]", "tests/test_types.py::test_decimal_validation[ConstrainedDecimalValue-value40-result40]", "tests/test_types.py::test_decimal_validation[ConstrainedDecimalValue-value41-result41]", "tests/test_types.py::test_decimal_validation[ConstrainedDecimalValue-value42-result42]", "tests/test_types.py::test_decimal_validation[ConstrainedDecimalValue-value43-result43]", "tests/test_types.py::test_decimal_validation[ConstrainedDecimalValue-value44-result44]", "tests/test_types.py::test_decimal_validation[ConstrainedDecimalValue-value45-result45]", "tests/test_types.py::test_path_validation_success[/test/path-result0]", "tests/test_types.py::test_path_validation_success[value1-result1]", "tests/test_types.py::test_path_validation_fails", "tests/test_types.py::test_file_path_validation_success[tests/test_types.py-result0]", "tests/test_types.py::test_file_path_validation_success[value1-result1]", "tests/test_types.py::test_file_path_validation_fails[nonexistentfile-errors0]", "tests/test_types.py::test_file_path_validation_fails[value1-errors1]", "tests/test_types.py::test_file_path_validation_fails[tests-errors2]", "tests/test_types.py::test_file_path_validation_fails[value3-errors3]", "tests/test_types.py::test_directory_path_validation_success[tests-result0]", "tests/test_types.py::test_directory_path_validation_success[value1-result1]", "tests/test_types.py::test_directory_path_validation_fails[nonexistentdirectory-errors0]", "tests/test_types.py::test_directory_path_validation_fails[value1-errors1]", "tests/test_types.py::test_directory_path_validation_fails[tests/test_types.py-errors2]", "tests/test_types.py::test_directory_path_validation_fails[value3-errors3]", "tests/test_types.py::test_number_gt", "tests/test_types.py::test_number_ge", "tests/test_types.py::test_number_lt", "tests/test_types.py::test_number_le", "tests/test_types.py::test_number_multiple_of_int_valid[10]", "tests/test_types.py::test_number_multiple_of_int_valid[100]", "tests/test_types.py::test_number_multiple_of_int_valid[20]", "tests/test_types.py::test_number_multiple_of_int_invalid[1337]", "tests/test_types.py::test_number_multiple_of_int_invalid[23]", "tests/test_types.py::test_number_multiple_of_int_invalid[6]", "tests/test_types.py::test_number_multiple_of_int_invalid[14]", "tests/test_types.py::test_number_multiple_of_float_valid[0.2]", "tests/test_types.py::test_number_multiple_of_float_valid[0.3]", "tests/test_types.py::test_number_multiple_of_float_valid[0.4]", "tests/test_types.py::test_number_multiple_of_float_valid[0.5]", "tests/test_types.py::test_number_multiple_of_float_valid[1]", "tests/test_types.py::test_number_multiple_of_float_invalid[0.07]", "tests/test_types.py::test_number_multiple_of_float_invalid[1.27]", "tests/test_types.py::test_number_multiple_of_float_invalid[1.003]", "tests/test_types.py::test_bounds_config_exceptions[conint]", "tests/test_types.py::test_bounds_config_exceptions[confloat]", "tests/test_types.py::test_bounds_config_exceptions[condecimal]", "tests/test_types.py::test_new_type_success", "tests/test_types.py::test_new_type_fails", "tests/test_types.py::test_valid_simple_json", "tests/test_types.py::test_invalid_simple_json", "tests/test_types.py::test_valid_simple_json_bytes", "tests/test_types.py::test_valid_detailed_json", "tests/test_types.py::test_invalid_detailed_json_value_error", "tests/test_types.py::test_valid_detailed_json_bytes", "tests/test_types.py::test_invalid_detailed_json_type_error", "tests/test_types.py::test_json_not_str", "tests/test_types.py::test_pattern", "tests/test_types.py::test_pattern_error", "tests/test_types.py::test_secretstr", "tests/test_types.py::test_secretstr_error", "tests/test_types.py::test_secretbytes", "tests/test_types.py::test_secretbytes_error", "tests/test_types.py::test_generic_without_params", "tests/test_types.py::test_generic_without_params_error", "tests/test_types.py::test_literal_single" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-08-20 04:44:05+00:00
mit
4,904
pydantic__pydantic-772
diff --git a/pydantic/schema.py b/pydantic/schema.py --- a/pydantic/schema.py +++ b/pydantic/schema.py @@ -277,7 +277,7 @@ def field_schema( ref_prefix = ref_prefix or default_prefix schema_overrides = False schema = cast('Schema', field.schema) - s = dict(title=schema.title or field.alias.title()) + s = dict(title=schema.title or field.alias.title().replace('_', ' ')) if schema.title: schema_overrides = True
pydantic/pydantic
6235ac2153e6efd6e60985839d765b7ce5a59954
Would you accept this change as a PR? PR sounds good. I guess no harm in including this in v1 since it's so small. Given this breaks a lot of fastapi tests (presumably mostly just requiring modifications to generated schemas), @tiangolo do you have any issues with this change? Okay, let's wait until v1.1. except I guess if it's a breaking change, it would make more sense to include it in v1. @tiangolo what do you think? @tiangolo would you like me to also update the title field in the schema unit tests to ensure that's all it is? I'm pro this change, it seems like a no brainer, especially if it's a breaking change, to include it in v1. @skewty please fix the PR and I'll merge.
diff --git a/tests/test_dataclasses.py b/tests/test_dataclasses.py --- a/tests/test_dataclasses.py +++ b/tests/test_dataclasses.py @@ -381,7 +381,7 @@ class User: 'properties': { 'id': {'title': 'Id', 'type': 'integer'}, 'name': {'title': 'Name', 'default': 'John Doe', 'type': 'string'}, - 'signup_ts': {'title': 'Signup_Ts', 'type': 'string', 'format': 'date-time'}, + 'signup_ts': {'title': 'Signup Ts', 'type': 'string', 'format': 'date-time'}, }, 'required': ['id'], } diff --git a/tests/test_schema.py b/tests/test_schema.py --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -705,7 +705,7 @@ class Model(BaseModel): assert model_schema == { 'title': 'Model', 'type': 'object', - 'properties': {'ip_address': {'title': 'Ip_Address', 'type': 'string', 'format': 'ipv4'}}, + 'properties': {'ip_address': {'title': 'Ip Address', 'type': 'string', 'format': 'ipv4'}}, 'required': ['ip_address'], } @@ -718,7 +718,7 @@ class Model(BaseModel): assert model_schema == { 'title': 'Model', 'type': 'object', - 'properties': {'ip_address': {'title': 'Ip_Address', 'type': 'string', 'format': 'ipv6'}}, + 'properties': {'ip_address': {'title': 'Ip Address', 'type': 'string', 'format': 'ipv6'}}, 'required': ['ip_address'], } @@ -731,7 +731,7 @@ class Model(BaseModel): assert model_schema == { 'title': 'Model', 'type': 'object', - 'properties': {'ip_address': {'title': 'Ip_Address', 'type': 'string', 'format': 'ipvanyaddress'}}, + 'properties': {'ip_address': {'title': 'Ip Address', 'type': 'string', 'format': 'ipvanyaddress'}}, 'required': ['ip_address'], } @@ -744,7 +744,7 @@ class Model(BaseModel): assert model_schema == { 'title': 'Model', 'type': 'object', - 'properties': {'ip_interface': {'title': 'Ip_Interface', 'type': 'string', 'format': 'ipv4interface'}}, + 'properties': {'ip_interface': {'title': 'Ip Interface', 'type': 'string', 'format': 'ipv4interface'}}, 'required': ['ip_interface'], } @@ -757,7 +757,7 @@ class Model(BaseModel): assert model_schema == { 'title': 'Model', 'type': 'object', - 'properties': {'ip_interface': {'title': 'Ip_Interface', 'type': 'string', 'format': 'ipv6interface'}}, + 'properties': {'ip_interface': {'title': 'Ip Interface', 'type': 'string', 'format': 'ipv6interface'}}, 'required': ['ip_interface'], } @@ -770,7 +770,7 @@ class Model(BaseModel): assert model_schema == { 'title': 'Model', 'type': 'object', - 'properties': {'ip_interface': {'title': 'Ip_Interface', 'type': 'string', 'format': 'ipvanyinterface'}}, + 'properties': {'ip_interface': {'title': 'Ip Interface', 'type': 'string', 'format': 'ipvanyinterface'}}, 'required': ['ip_interface'], } @@ -783,7 +783,7 @@ class Model(BaseModel): assert model_schema == { 'title': 'Model', 'type': 'object', - 'properties': {'ip_network': {'title': 'Ip_Network', 'type': 'string', 'format': 'ipv4network'}}, + 'properties': {'ip_network': {'title': 'Ip Network', 'type': 'string', 'format': 'ipv4network'}}, 'required': ['ip_network'], } @@ -796,7 +796,7 @@ class Model(BaseModel): assert model_schema == { 'title': 'Model', 'type': 'object', - 'properties': {'ip_network': {'title': 'Ip_Network', 'type': 'string', 'format': 'ipv6network'}}, + 'properties': {'ip_network': {'title': 'Ip Network', 'type': 'string', 'format': 'ipv6network'}}, 'required': ['ip_network'], } @@ -809,7 +809,7 @@ class Model(BaseModel): assert model_schema == { 'title': 'Model', 'type': 'object', - 'properties': {'ip_network': {'title': 'Ip_Network', 'type': 'string', 'format': 'ipvanynetwork'}}, + 'properties': {'ip_network': {'title': 'Ip Network', 'type': 'string', 'format': 'ipvanynetwork'}}, 'required': ['ip_network'], } @@ -1368,7 +1368,7 @@ class Model(BaseModel): 'type': 'object', 'properties': { 'dep': {'$ref': '#/definitions/Dep'}, - 'dep_l': {'title': 'Dep_L', 'type': 'array', 'items': {'$ref': '#/definitions/Dep'}}, + 'dep_l': {'title': 'Dep L', 'type': 'array', 'items': {'$ref': '#/definitions/Dep'}}, }, 'required': ['dep', 'dep_l'], 'definitions': {
Improve auto-generated JSON Schema title when none provided # Feature Request ## schema.py:280 Current: ```python s = dict(title=schema.title or field.alias.title()) ``` Proposed: ```python # provide better title for PEP8 snake case names s = dict(title=schema.title or field.alias.title().replace('_', ' ')) ```
0.0
6235ac2153e6efd6e60985839d765b7ce5a59954
[ "tests/test_dataclasses.py::test_schema", "tests/test_schema.py::test_ipv4address_type", "tests/test_schema.py::test_ipv6address_type", "tests/test_schema.py::test_ipvanyaddress_type", "tests/test_schema.py::test_ipv4interface_type", "tests/test_schema.py::test_ipv6interface_type", "tests/test_schema.py::test_ipvanyinterface_type", "tests/test_schema.py::test_ipv4network_type", "tests/test_schema.py::test_ipv6network_type", "tests/test_schema.py::test_ipvanynetwork_type", "tests/test_schema.py::test_known_model_optimization" ]
[ "tests/test_dataclasses.py::test_simple", "tests/test_dataclasses.py::test_value_error", "tests/test_dataclasses.py::test_frozen", "tests/test_dataclasses.py::test_validate_assignment", "tests/test_dataclasses.py::test_validate_assignment_error", "tests/test_dataclasses.py::test_not_validate_assignment", "tests/test_dataclasses.py::test_post_init", "tests/test_dataclasses.py::test_post_init_inheritance_chain", "tests/test_dataclasses.py::test_post_init_post_parse", "tests/test_dataclasses.py::test_post_init_post_parse_types", "tests/test_dataclasses.py::test_post_init_assignment", "tests/test_dataclasses.py::test_inheritance", "tests/test_dataclasses.py::test_validate_long_string_error", "tests/test_dataclasses.py::test_validate_assigment_long_string_error", "tests/test_dataclasses.py::test_no_validate_assigment_long_string_error", "tests/test_dataclasses.py::test_nested_dataclass", "tests/test_dataclasses.py::test_arbitrary_types_allowed", "tests/test_dataclasses.py::test_nested_dataclass_model", "tests/test_dataclasses.py::test_fields", "tests/test_dataclasses.py::test_nested_schema", "tests/test_dataclasses.py::test_initvar", "tests/test_dataclasses.py::test_derived_field_from_initvar", "tests/test_dataclasses.py::test_initvars_post_init", "tests/test_dataclasses.py::test_initvars_post_init_post_parse", "tests/test_dataclasses.py::test_classvar", "tests/test_schema.py::test_key", "tests/test_schema.py::test_by_alias", "tests/test_schema.py::test_sub_model", "tests/test_schema.py::test_schema_class", "tests/test_schema.py::test_schema_repr", "tests/test_schema.py::test_schema_class_by_alias", "tests/test_schema.py::test_choices", "tests/test_schema.py::test_json_schema", "tests/test_schema.py::test_list_sub_model", "tests/test_schema.py::test_optional", "tests/test_schema.py::test_any", "tests/test_schema.py::test_set", "tests/test_schema.py::test_const_str", "tests/test_schema.py::test_const_false", "tests/test_schema.py::test_tuple[tuple-expected_schema0]", "tests/test_schema.py::test_tuple[field_type1-expected_schema1]", "tests/test_schema.py::test_tuple[field_type2-expected_schema2]", "tests/test_schema.py::test_bool", "tests/test_schema.py::test_strict_bool", "tests/test_schema.py::test_dict", "tests/test_schema.py::test_list", "tests/test_schema.py::test_list_union_dict[field_type0-expected_schema0]", "tests/test_schema.py::test_list_union_dict[field_type1-expected_schema1]", "tests/test_schema.py::test_list_union_dict[field_type2-expected_schema2]", "tests/test_schema.py::test_list_union_dict[field_type3-expected_schema3]", "tests/test_schema.py::test_list_union_dict[field_type4-expected_schema4]", "tests/test_schema.py::test_date_types[datetime-expected_schema0]", "tests/test_schema.py::test_date_types[date-expected_schema1]", "tests/test_schema.py::test_date_types[time-expected_schema2]", "tests/test_schema.py::test_date_types[timedelta-expected_schema3]", "tests/test_schema.py::test_str_basic_types[field_type0-expected_schema0]", "tests/test_schema.py::test_str_basic_types[field_type1-expected_schema1]", "tests/test_schema.py::test_str_basic_types[field_type2-expected_schema2]", "tests/test_schema.py::test_str_basic_types[field_type3-expected_schema3]", "tests/test_schema.py::test_str_constrained_types[StrictStr-expected_schema0]", "tests/test_schema.py::test_str_constrained_types[ConstrainedStr-expected_schema1]", "tests/test_schema.py::test_str_constrained_types[ConstrainedStrValue-expected_schema2]", "tests/test_schema.py::test_special_str_types[UrlStr-expected_schema0]", "tests/test_schema.py::test_special_str_types[UrlStrValue-expected_schema1]", "tests/test_schema.py::test_special_str_types[DSN-expected_schema2]", "tests/test_schema.py::test_email_str_types[EmailStr-email]", "tests/test_schema.py::test_email_str_types[NameEmail-name-email]", "tests/test_schema.py::test_secret_types[SecretBytes-string]", "tests/test_schema.py::test_secret_types[SecretStr-string]", "tests/test_schema.py::test_special_int_types[ConstrainedInt-expected_schema0]", "tests/test_schema.py::test_special_int_types[ConstrainedIntValue-expected_schema1]", "tests/test_schema.py::test_special_int_types[ConstrainedIntValue-expected_schema2]", "tests/test_schema.py::test_special_int_types[ConstrainedIntValue-expected_schema3]", "tests/test_schema.py::test_special_int_types[PositiveInt-expected_schema4]", "tests/test_schema.py::test_special_int_types[NegativeInt-expected_schema5]", "tests/test_schema.py::test_special_float_types[ConstrainedFloat-expected_schema0]", "tests/test_schema.py::test_special_float_types[ConstrainedFloatValue-expected_schema1]", "tests/test_schema.py::test_special_float_types[ConstrainedFloatValue-expected_schema2]", "tests/test_schema.py::test_special_float_types[ConstrainedFloatValue-expected_schema3]", "tests/test_schema.py::test_special_float_types[PositiveFloat-expected_schema4]", "tests/test_schema.py::test_special_float_types[NegativeFloat-expected_schema5]", "tests/test_schema.py::test_special_float_types[ConstrainedDecimal-expected_schema6]", "tests/test_schema.py::test_special_float_types[ConstrainedDecimalValue-expected_schema7]", "tests/test_schema.py::test_special_float_types[ConstrainedDecimalValue-expected_schema8]", "tests/test_schema.py::test_special_float_types[ConstrainedDecimalValue-expected_schema9]", "tests/test_schema.py::test_uuid_types[UUID-uuid]", "tests/test_schema.py::test_uuid_types[UUID1-uuid1]", "tests/test_schema.py::test_uuid_types[UUID3-uuid3]", "tests/test_schema.py::test_uuid_types[UUID4-uuid4]", "tests/test_schema.py::test_uuid_types[UUID5-uuid5]", "tests/test_schema.py::test_path_types[FilePath-file-path]", "tests/test_schema.py::test_path_types[DirectoryPath-directory-path]", "tests/test_schema.py::test_path_types[Path-path]", "tests/test_schema.py::test_json_type", "tests/test_schema.py::test_callable_type[annotation0]", "tests/test_schema.py::test_callable_type[annotation1]", "tests/test_schema.py::test_error_non_supported_types", "tests/test_schema.py::test_flat_models_unique_models", "tests/test_schema.py::test_flat_models_with_submodels", "tests/test_schema.py::test_flat_models_with_submodels_from_sequence", "tests/test_schema.py::test_model_name_maps", "tests/test_schema.py::test_schema_overrides", "tests/test_schema.py::test_schema_from_models", "tests/test_schema.py::test_schema_with_ref_prefix", "tests/test_schema.py::test_schema_no_definitions", "tests/test_schema.py::test_list_default", "tests/test_schema.py::test_dict_default", "tests/test_schema.py::test_constraints_schema[kwargs0-str-expected_extra0]", "tests/test_schema.py::test_constraints_schema[kwargs1-ConstrainedStrValue-expected_extra1]", "tests/test_schema.py::test_constraints_schema[kwargs2-str-expected_extra2]", "tests/test_schema.py::test_constraints_schema[kwargs3-bytes-expected_extra3]", "tests/test_schema.py::test_constraints_schema[kwargs4-str-expected_extra4]", "tests/test_schema.py::test_constraints_schema[kwargs5-int-expected_extra5]", "tests/test_schema.py::test_constraints_schema[kwargs6-int-expected_extra6]", "tests/test_schema.py::test_constraints_schema[kwargs7-int-expected_extra7]", "tests/test_schema.py::test_constraints_schema[kwargs8-int-expected_extra8]", "tests/test_schema.py::test_constraints_schema[kwargs9-int-expected_extra9]", "tests/test_schema.py::test_constraints_schema[kwargs10-float-expected_extra10]", "tests/test_schema.py::test_constraints_schema[kwargs11-float-expected_extra11]", "tests/test_schema.py::test_constraints_schema[kwargs12-float-expected_extra12]", "tests/test_schema.py::test_constraints_schema[kwargs13-float-expected_extra13]", "tests/test_schema.py::test_constraints_schema[kwargs14-float-expected_extra14]", "tests/test_schema.py::test_constraints_schema[kwargs15-Decimal-expected_extra15]", "tests/test_schema.py::test_constraints_schema[kwargs16-Decimal-expected_extra16]", "tests/test_schema.py::test_constraints_schema[kwargs17-Decimal-expected_extra17]", "tests/test_schema.py::test_constraints_schema[kwargs18-Decimal-expected_extra18]", "tests/test_schema.py::test_constraints_schema[kwargs19-Decimal-expected_extra19]", "tests/test_schema.py::test_not_constraints_schema[kwargs0-int-expected0]", "tests/test_schema.py::test_not_constraints_schema[kwargs1-float-expected1]", "tests/test_schema.py::test_not_constraints_schema[kwargs2-Decimal-expected2]", "tests/test_schema.py::test_not_constraints_schema[kwargs3-int-expected3]", "tests/test_schema.py::test_not_constraints_schema[kwargs4-str-expected4]", "tests/test_schema.py::test_not_constraints_schema[kwargs5-bytes-expected5]", "tests/test_schema.py::test_not_constraints_schema[kwargs6-str-expected6]", "tests/test_schema.py::test_not_constraints_schema[kwargs7-bool-expected7]", "tests/test_schema.py::test_constraints_schema_validation[kwargs0-str-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs1-ConstrainedStrValue-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs2-str-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs3-bytes-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs4-str-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs5-bool-True]", "tests/test_schema.py::test_constraints_schema_validation[kwargs6-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs7-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs8-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs9-int-2]", "tests/test_schema.py::test_constraints_schema_validation[kwargs10-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs11-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs12-int-5]", "tests/test_schema.py::test_constraints_schema_validation[kwargs13-float-3.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs14-float-2.1]", "tests/test_schema.py::test_constraints_schema_validation[kwargs15-float-3.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs16-float-4.9]", "tests/test_schema.py::test_constraints_schema_validation[kwargs17-float-3.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs18-float-2.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs19-float-3.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs20-float-5.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs21-float-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs22-float-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs23-Decimal-value23]", "tests/test_schema.py::test_constraints_schema_validation[kwargs24-Decimal-value24]", "tests/test_schema.py::test_constraints_schema_validation[kwargs25-Decimal-value25]", "tests/test_schema.py::test_constraints_schema_validation[kwargs26-Decimal-value26]", "tests/test_schema.py::test_constraints_schema_validation[kwargs27-Decimal-value27]", "tests/test_schema.py::test_constraints_schema_validation[kwargs28-Decimal-value28]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs0-str-foobar]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs1-str-f]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs2-str-bar]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs3-int-2]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs4-int-5]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs5-int-1]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs6-int-6]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs7-float-2.0]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs8-float-5.0]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs9-float-1.9]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs10-float-5.1]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs11-Decimal-value11]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs12-Decimal-value12]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs13-Decimal-value13]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs14-Decimal-value14]", "tests/test_schema.py::test_schema_kwargs", "tests/test_schema.py::test_schema_dict_constr", "tests/test_schema.py::test_bytes_constrained_types[ConstrainedBytes-expected_schema0]", "tests/test_schema.py::test_bytes_constrained_types[ConstrainedBytesValue-expected_schema1]", "tests/test_schema.py::test_optional_dict", "tests/test_schema.py::test_field_with_validator", "tests/test_schema.py::test_root", "tests/test_schema.py::test_root_list", "tests/test_schema.py::test_root_nested_model", "tests/test_schema.py::test_new_type_schema", "tests/test_schema.py::test_literal_schema", "tests/test_schema.py::test_color_type", "tests/test_schema.py::test_model_with_schema_extra" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2019-08-21 03:10:11+00:00
mit
4,905
pydantic__pydantic-790
diff --git a/docs/examples/payment_card_number.py b/docs/examples/payment_card_number.py new file mode 100644 --- /dev/null +++ b/docs/examples/payment_card_number.py @@ -0,0 +1,28 @@ +from datetime import date + +from pydantic import BaseModel +from pydantic.types import PaymentCardBrand, PaymentCardNumber, constr + +class Card(BaseModel): + name: constr(strip_whitespace=True, min_length=1) + number: PaymentCardNumber + exp: date + + @property + def brand(self) -> PaymentCardBrand: + return self.number.brand + + @property + def expired(self) -> bool: + return self.exp < date.today() + +card = Card( + name='Georg Wilhelm Friedrich Hegel', + number='4000000000000002', + exp=date(2023, 9, 30) +) + +assert card.number.brand == PaymentCardBrand.visa +assert card.number.bin == '400000' +assert card.number.last4 == '0002' +assert card.number.masked == '400000******0002' diff --git a/pydantic/errors.py b/pydantic/errors.py --- a/pydantic/errors.py +++ b/pydantic/errors.py @@ -402,3 +402,18 @@ class ColorError(PydanticValueError): class StrictBoolError(PydanticValueError): msg_template = 'value is not a valid boolean' + + +class NotDigitError(PydanticValueError): + code = 'payment_card_number.digits' + msg_template = 'card number is not all digits' + + +class LuhnValidationError(PydanticValueError): + code = 'payment_card_number.luhn_check' + msg_template = 'card number is not luhn valid' + + +class InvalidLengthForBrand(PydanticValueError): + code = 'payment_card_number.invalid_length_for_brand' + msg_template = 'Length for a {brand} card must be {required_length}' diff --git a/pydantic/types.py b/pydantic/types.py --- a/pydantic/types.py +++ b/pydantic/types.py @@ -1,9 +1,10 @@ import json import re from decimal import Decimal +from enum import Enum from pathlib import Path from types import new_class -from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Pattern, Type, TypeVar, Union, cast +from typing import TYPE_CHECKING, Any, Callable, ClassVar, Dict, List, Optional, Pattern, Type, TypeVar, Union, cast from uuid import UUID from . import errors @@ -63,6 +64,7 @@ 'SecretStr', 'SecretBytes', 'StrictBool', + 'PaymentCardNumber', ] NoneStr = Optional[str] @@ -502,3 +504,101 @@ def display(self) -> str: def get_secret_value(self) -> bytes: return self._secret_value + + +class PaymentCardBrand(Enum): + amex = 'American Express' + mastercard = 'Mastercard' + visa = 'Visa' + other = 'other' + + def __str__(self) -> str: + return self.value + + +class PaymentCardNumber(str): + """ + Based on: https://en.wikipedia.org/wiki/Payment_card_number + """ + + strip_whitespace: ClassVar[bool] = True + min_length: ClassVar[int] = 12 + max_length: ClassVar[int] = 19 + bin: str + last4: str + brand: PaymentCardBrand + + def __init__(self, card_number: str): + self.bin = card_number[:6] + self.last4 = card_number[-4:] + self.brand = self._get_brand(card_number) + + @classmethod + def __get_validators__(cls) -> 'CallableGenerator': + yield not_none_validator + yield str_validator + yield constr_strip_whitespace + yield constr_length_validator + yield cls.validate_digits + yield cls.validate_luhn_check_digit + yield cls + yield cls.validate_length_for_brand + + @property + def masked(self) -> str: + num_masked = len(self) - 10 # len(bin) + len(last4) == 10 + return f'{self.bin}{"*" * num_masked}{self.last4}' + + @classmethod + def validate_digits(cls, card_number: str) -> str: + if not card_number.isdigit(): + raise errors.NotDigitError + return card_number + + @classmethod + def validate_luhn_check_digit(cls, card_number: str) -> str: + """ + Based on: https://en.wikipedia.org/wiki/Luhn_algorithm + """ + sum_ = int(card_number[-1]) + length = len(card_number) + parity = length % 2 + for i in range(length - 1): + digit = int(card_number[i]) + if i % 2 == parity: + digit *= 2 + sum_ += digit + valid = sum_ % 10 == 0 + if not valid: + raise errors.LuhnValidationError + return card_number + + @classmethod + def validate_length_for_brand(cls, card_number: 'PaymentCardNumber') -> 'PaymentCardNumber': + """ + Validate length based on BIN for major brands: + https://en.wikipedia.org/wiki/Payment_card_number#Issuer_identification_number_(IIN) + """ + if card_number.brand is (PaymentCardBrand.visa or PaymentCardBrand.mastercard): + required_length = 16 + valid = len(card_number) == required_length + elif card_number.brand is PaymentCardBrand.amex: + required_length = 15 + valid = len(card_number) == required_length + else: + valid = True + if not valid: + raise errors.InvalidLengthForBrand(brand=card_number.brand, required_length=required_length) + return card_number + + @staticmethod + def _get_brand(card_number: str) -> PaymentCardBrand: + if card_number[0] == '4': + brand = PaymentCardBrand.visa + elif 51 <= int(card_number[:2]) <= 55: + brand = PaymentCardBrand.mastercard + elif card_number[:2] in {'34', '37'}: + brand = PaymentCardBrand.amex + else: + brand = PaymentCardBrand.other + return brand
pydantic/pydantic
f08fd2fee738145efa894199fe47e49a84c96aa1
diff --git a/tests/test_types_payment_card_number.py b/tests/test_types_payment_card_number.py new file mode 100644 --- /dev/null +++ b/tests/test_types_payment_card_number.py @@ -0,0 +1,90 @@ +from collections import namedtuple +from typing import Any + +import pytest + +from pydantic import BaseModel, ValidationError +from pydantic.errors import InvalidLengthForBrand, LuhnValidationError, NotDigitError +from pydantic.types import PaymentCardBrand, PaymentCardNumber + +VALID_AMEX = '370000000000002' +VALID_MC = '5100000000000003' +VALID_VISA = '4000000000000002' +VALID_OTHER = '2000000000000000008' +LUHN_INVALID = '4000000000000000' +LEN_INVALID = '40000000000000006' + +# Mock PaymentCardNumber +PCN = namedtuple('PaymentCardNumber', ['card_number', 'brand']) +PCN.__len__ = lambda v: len(v.card_number) + + +class PaymentCard(BaseModel): + card_number: PaymentCardNumber + + +def test_validate_digits(): + digits = '12345' + assert PaymentCardNumber.validate_digits(digits) == digits + with pytest.raises(NotDigitError): + PaymentCardNumber.validate_digits('hello') + + +def test_validate_luhn_check_digit(): + assert PaymentCardNumber.validate_luhn_check_digit(VALID_VISA) == VALID_VISA + with pytest.raises(LuhnValidationError): + PaymentCardNumber.validate_luhn_check_digit(LUHN_INVALID) + + [email protected]( + 'card_number, brand, valid', + [ + (VALID_VISA, PaymentCardBrand.visa, True), + (VALID_MC, PaymentCardBrand.mastercard, True), + (VALID_AMEX, PaymentCardBrand.amex, True), + (VALID_OTHER, PaymentCardBrand.other, True), + (LEN_INVALID, PaymentCardBrand.visa, False), + ], +) +def test_length_for_brand(card_number: str, brand: PaymentCardBrand, valid: bool): + pcn = PCN(card_number, brand) + if valid: + assert PaymentCardNumber.validate_length_for_brand(pcn) == pcn + else: + with pytest.raises(InvalidLengthForBrand): + PaymentCardNumber.validate_length_for_brand(pcn) + + [email protected]( + 'card_number, brand', + [ + (VALID_AMEX, PaymentCardBrand.amex), + (VALID_MC, PaymentCardBrand.mastercard), + (VALID_VISA, PaymentCardBrand.visa), + (VALID_OTHER, PaymentCardBrand.other), + ], +) +def test_get_brand(card_number: str, brand: PaymentCardBrand): + assert PaymentCardNumber._get_brand(card_number) == brand + + +def test_valid(): + card = PaymentCard(card_number=VALID_VISA) + assert str(card.card_number) == VALID_VISA + assert card.card_number.masked == '400000******0002' + + [email protected]( + 'card_number, error_message', + [ + (None, 'type_error.none.not_allowed'), + ('1' * 11, 'value_error.any_str.min_length'), + ('1' * 20, 'value_error.any_str.max_length'), + ('h' * 16, 'value_error.payment_card_number.digits'), + (LUHN_INVALID, 'value_error.payment_card_number.luhn_check'), + (LEN_INVALID, 'value_error.payment_card_number.invalid_length_for_brand'), + ], +) +def test_error_types(card_number: Any, error_message: str): + with pytest.raises(ValidationError, match=error_message): + PaymentCard(card_number=card_number)
Add validation for payment card numbers A common validation for any payment system or e-commerce site is validating a debit / credit card number. The validation would like _something_ like this and be defined in `pydantic.types`: ```python class PaymentCardNumber(str): """ Based on: https://en.wikipedia.org/wiki/Payment_card_number """ strip_whitespace = True min_length: int = 12 max_length: int = 19 @classmethod def __get_validators__(cls) -> 'CallableGenerator': yield not_none_validator yield str_validator yield constr_strip_whitespace yield constr_length_validator yield cls.validate_digits yield cls.validate_length_based_on_bin yield cls.validate_luhn_check_digit @classmethod def validate_digits(cls, value: str) -> str: if not value.isdigit(): raise ValueError('payment card number must be digits') return value @classmethod def validate_length_based_on_bin(cls, value: str) -> str: """ Validate length based on BIN for major brands: https://en.wikipedia.org/wiki/Payment_card_number#Issuer_identification_number_(IIN) """ if value[0] == '4': # Visa length = 16 brand = 'Visa' elif 51 <= int(value[:1]) <= 55: # Most common Mastercard range length = 16 brand = 'Mastercard' elif value[:1] in {'34', '37'}: # Amex length = 15 brand = 'Amex' else: length = None brand = None if length and len(value) != length: raise ValueError(f'Length for a {brand} card must be {length}') return value @classmethod def validate_luhn_check_digit(cls, value: str) -> str: """ Based on: https://en.wikipedia.org/wiki/Luhn_algorithm """ sum_ = int(value[-1]) length = len(value) parity = length % 2 for i in range(length - 1): digit = int(value[i]) if i % 2 == parity: digit *= 2 if digit > 9: digit -= 9 sum_ += digit valid = sum_ % 10 == 0 if not valid: raise ValueError('Card number is not luhn valid') return value ```
0.0
f08fd2fee738145efa894199fe47e49a84c96aa1
[ "tests/test_types_payment_card_number.py::test_validate_digits", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit", "tests/test_types_payment_card_number.py::test_length_for_brand[4000000000000002-Visa-True]", "tests/test_types_payment_card_number.py::test_length_for_brand[5100000000000003-Mastercard-True]", "tests/test_types_payment_card_number.py::test_length_for_brand[370000000000002-American", "tests/test_types_payment_card_number.py::test_length_for_brand[2000000000000000008-other-True]", "tests/test_types_payment_card_number.py::test_length_for_brand[40000000000000006-Visa-False]", "tests/test_types_payment_card_number.py::test_get_brand[370000000000002-American", "tests/test_types_payment_card_number.py::test_get_brand[5100000000000003-Mastercard]", "tests/test_types_payment_card_number.py::test_get_brand[4000000000000002-Visa]", "tests/test_types_payment_card_number.py::test_get_brand[2000000000000000008-other]", "tests/test_types_payment_card_number.py::test_valid", "tests/test_types_payment_card_number.py::test_error_types[None-type_error.none.not_allowed]", "tests/test_types_payment_card_number.py::test_error_types[11111111111-value_error.any_str.min_length]", "tests/test_types_payment_card_number.py::test_error_types[11111111111111111111-value_error.any_str.max_length]", "tests/test_types_payment_card_number.py::test_error_types[hhhhhhhhhhhhhhhh-value_error.payment_card_number.digits]", "tests/test_types_payment_card_number.py::test_error_types[4000000000000000-value_error.payment_card_number.luhn_check]", "tests/test_types_payment_card_number.py::test_error_types[40000000000000006-value_error.payment_card_number.invalid_length_for_brand]" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2019-09-01 19:41:33+00:00
mit
4,906
pydantic__pydantic-794
diff --git a/pydantic/error_wrappers.py b/pydantic/error_wrappers.py --- a/pydantic/error_wrappers.py +++ b/pydantic/error_wrappers.py @@ -105,7 +105,7 @@ def flatten_errors( else: yield error.dict(config, loc_prefix=loc) elif isinstance(error, list): - yield from flatten_errors(error, config) + yield from flatten_errors(error, config, loc=loc) else: raise RuntimeError(f'Unknown error object: {error}') diff --git a/pydantic/fields.py b/pydantic/fields.py --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -106,8 +106,8 @@ def __init__( self.sub_fields: Optional[List[Field]] = None self.key_field: Optional[Field] = None self.validators: 'ValidatorsList' = [] - self.whole_pre_validators: Optional['ValidatorsList'] = None - self.whole_post_validators: Optional['ValidatorsList'] = None + self.whole_pre_validators: 'ValidatorsList' = [] + self.whole_post_validators: 'ValidatorsList' = [] self.parse_json: bool = False self.shape: int = SHAPE_SINGLETON self.prepare() @@ -253,9 +253,8 @@ def _populate_sub_fields(self) -> None: # noqa: C901 (ignore complexity) else: raise TypeError(f'Fields of type "{origin}" are not supported.') - if getattr(self.type_, '__origin__', None): - # type_ has been refined eg. as the type of a List and sub_fields needs to be populated - self.sub_fields = [self._create_sub_type(self.type_, '_' + self.name)] + # type_ has been refined eg. as the type of a List and sub_fields needs to be populated + self.sub_fields = [self._create_sub_type(self.type_, '_' + self.name)] def _create_sub_type(self, type_: AnyType, name: str, *, for_keys: bool = False) -> 'Field': return self.__class__( @@ -272,13 +271,16 @@ def _populate_validators(self) -> None: v_funcs = ( *[v.func for v in class_validators_ if not v.whole and v.pre], *(get_validators() if get_validators else list(find_validators(self.type_, self.model_config))), - self.schema is not None and self.schema.const and constant_validator, *[v.func for v in class_validators_ if not v.whole and not v.pre], ) self.validators = self._prep_vals(v_funcs) + # Add const validator + if self.schema is not None and self.schema.const: + self.whole_pre_validators = self._prep_vals([constant_validator]) + if class_validators_: - self.whole_pre_validators = self._prep_vals(v.func for v in class_validators_ if v.whole and v.pre) + self.whole_pre_validators.extend(self._prep_vals(v.func for v in class_validators_ if v.whole and v.pre)) self.whole_post_validators = self._prep_vals(v.func for v in class_validators_ if v.whole and not v.pre) @staticmethod
pydantic/pydantic
1b467da11f79a91125b3d2f80b4b499139a14daa
please try master, since this might have been fixed/changed by #582 Same on master. wording has indeed changed but there is still a difference between the given and permitted where the former shows a single item and the latter shows the whole list... Thanks for checking, PR welcome.
diff --git a/tests/test_main.py b/tests/test_main.py --- a/tests/test_main.py +++ b/tests/test_main.py @@ -397,6 +397,112 @@ class Model(BaseModel): ] +def test_const_list(): + class SubModel(BaseModel): + b: int + + class Model(BaseModel): + a: List[SubModel] = Schema([SubModel(b=1), SubModel(b=2), SubModel(b=3)], const=True) + b: List[SubModel] = Schema([{'b': 4}, {'b': 5}, {'b': 6}], const=True) + + m = Model() + assert m.a == [SubModel(b=1), SubModel(b=2), SubModel(b=3)] + assert m.b == [SubModel(b=4), SubModel(b=5), SubModel(b=6)] + assert m.schema() == { + 'definitions': { + 'SubModel': { + 'properties': {'b': {'title': 'B', 'type': 'integer'}}, + 'required': ['b'], + 'title': 'SubModel', + 'type': 'object', + } + }, + 'properties': { + 'a': { + 'const': [SubModel(b=1), SubModel(b=2), SubModel(b=3)], + 'items': {'$ref': '#/definitions/SubModel'}, + 'title': 'A', + 'type': 'array', + }, + 'b': { + 'const': [{'b': 4}, {'b': 5}, {'b': 6}], + 'items': {'$ref': '#/definitions/SubModel'}, + 'title': 'B', + 'type': 'array', + }, + }, + 'title': 'Model', + 'type': 'object', + } + + +def test_const_list_with_wrong_value(): + class SubModel(BaseModel): + b: int + + class Model(BaseModel): + a: List[SubModel] = Schema([SubModel(b=1), SubModel(b=2), SubModel(b=3)], const=True) + b: List[SubModel] = Schema([{'b': 4}, {'b': 5}, {'b': 6}], const=True) + + with pytest.raises(ValidationError) as exc_info: + Model(a=[{'b': 3}, {'b': 1}, {'b': 2}], b=[{'b': 6}, {'b': 5}]) + + assert exc_info.value.errors() == [ + { + 'ctx': { + 'given': [{'b': 3}, {'b': 1}, {'b': 2}], + 'permitted': [[SubModel(b=1), SubModel(b=2), SubModel(b=3)]], + }, + 'loc': ('a',), + 'msg': 'unexpected value; permitted: [<SubModel b=1>, <SubModel b=2>, <SubModel b=3>]', + 'type': 'value_error.const', + }, + { + 'ctx': {'given': [{'b': 6}, {'b': 5}], 'permitted': [[{'b': 4}, {'b': 5}, {'b': 6}]]}, + 'loc': ('b',), + 'msg': "unexpected value; permitted: [{'b': 4}, {'b': 5}, {'b': 6}]", + 'type': 'value_error.const', + }, + ] + + with pytest.raises(ValidationError) as exc_info: + Model(a=[SubModel(b=3), SubModel(b=1), SubModel(b=2)], b=[SubModel(b=3), SubModel(b=1)]) + + assert exc_info.value.errors() == [ + { + 'ctx': { + 'given': [SubModel(b=3), SubModel(b=1), SubModel(b=2)], + 'permitted': [[SubModel(b=1), SubModel(b=2), SubModel(b=3)]], + }, + 'loc': ('a',), + 'msg': 'unexpected value; permitted: [<SubModel b=1>, <SubModel b=2>, <SubModel b=3>]', + 'type': 'value_error.const', + }, + { + 'ctx': {'given': [SubModel(b=3), SubModel(b=1)], 'permitted': [[{'b': 4}, {'b': 5}, {'b': 6}]]}, + 'loc': ('b',), + 'msg': "unexpected value; permitted: [{'b': 4}, {'b': 5}, {'b': 6}]", + 'type': 'value_error.const', + }, + ] + + +def test_const_validation_json_serializable(): + class SubForm(BaseModel): + field: int + + class Form(BaseModel): + field1: SubForm = Schema({'field': 2}, const=True) + field2: List[SubForm] = Schema([{'field': 2}], const=True) + + with pytest.raises(ValidationError) as exc_info: + # Fails + Form(field1={'field': 1}, field2=[{'field': 1}]) + + # This should not raise an Json error + exc_info.value.json() + + class ValidateAssignmentModel(BaseModel): a: int = 2 b: constr(min_length=1)
const validation with list gives unexpected error # Feature Request | Bug For bugs/questions: * OS: Linux * Python version `import sys; print(sys.version)`: 3.7.3 * Pydantic version `import pydantic; print(pydantic.VERSION)`: 0.29 I expect the following test (not yet in code base) to succeed ```py def test_const_list_with_wrong_value(): class SubModel(BaseModel): b: int class Model(BaseModel): a: List[SubModel] = Schema([{"b": 1}, {"b": 2}, {"b": 3}], const=True) with pytest.raises(ValidationError) as exc_info: Model(a=[{"b": 3}, {"b": 1}, {"b": 2}]) assert exc_info.value.errors() == [ { 'ctx': {'const': SubModel(b=1), 'given': SubModel(b=3)}, 'loc': ('a', 0), 'msg': "expected constant value {'b': 1}", 'type': 'value_error.const', }, { 'ctx': {'const': SubModel(b=2), 'given': SubModel(b=1)}, 'loc': ('a', 1), 'msg': "expected constant value {'b': 2}", 'type': 'value_error.const', }, { 'ctx': {'const': SubModel(b=3), 'given': SubModel(b=2)}, 'loc': ('a', 2), 'msg': "expected constant value {'b': 3}", 'type': 'value_error.const', }, ] ``` However it fails with: ``` E assert [{'ctx': {'co...error.const'}] == [{'ctx': {'con...error.const'}] E At index 0 diff: {'loc': ('a', 0), 'msg': "expected constant value [{'b': 1}, {'b': 2}, {'b': 3}]", 'type': 'value_error.const', 'ctx': {'given': <SubModel b=3>, 'const': [{'b': 1}, {'b': 2}, {'b': 3}]}} != {'ctx': {'const': <SubModel b=1>, 'given': <SubModel b=3>}, 'loc': ('a', 0), 'msg': "expected constant value {'b': 1}", 'type': 'value_error.const'} E Full diff: E - [{'ctx': {'const': [{'b': 1}, {'b': 2}, {'b': 3}], 'given': <SubModel b=3>}, E + [{'ctx': {'const': <SubModel b=1>, 'given': <SubModel b=3>}, E 'loc': ('a', 0), E - 'msg': "expected constant value [{'b': 1}, {'b': 2}, {'b': 3}]", E ? - --------------------- E + 'msg': "expected constant value {'b': 1}", E 'type': 'value_error.const'}, E - {'ctx': {'const': [{'b': 1}, {'b': 2}, {'b': 3}], 'given': <SubModel b=1>}, E + {'ctx': {'const': <SubModel b=2>, 'given': <SubModel b=1>}, E 'loc': ('a', 1), E - 'msg': "expected constant value [{'b': 1}, {'b': 2}, {'b': 3}]", E ? - ---------- ----------- E + 'msg': "expected constant value {'b': 2}", E 'type': 'value_error.const'}, E - {'ctx': {'const': [{'b': 1}, {'b': 2}, {'b': 3}], 'given': <SubModel b=2>}, E + {'ctx': {'const': <SubModel b=3>, 'given': <SubModel b=2>}, E 'loc': ('a', 2), E - 'msg': "expected constant value [{'b': 1}, {'b': 2}, {'b': 3}]", E ? - -------------------- - E + 'msg': "expected constant value {'b': 3}", E 'type': 'value_error.const'}] ``` The issue here is that the error contains the complete list value as expected value while the error is per sub field (and the expected value is the sub field only): ``` { 'ctx': {'const': [{'b': 1}, {'b': 2}, {'b': 3}], 'given': SubModel(b=3)}, 'loc': ('a', 0), 'msg': "expected constant value [{'b': 1}, {'b': 2}, {'b': 3}]", 'type': 'value_error.const', }, ```
0.0
1b467da11f79a91125b3d2f80b4b499139a14daa
[ "tests/test_main.py::test_const_list", "tests/test_main.py::test_const_list_with_wrong_value", "tests/test_main.py::test_const_validation_json_serializable" ]
[ "tests/test_main.py::test_success", "tests/test_main.py::test_ultra_simple_missing", "tests/test_main.py::test_ultra_simple_failed", "tests/test_main.py::test_ultra_simple_repr", "tests/test_main.py::test_str_truncate", "tests/test_main.py::test_comparing", "tests/test_main.py::test_nullable_strings_success", "tests/test_main.py::test_nullable_strings_fails", "tests/test_main.py::test_recursion", "tests/test_main.py::test_recursion_fails", "tests/test_main.py::test_not_required", "tests/test_main.py::test_infer_type", "tests/test_main.py::test_allow_extra", "tests/test_main.py::test_forbidden_extra_success", "tests/test_main.py::test_forbidden_extra_fails", "tests/test_main.py::test_disallow_mutation", "tests/test_main.py::test_extra_allowed", "tests/test_main.py::test_extra_ignored", "tests/test_main.py::test_set_attr", "tests/test_main.py::test_set_attr_invalid", "tests/test_main.py::test_any", "tests/test_main.py::test_alias", "tests/test_main.py::test_population_by_alias", "tests/test_main.py::test_field_order", "tests/test_main.py::test_required", "tests/test_main.py::test_not_immutability", "tests/test_main.py::test_immutability", "tests/test_main.py::test_const_validates", "tests/test_main.py::test_const_uses_default", "tests/test_main.py::test_const_with_wrong_value", "tests/test_main.py::test_validating_assignment_pass", "tests/test_main.py::test_validating_assignment_fail", "tests/test_main.py::test_enum_values", "tests/test_main.py::test_enum_raw", "tests/test_main.py::test_set_tuple_values", "tests/test_main.py::test_default_copy", "tests/test_main.py::test_arbitrary_type_allowed_validation_success", "tests/test_main.py::test_arbitrary_type_allowed_validation_fails", "tests/test_main.py::test_arbitrary_types_not_allowed", "tests/test_main.py::test_type_type_validation_success", "tests/test_main.py::test_type_type_subclass_validation_success", "tests/test_main.py::test_type_type_validation_fails_for_instance", "tests/test_main.py::test_type_type_validation_fails_for_basic_type", "tests/test_main.py::test_annotation_field_name_shadows_attribute", "tests/test_main.py::test_value_field_name_shadows_attribute", "tests/test_main.py::test_class_var", "tests/test_main.py::test_fields_set", "tests/test_main.py::test_skip_defaults_dict", "tests/test_main.py::test_skip_defaults_recursive", "tests/test_main.py::test_dict_skip_defaults_populated_by_alias", "tests/test_main.py::test_dict_skip_defaults_populated_by_alias_with_extra", "tests/test_main.py::test_dir_fields", "tests/test_main.py::test_dict_with_extra_keys", "tests/test_main.py::test_alias_generator", "tests/test_main.py::test_alias_generator_with_field_schema", "tests/test_main.py::test_alias_generator_wrong_type_error", "tests/test_main.py::test_root", "tests/test_main.py::test_root_list", "tests/test_main.py::test_root_failed", "tests/test_main.py::test_root_undefined_failed", "tests/test_main.py::test_parse_root_as_mapping", "tests/test_main.py::test_untouched_types", "tests/test_main.py::test_custom_types_fail_without_keep_untouched", "tests/test_main.py::test_model_iteration" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-09-06 13:08:28+00:00
mit
4,907
pydantic__pydantic-808
diff --git a/docs/examples/bare_type_type.py b/docs/examples/bare_type_type.py new file mode 100644 --- /dev/null +++ b/docs/examples/bare_type_type.py @@ -0,0 +1,24 @@ +from typing import Type + +from pydantic import BaseModel, ValidationError + + +class Foo: + pass + + +class LenientSimpleModel(BaseModel): + any_class_goes: Type + + +LenientSimpleModel(any_class_goes=int) +LenientSimpleModel(any_class_goes=Foo) +try: + LenientSimpleModel(any_class_goes=Foo()) +except ValidationError as e: + print(e) +""" +1 validation error +any_class_goes + subclass of type expected (type=type_error.class) +""" diff --git a/docs/examples/type_type.py b/docs/examples/type_type.py new file mode 100644 --- /dev/null +++ b/docs/examples/type_type.py @@ -0,0 +1,29 @@ +from typing import Type + +from pydantic import BaseModel +from pydantic import ValidationError + +class Foo: + pass + +class Bar(Foo): + pass + +class Other: + pass + +class SimpleModel(BaseModel): + just_subclasses: Type[Foo] + + +SimpleModel(just_subclasses=Foo) +SimpleModel(just_subclasses=Bar) +try: + SimpleModel(just_subclasses=Other) +except ValidationError as e: + print(e) +""" +1 validation error +just_subclasses + subclass of Foo expected (type=type_error.class) +""" diff --git a/pydantic/errors.py b/pydantic/errors.py --- a/pydantic/errors.py +++ b/pydantic/errors.py @@ -324,6 +324,19 @@ def __init__(self, *, expected_arbitrary_type: AnyType) -> None: super().__init__(expected_arbitrary_type=display_as_type(expected_arbitrary_type)) +class ClassError(PydanticTypeError): + code = 'class' + msg_template = 'a class is expected' + + +class SubclassError(PydanticTypeError): + code = 'subclass' + msg_template = 'subclass of {expected_class} expected' + + def __init__(self, *, expected_class: AnyType) -> None: + super().__init__(expected_class=display_as_type(expected_class)) + + class JsonError(PydanticValueError): msg_template = 'Invalid JSON' diff --git a/pydantic/fields.py b/pydantic/fields.py --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -248,6 +248,8 @@ def _populate_sub_fields(self) -> None: # noqa: C901 (ignore complexity) ) self.type_ = self.type_.__args__[1] # type: ignore self.shape = SHAPE_MAPPING + elif issubclass(origin, Type): # type: ignore + return else: raise TypeError(f'Fields of type "{origin}" are not supported.') diff --git a/pydantic/typing.py b/pydantic/typing.py --- a/pydantic/typing.py +++ b/pydantic/typing.py @@ -193,3 +193,21 @@ def update_field_forward_refs(field: 'Field', globalns: Any, localns: Any) -> No if field.sub_fields: for sub_f in field.sub_fields: update_field_forward_refs(sub_f, globalns=globalns, localns=localns) + + +def get_class(type_: AnyType) -> Union[None, bool, AnyType]: + """ + Tries to get the class of a Type[T] annotation. Returns True if Type is used + without brackets. Otherwise returns None. + """ + try: + origin = getattr(type_, '__origin__') + if origin is None: # Python 3.6 + origin = type_ + if issubclass(origin, Type): # type: ignore + if type_.__args__ is None or not isinstance(type_.__args__[0], type): + return True + return type_.__args__[0] + except AttributeError: + pass + return None diff --git a/pydantic/validators.py b/pydantic/validators.py --- a/pydantic/validators.py +++ b/pydantic/validators.py @@ -26,8 +26,8 @@ from . import errors from .datetime_parse import parse_date, parse_datetime, parse_duration, parse_time -from .typing import AnyCallable, AnyType, ForwardRef, display_as_type, is_callable_type, is_literal_type -from .utils import almost_equal_floats, change_exception, sequence_like +from .typing import AnyCallable, AnyType, ForwardRef, display_as_type, get_class, is_callable_type, is_literal_type +from .utils import almost_equal_floats, change_exception, lenient_issubclass, sequence_like if TYPE_CHECKING: # pragma: no cover from .fields import Field @@ -404,6 +404,21 @@ def arbitrary_type_validator(v: Any) -> T: return arbitrary_type_validator +def make_class_validator(type_: Type[T]) -> Callable[[Any], Type[T]]: + def class_validator(v: Any) -> Type[T]: + if lenient_issubclass(v, type_): + return v + raise errors.SubclassError(expected_class=type_) + + return class_validator + + +def any_class_validator(v: Any) -> Type[T]: + if isinstance(v, type): + return v + raise errors.ClassError() + + def pattern_validator(v: Any) -> Pattern[str]: with change_exception(errors.PatternError, re.error): return re.compile(v) @@ -486,6 +501,14 @@ def find_validators( # noqa: C901 (ignore complexity) yield make_literal_validator(type_) return + class_ = get_class(type_) + if class_ is not None: + if isinstance(class_, type): + yield make_class_validator(class_) + else: + yield any_class_validator + return + supertype = _find_supertype(type_) if supertype is not None: type_ = supertype
pydantic/pydantic
ef894d20b3fd82e63ed033c69db6b4735c1ec6a1
Might be possible to achieve this now using validator decorators. Please let us know whether or not you get it to work. I'd be happy to accept a PR to implement it out of the box if it's something multiple people want.
diff --git a/tests/test_main.py b/tests/test_main.py --- a/tests/test_main.py +++ b/tests/test_main.py @@ -1,5 +1,5 @@ from enum import Enum -from typing import Any, ClassVar, List, Mapping +from typing import Any, ClassVar, List, Mapping, Type import pytest @@ -530,6 +530,81 @@ class ArbitraryTypeNotAllowedModel(BaseModel): assert exc_info.value.args[0].startswith('no validator found for') +def test_type_type_validation_success(): + class ArbitraryClassAllowedModel(BaseModel): + t: Type[ArbitraryType] + + arbitrary_type_class = ArbitraryType + m = ArbitraryClassAllowedModel(t=arbitrary_type_class) + assert m.t == arbitrary_type_class + + +def test_type_type_subclass_validation_success(): + class ArbitraryClassAllowedModel(BaseModel): + t: Type[ArbitraryType] + + class ArbitrarySubType(ArbitraryType): + pass + + arbitrary_type_class = ArbitrarySubType + m = ArbitraryClassAllowedModel(t=arbitrary_type_class) + assert m.t == arbitrary_type_class + + +def test_type_type_validation_fails_for_instance(): + class ArbitraryClassAllowedModel(BaseModel): + t: Type[ArbitraryType] + + class C: + pass + + with pytest.raises(ValidationError) as exc_info: + ArbitraryClassAllowedModel(t=C) + assert exc_info.value.errors() == [ + { + 'loc': ('t',), + 'msg': 'subclass of ArbitraryType expected', + 'type': 'type_error.subclass', + 'ctx': {'expected_class': 'ArbitraryType'}, + } + ] + + +def test_type_type_validation_fails_for_basic_type(): + class ArbitraryClassAllowedModel(BaseModel): + t: Type[ArbitraryType] + + with pytest.raises(ValidationError) as exc_info: + ArbitraryClassAllowedModel(t=1) + assert exc_info.value.errors() == [ + { + 'loc': ('t',), + 'msg': 'subclass of ArbitraryType expected', + 'type': 'type_error.subclass', + 'ctx': {'expected_class': 'ArbitraryType'}, + } + ] + + +def test_bare_type_type_validation_success(): + class ArbitraryClassAllowedModel(BaseModel): + t: Type + + arbitrary_type_class = ArbitraryType + m = ArbitraryClassAllowedModel(t=arbitrary_type_class) + assert m.t == arbitrary_type_class + + +def test_bare_type_type_validation_fails(): + class ArbitraryClassAllowedModel(BaseModel): + t: Type + + arbitrary_type = ArbitraryType() + with pytest.raises(ValidationError) as exc_info: + ArbitraryClassAllowedModel(t=arbitrary_type) + assert exc_info.value.errors() == [{'loc': ('t',), 'msg': 'a class is expected', 'type': 'type_error.class'}] + + def test_annotation_field_name_shadows_attribute(): with pytest.raises(NameError): # When defining a model that has an attribute with the name of a built-in attribute, an exception is raised
Validating subclasses # Question I was wondering what the best way to validate subclasses is? Something along the sorts of ```python import pydantic class MyClass: pass class MySubClass(MyClass): pass class MyOtherClass: pass class Foo(BaseModel): a_class_not_an_object: Type[MyClass] ``` where I would expect both ```python Foo(a_class_not_an_object=MyClass) Foo(a_class_not_an_object=MySubClass) ``` to work, but ```python Foo(a_class_not_an_object=MyOtherClass) ``` to throw an error. Is the way to go to implement a custom type or is there a way pydantic supports this out-of-the-box? Have a good weekend :)
0.0
ef894d20b3fd82e63ed033c69db6b4735c1ec6a1
[ "tests/test_main.py::test_type_type_validation_success", "tests/test_main.py::test_type_type_subclass_validation_success", "tests/test_main.py::test_type_type_validation_fails_for_instance", "tests/test_main.py::test_type_type_validation_fails_for_basic_type" ]
[ "tests/test_main.py::test_success", "tests/test_main.py::test_ultra_simple_missing", "tests/test_main.py::test_ultra_simple_failed", "tests/test_main.py::test_ultra_simple_repr", "tests/test_main.py::test_str_truncate", "tests/test_main.py::test_comparing", "tests/test_main.py::test_nullable_strings_success", "tests/test_main.py::test_nullable_strings_fails", "tests/test_main.py::test_recursion", "tests/test_main.py::test_recursion_fails", "tests/test_main.py::test_not_required", "tests/test_main.py::test_infer_type", "tests/test_main.py::test_allow_extra", "tests/test_main.py::test_forbidden_extra_success", "tests/test_main.py::test_forbidden_extra_fails", "tests/test_main.py::test_disallow_mutation", "tests/test_main.py::test_extra_allowed", "tests/test_main.py::test_extra_ignored", "tests/test_main.py::test_set_attr", "tests/test_main.py::test_set_attr_invalid", "tests/test_main.py::test_any", "tests/test_main.py::test_alias", "tests/test_main.py::test_population_by_alias", "tests/test_main.py::test_field_order", "tests/test_main.py::test_required", "tests/test_main.py::test_not_immutability", "tests/test_main.py::test_immutability", "tests/test_main.py::test_const_validates", "tests/test_main.py::test_const_uses_default", "tests/test_main.py::test_const_with_wrong_value", "tests/test_main.py::test_validating_assignment_pass", "tests/test_main.py::test_validating_assignment_fail", "tests/test_main.py::test_enum_values", "tests/test_main.py::test_enum_raw", "tests/test_main.py::test_set_tuple_values", "tests/test_main.py::test_default_copy", "tests/test_main.py::test_arbitrary_type_allowed_validation_success", "tests/test_main.py::test_arbitrary_type_allowed_validation_fails", "tests/test_main.py::test_arbitrary_types_not_allowed", "tests/test_main.py::test_annotation_field_name_shadows_attribute", "tests/test_main.py::test_value_field_name_shadows_attribute", "tests/test_main.py::test_class_var", "tests/test_main.py::test_fields_set", "tests/test_main.py::test_skip_defaults_dict", "tests/test_main.py::test_skip_defaults_recursive", "tests/test_main.py::test_dict_skip_defaults_populated_by_alias", "tests/test_main.py::test_dict_skip_defaults_populated_by_alias_with_extra", "tests/test_main.py::test_dir_fields", "tests/test_main.py::test_dict_with_extra_keys", "tests/test_main.py::test_alias_generator", "tests/test_main.py::test_alias_generator_with_field_schema", "tests/test_main.py::test_alias_generator_wrong_type_error", "tests/test_main.py::test_root", "tests/test_main.py::test_root_list", "tests/test_main.py::test_root_failed", "tests/test_main.py::test_root_undefined_failed", "tests/test_main.py::test_parse_root_as_mapping", "tests/test_main.py::test_untouched_types", "tests/test_main.py::test_custom_types_fail_without_keep_untouched", "tests/test_main.py::test_model_iteration" ]
{ "failed_lite_validators": [ "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-09-14 20:01:01+00:00
mit
4,908
pydantic__pydantic-817
diff --git a/docs/examples/validators_root.py b/docs/examples/validators_root.py new file mode 100644 --- /dev/null +++ b/docs/examples/validators_root.py @@ -0,0 +1,41 @@ +from pydantic import BaseModel, ValidationError, root_validator + +class UserModel(BaseModel): + username: str + password1: str + password2: str + + @root_validator(pre=True) + def check_card_number_omitted(cls, values): + assert 'card_number' not in values, 'card_number should not be included' + return values + + @root_validator + def check_passwords_match(cls, values): + pw1, pw2 = values.get('password1'), values.get('password2') + if pw1 is not None and pw2 is not None and pw1 != pw2: + raise ValueError('passwords do not match') + return values + +print(UserModel(username='scolvin', password1='zxcvbn', password2='zxcvbn')) +#> UserModel username='scolvin' password1='zxcvbn' password2='zxcvbn' + +try: + UserModel(username='scolvin', password1='zxcvbn', password2='zxcvbn2') +except ValidationError as e: + print(e) +""" +1 validation error for UserModel +__root__ + passwords do not match (type=value_error) +""" + +try: + UserModel(username='scolvin', password1='zxcvbn', password2='zxcvbn', card_number='1234') +except ValidationError as e: + print(e) +""" +1 validation error for UserModel +__root__ + card_number should not be included (type=assertion_error) +""" diff --git a/docs/examples/validators_simple.py b/docs/examples/validators_simple.py --- a/docs/examples/validators_simple.py +++ b/docs/examples/validators_simple.py @@ -1,6 +1,5 @@ from pydantic import BaseModel, ValidationError, validator - class UserModel(BaseModel): name: str username: str @@ -24,16 +23,15 @@ def username_alphanumeric(cls, v): assert v.isalpha(), 'must be alphanumeric' return v - print(UserModel(name='samuel colvin', username='scolvin', password1='zxcvbn', password2='zxcvbn')) -# > UserModel name='Samuel Colvin' password1='zxcvbn' password2='zxcvbn' +#> UserModel name='Samuel Colvin' username='scolvin' password1='zxcvbn' password2='zxcvbn' try: UserModel(name='samuel', username='scolvin', password1='zxcvbn', password2='zxcvbn2') except ValidationError as e: print(e) """ -2 validation errors +2 validation errors for UserModel name must contain a space (type=value_error) password2 diff --git a/pydantic/__init__.py b/pydantic/__init__.py --- a/pydantic/__init__.py +++ b/pydantic/__init__.py @@ -1,6 +1,6 @@ # flake8: noqa from . import dataclasses -from .class_validators import validator +from .class_validators import root_validator, validator from .env_settings import BaseSettings from .error_wrappers import ValidationError from .errors import * diff --git a/pydantic/class_validators.py b/pydantic/class_validators.py --- a/pydantic/class_validators.py +++ b/pydantic/class_validators.py @@ -4,24 +4,24 @@ from inspect import Signature, signature from itertools import chain from types import FunctionType -from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Set, Type +from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Optional, Set, Tuple, Type, Union from .errors import ConfigError from .typing import AnyCallable from .utils import in_ipython -if TYPE_CHECKING: # pragma: no cover - from .main import BaseConfig - from .fields import Field - from .types import ModelOrDc - - ValidatorCallable = Callable[[Optional[ModelOrDc], Any, Dict[str, Any], Field, Type[BaseConfig]], Any] - class Validator: __slots__ = 'func', 'pre', 'each_item', 'always', 'check_fields' - def __init__(self, func: AnyCallable, pre: bool, each_item: bool, always: bool, check_fields: bool): + def __init__( + self, + func: AnyCallable, + pre: bool = False, + each_item: bool = False, + always: bool = False, + check_fields: bool = False, + ): self.func = func self.pre = pre self.each_item = each_item @@ -29,7 +29,19 @@ def __init__(self, func: AnyCallable, pre: bool, each_item: bool, always: bool, self.check_fields = check_fields +if TYPE_CHECKING: # pragma: no cover + from .main import BaseConfig + from .fields import Field + from .types import ModelOrDc + + ValidatorCallable = Callable[[Optional[ModelOrDc], Any, Dict[str, Any], Field, Type[BaseConfig]], Any] + ValidatorsList = List[ValidatorCallable] + ValidatorListDict = Dict[str, List[Validator]] + _FUNCS: Set[str] = set() +ROOT_KEY = '__root__' +VALIDATOR_CONFIG_KEY = '__validator_config__' +ROOT_VALIDATOR_CONFIG_KEY = '__root_validator_config__' def validator( @@ -66,39 +78,62 @@ def validator( each_item = not whole def dec(f: AnyCallable) -> classmethod: - # avoid validators with duplicated names since without this validators can be overwritten silently - # which generally isn't the intended behaviour, don't run in ipython - see #312 - if not in_ipython(): # pragma: no branch - ref = f.__module__ + '.' + f.__qualname__ - if ref in _FUNCS: - raise ConfigError(f'duplicate validator function "{ref}"') - _FUNCS.add(ref) + _check_validator_name(f) f_cls = classmethod(f) - f_cls.__validator_config = ( # type: ignore - fields, - Validator(func=f, pre=pre, each_item=each_item, always=always, check_fields=check_fields), + setattr( + f_cls, + VALIDATOR_CONFIG_KEY, + (fields, Validator(func=f, pre=pre, each_item=each_item, always=always, check_fields=check_fields)), ) return f_cls return dec -ValidatorListDict = Dict[str, List[Validator]] +def root_validator( + _func: Optional[AnyCallable] = None, *, pre: bool = False +) -> Union[classmethod, Callable[[AnyCallable], classmethod]]: + if _func: + _check_validator_name(_func) + f_cls = classmethod(_func) + setattr(f_cls, ROOT_VALIDATOR_CONFIG_KEY, Validator(func=_func, pre=pre)) + return f_cls + + def dec(f: AnyCallable) -> classmethod: + _check_validator_name(f) + f_cls = classmethod(f) + setattr(f_cls, ROOT_VALIDATOR_CONFIG_KEY, Validator(func=f, pre=pre)) + return f_cls + + return dec + + +def _check_validator_name(f: AnyCallable) -> None: + """ + avoid validators with duplicated names since without this, validators can be overwritten silently + which generally isn't the intended behaviour, don't run in ipython - see #312 + """ + if not in_ipython(): # pragma: no branch + ref = f.__module__ + '.' + f.__qualname__ + if ref in _FUNCS: + raise ConfigError(f'duplicate validator function "{ref}"') + _FUNCS.add(ref) class ValidatorGroup: - def __init__(self, validators: ValidatorListDict) -> None: + def __init__(self, validators: 'ValidatorListDict') -> None: self.validators = validators self.used_validators = {'*'} def get_validators(self, name: str) -> Optional[Dict[str, Validator]]: self.used_validators.add(name) - specific_validators = self.validators.get(name) - wildcard_validators = self.validators.get('*') - if specific_validators or wildcard_validators: - validators = (specific_validators or []) + (wildcard_validators or []) + validators = self.validators.get(name, []) + if name != ROOT_KEY: + validators += self.validators.get('*', []) + if validators: return {v.func.__name__: v for v in validators} - return None + else: + return None def check_for_unused(self) -> None: unused_validators = set( @@ -120,7 +155,7 @@ def check_for_unused(self) -> None: def extract_validators(namespace: Dict[str, Any]) -> Dict[str, List[Validator]]: validators: Dict[str, List[Validator]] = {} for var_name, value in namespace.items(): - validator_config = getattr(value, '__validator_config', None) + validator_config = getattr(value, VALIDATOR_CONFIG_KEY, None) if validator_config: fields, v = validator_config for field in fields: @@ -131,7 +166,30 @@ def extract_validators(namespace: Dict[str, Any]) -> Dict[str, List[Validator]]: return validators -def inherit_validators(base_validators: ValidatorListDict, validators: ValidatorListDict) -> ValidatorListDict: +def extract_root_validators(namespace: Dict[str, Any]) -> Tuple[List[AnyCallable], List[AnyCallable]]: + pre_validators: List[AnyCallable] = [] + post_validators: List[AnyCallable] = [] + for name, value in namespace.items(): + validator_config: Optional[Validator] = getattr(value, ROOT_VALIDATOR_CONFIG_KEY, None) + if validator_config: + sig = signature(validator_config.func) + args = list(sig.parameters.keys()) + if args[0] == 'self': + raise ConfigError( + f'Invalid signature for root validator {name}: {sig}, "self" not permitted as first argument, ' + f'should be: (cls, values).' + ) + if len(args) != 2: + raise ConfigError(f'Invalid signature for root validator {name}: {sig}, should be: (cls, values).') + # check function signature + if validator_config.pre: + pre_validators.append(validator_config.func) + else: + post_validators.append(validator_config.func) + return pre_validators, post_validators + + +def inherit_validators(base_validators: 'ValidatorListDict', validators: 'ValidatorListDict') -> 'ValidatorListDict': for field, field_validators in base_validators.items(): if field not in validators: validators[field] = [] @@ -165,6 +223,10 @@ def make_generic_validator(validator: AnyCallable) -> 'ValidatorCallable': return wraps(validator)(_generic_validator_basic(validator, sig, set(args))) +def prep_validators(v_funcs: Iterable[AnyCallable]) -> 'ValidatorsList': + return [make_generic_validator(f) for f in v_funcs if f] + + all_kwargs = {'values', 'field', 'config'} @@ -235,6 +297,10 @@ def _generic_validator_basic(validator: AnyCallable, sig: Signature, args: Set[s return lambda cls, v, values, field, config: validator(v, values=values, field=field, config=config) -def gather_validators(type_: 'ModelOrDc') -> Dict[str, classmethod]: +def gather_all_validators(type_: 'ModelOrDc') -> Dict[str, classmethod]: all_attributes = ChainMap(*[cls.__dict__ for cls in type_.__mro__]) - return {k: v for k, v in all_attributes.items() if hasattr(v, '__validator_config')} + return { + k: v + for k, v in all_attributes.items() + if hasattr(v, VALIDATOR_CONFIG_KEY) or hasattr(v, ROOT_VALIDATOR_CONFIG_KEY) + } diff --git a/pydantic/dataclasses.py b/pydantic/dataclasses.py --- a/pydantic/dataclasses.py +++ b/pydantic/dataclasses.py @@ -1,7 +1,7 @@ import dataclasses from typing import TYPE_CHECKING, Any, Callable, Dict, Generator, Optional, Type, Union -from .class_validators import gather_validators +from .class_validators import gather_all_validators from .error_wrappers import ValidationError from .errors import DataclassTypeError from .fields import Required @@ -67,7 +67,9 @@ def _process_class( def _pydantic_post_init(self: 'DataclassType', *initvars: Any) -> None: if post_init_original is not None: post_init_original(self, *initvars) - d = validate_model(self.__pydantic_model__, self.__dict__, cls=self.__class__)[0] + d, _, validation_error = validate_model(self.__pydantic_model__, self.__dict__, cls=self.__class__) + if validation_error: + raise validation_error object.__setattr__(self, '__dict__', d) object.__setattr__(self, '__initialised__', True) if post_init_post_parse is not None: @@ -81,7 +83,7 @@ def _pydantic_post_init(self: 'DataclassType', *initvars: Any) -> None: for field in dataclasses.fields(cls) } - validators = gather_validators(cls) + validators = gather_all_validators(cls) cls.__pydantic_model__ = create_model( cls.__name__, __config__=config, __module__=_cls.__module__, __validators__=validators, **fields ) diff --git a/pydantic/fields.py b/pydantic/fields.py --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -4,7 +4,6 @@ Dict, FrozenSet, Generator, - Iterable, Iterator, List, Mapping, @@ -19,11 +18,11 @@ ) from . import errors as errors_ -from .class_validators import Validator, make_generic_validator +from .class_validators import Validator, make_generic_validator, prep_validators from .error_wrappers import ErrorWrapper from .errors import NoneIsNotAllowedError from .types import Json, JsonWrapper -from .typing import AnyCallable, AnyType, Callable, ForwardRef, display_as_type, is_literal_type, literal_values +from .typing import AnyType, Callable, ForwardRef, display_as_type, is_literal_type, literal_values from .utils import lenient_issubclass, sequence_like from .validators import constant_validator, dict_validator, find_validators, validate_json @@ -36,13 +35,12 @@ NoneType = type(None) if TYPE_CHECKING: # pragma: no cover - from .class_validators import ValidatorCallable # noqa: F401 + from .class_validators import ValidatorsList # noqa: F401 from .error_wrappers import ErrorList from .main import BaseConfig, BaseModel # noqa: F401 from .schema import Schema # noqa: F401 from .types import ModelOrDc # noqa: F401 - ValidatorsList = List[ValidatorCallable] ValidateReturn = Tuple[Optional[Any], Optional[ErrorList]] LocStr = Union[Tuple[Union[int, str], ...], str] @@ -238,7 +236,7 @@ def _type_analysis(self) -> None: # noqa: C901 (ignore complexity) if get_validators: self.class_validators.update( { - f'list_{i}': Validator(validator, each_item=False, pre=True, always=True, check_fields=False) + f'list_{i}': Validator(validator, pre=True, always=True) for i, validator in enumerate(get_validators()) } ) @@ -285,7 +283,7 @@ def _populate_validators(self) -> None: *(get_validators() if get_validators else list(find_validators(self.type_, self.model_config))), *[v.func for v in class_validators_ if v.each_item and not v.pre], ) - self.validators = self._prep_vals(v_funcs) + self.validators = prep_validators(v_funcs) # Add const validator self.pre_validators = [] @@ -294,8 +292,8 @@ def _populate_validators(self) -> None: self.pre_validators = [make_generic_validator(constant_validator)] if class_validators_: - self.pre_validators += self._prep_vals(v.func for v in class_validators_ if not v.each_item and v.pre) - self.post_validators = self._prep_vals(v.func for v in class_validators_ if not v.each_item and not v.pre) + self.pre_validators += prep_validators(v.func for v in class_validators_ if not v.each_item and v.pre) + self.post_validators = prep_validators(v.func for v in class_validators_ if not v.each_item and not v.pre) if self.parse_json: self.pre_validators.append(make_generic_validator(validate_json)) @@ -303,10 +301,6 @@ def _populate_validators(self) -> None: self.pre_validators = self.pre_validators or None self.post_validators = self.post_validators or None - @staticmethod - def _prep_vals(v_funcs: Iterable[AnyCallable]) -> 'ValidatorsList': - return [make_generic_validator(f) for f in v_funcs if f] - def validate( self, v: Any, values: Dict[str, Any], *, loc: 'LocStr', cls: Optional['ModelOrDc'] = None ) -> 'ValidateReturn': diff --git a/pydantic/generics.py b/pydantic/generics.py --- a/pydantic/generics.py +++ b/pydantic/generics.py @@ -1,7 +1,7 @@ from typing import Any, ClassVar, Dict, Generic, Tuple, Type, TypeVar, Union, get_type_hints -from pydantic.class_validators import gather_validators -from pydantic.main import BaseModel, create_model +from .class_validators import gather_all_validators +from .main import BaseModel, create_model _generic_types_cache: Dict[Tuple[Type[Any], Union[Any, Tuple[Any, ...]]], Type[BaseModel]] = {} GenericModelT = TypeVar('GenericModelT', bound='GenericModel') @@ -41,7 +41,7 @@ def __class_getitem__( # type: ignore } model_name = concrete_name(cls, params) - validators = gather_validators(cls) + validators = gather_all_validators(cls) fields: Dict[str, Tuple[Type[Any], Any]] = { k: (v, cls.__fields__[k].default) for k, v in concrete_type_hints.items() if k in cls.__fields__ } diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -7,9 +7,9 @@ from functools import partial from pathlib import Path from types import FunctionType -from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, Tuple, Type, TypeVar, Union, cast, no_type_check +from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Type, TypeVar, Union, cast, no_type_check -from .class_validators import ValidatorGroup, extract_validators, inherit_validators +from .class_validators import ROOT_KEY, ValidatorGroup, extract_root_validators, extract_validators, inherit_validators from .error_wrappers import ErrorWrapper, ValidationError from .errors import ConfigError, DictError, ExtraError, MissingError from .fields import SHAPE_MAPPING, Field @@ -64,6 +64,7 @@ class BaseConfig: 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: Dict[str, Any] = {} @@ -108,13 +109,13 @@ def set_extra(config: Type[BaseConfig], cls_name: str) -> None: def is_valid_field(name: str) -> bool: if not name.startswith('_'): return True - return '__root__' == name + return ROOT_KEY == name def validate_custom_root_type(fields: Dict[str, Field]) -> None: if len(fields) > 1: raise ValueError('__root__ cannot be mixed with other fields') - if fields['__root__'].shape == SHAPE_MAPPING: + if fields[ROOT_KEY].shape == SHAPE_MAPPING: raise TypeError('custom root type cannot allow mapping') @@ -127,11 +128,14 @@ def __new__(mcs, name, bases, namespace): fields: Dict[str, Field] = {} config = BaseConfig validators: 'ValidatorListDict' = {} + pre_root_validators, post_root_validators = [], [] for base in reversed(bases): if issubclass(base, BaseModel) and base != BaseModel: fields.update(deepcopy(base.__fields__)) config = inherit_config(base.__config__, config) validators = inherit_validators(base.__validators__, validators) + pre_root_validators += base.__pre_root_validators__ + post_root_validators += base.__post_root_validators__ config = inherit_config(namespace.get('Config'), config) validators = inherit_validators(extract_validators(namespace), validators) @@ -190,7 +194,7 @@ def __new__(mcs, name, bases, namespace): ) fields[var_name] = inferred - _custom_root_type = '__root__' in fields + _custom_root_type = ROOT_KEY in fields if _custom_root_type: validate_custom_root_type(fields) vg.check_for_unused() @@ -198,10 +202,13 @@ def __new__(mcs, name, bases, namespace): json_encoder = partial(custom_pydantic_encoder, config.json_encoders) else: json_encoder = pydantic_encoder + pre_rv_new, post_rv_new = extract_root_validators(namespace) new_namespace = { '__config__': config, '__fields__': fields, '__validators__': vg.validators, + '__pre_root_validators__': pre_root_validators + pre_rv_new, + '__post_root_validators__': post_root_validators + post_rv_new, '_schema_cache': {}, '_json_encoder': staticmethod(json_encoder), '_custom_root_type': _custom_root_type, @@ -215,6 +222,8 @@ class BaseModel(metaclass=MetaModel): # populated by the metaclass, defined here to help IDEs only __fields__: Dict[str, Field] = {} __validators__: Dict[str, AnyCallable] = {} + __pre_root_validators__: List[AnyCallable] + __post_root_validators__: List[AnyCallable] __config__: Type[BaseConfig] = BaseConfig __root__: Any = None _json_encoder: Callable[[Any], Any] = lambda x: x @@ -229,7 +238,9 @@ def __init__(__pydantic_self__, **data: Any) -> None: if TYPE_CHECKING: # pragma: no cover __pydantic_self__.__dict__: Dict[str, Any] = {} __pydantic_self__.__fields_set__: 'SetStr' = set() - values, fields_set, _ = validate_model(__pydantic_self__, data) + values, fields_set, validation_error = validate_model(__pydantic_self__.__class__, data) + if validation_error: + raise validation_error object.__setattr__(__pydantic_self__, '__dict__', values) object.__setattr__(__pydantic_self__, '__fields_set__', fields_set) @@ -308,20 +319,20 @@ def json( encoder = cast(Callable[[Any], Any], encoder or self._json_encoder) data = self.dict(include=include, exclude=exclude, by_alias=by_alias, skip_defaults=skip_defaults) if self._custom_root_type: - data = data['__root__'] + data = data[ROOT_KEY] return self.__config__.json_dumps(data, default=encoder, **dumps_kwargs) @classmethod def parse_obj(cls: Type['Model'], obj: Any) -> 'Model': if not isinstance(obj, dict): if cls._custom_root_type: - obj = {'__root__': obj} + obj = {ROOT_KEY: obj} else: try: obj = dict(obj) except (TypeError, ValueError) as e: exc = TypeError(f'{cls.__name__} expected dict not {type(obj).__name__}') - raise ValidationError([ErrorWrapper(exc, loc='__obj__')], cls) from e + raise ValidationError([ErrorWrapper(exc, loc=ROOT_KEY)], cls) from e return cls(**obj) @classmethod @@ -344,7 +355,7 @@ def parse_raw( json_loads=cls.__config__.json_loads, ) except (ValueError, TypeError, UnicodeDecodeError) as e: - raise ValidationError([ErrorWrapper(e, loc='__obj__')], cls) + raise ValidationError([ErrorWrapper(e, loc=ROOT_KEY)], cls) return cls.parse_obj(obj) @classmethod @@ -366,7 +377,9 @@ def from_orm(cls: Type['Model'], obj: Any) -> 'Model': raise ConfigError('You must have the config attribute orm_mode=True to use from_orm') obj = cls._decompose_class(obj) m = cls.__new__(cls) - values, fields_set, _ = validate_model(m, obj) + values, fields_set, validation_error = validate_model(cls, obj) + if validation_error: + raise validation_error object.__setattr__(m, '__dict__', values) object.__setattr__(m, '__fields_set__', fields_set) return m @@ -467,7 +480,7 @@ def validate(cls: Type['Model'], value: Any) -> 'Model': @classmethod def _decompose_class(cls: Type['Model'], obj: Any) -> GetterDict: - return GetterDict(obj) + return cls.__config__.getter_dict(obj) @classmethod @no_type_check @@ -681,7 +694,7 @@ def create_model( def validate_model( # noqa: C901 (ignore complexity) - model: Union[BaseModel, Type[BaseModel]], input_data: 'DictStrAny', raise_exc: bool = True, cls: 'ModelOrDc' = None + model: Type[BaseModel], input_data: 'DictStrAny', cls: 'ModelOrDc' = None ) -> Tuple['DictStrAny', 'SetStr', Optional[ValidationError]]: """ validate data against a model. @@ -694,7 +707,13 @@ def validate_model( # noqa: C901 (ignore complexity) fields_set = set() config = model.__config__ check_extra = config.extra is not Extra.ignore - cls_ = cls or model.__class__ + cls_ = cls or model + + for validator in model.__pre_root_validators__: + try: + input_data = validator(cls_, input_data) + except (ValueError, TypeError, AssertionError) as exc: + return {}, set(), ValidationError([ErrorWrapper(exc, loc=ROOT_KEY)], cls_) for name, field in model.__fields__.items(): if type(field.type_) == ForwardRef: @@ -728,7 +747,7 @@ def validate_model( # noqa: C901 (ignore complexity) if check_extra: names_used.add(field.name if using_name else field.alias) - v_, errors_ = field.validate(value, values, loc=field.alias, cls=cls_) # type: ignore + v_, errors_ = field.validate(value, values, loc=field.alias, cls=cls_) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): @@ -737,7 +756,10 @@ def validate_model( # noqa: C901 (ignore complexity) values[name] = v_ if check_extra: - extra = input_data.keys() - names_used + if isinstance(input_data, GetterDict): + extra = input_data.extra_keys() - names_used + else: + extra = input_data.keys() - names_used if extra: fields_set |= extra if config.extra is Extra.allow: @@ -747,15 +769,14 @@ def validate_model( # noqa: C901 (ignore complexity) for f in sorted(extra): errors.append(ErrorWrapper(ExtraError(), loc=f)) - err = None - if errors: - model_type = model if isinstance(model, type) else type(model) - err = ValidationError(errors, model_type) - - if not raise_exc: - return values, fields_set, err - - if err: - raise err + for validator in model.__post_root_validators__: + try: + values = validator(cls_, values) + except (ValueError, TypeError, AssertionError) as exc: + errors.append(ErrorWrapper(exc, loc=ROOT_KEY)) + break - return values, fields_set, None + if errors: + return values, fields_set, ValidationError(errors, cls_) + else: + return values, fields_set, None diff --git a/pydantic/schema.py b/pydantic/schema.py --- a/pydantic/schema.py +++ b/pydantic/schema.py @@ -11,6 +11,7 @@ from pydantic.color import Color +from .class_validators import ROOT_KEY from .fields import SHAPE_LIST, SHAPE_MAPPING, SHAPE_SET, SHAPE_SINGLETON, SHAPE_TUPLE, Field from .json import pydantic_encoder from .networks import AnyUrl, EmailStr, IPvAnyAddress, IPvAnyInterface, IPvAnyNetwork, NameEmail @@ -586,8 +587,8 @@ def model_type_schema( properties[k] = f_schema if f.required: required.append(k) - if '__root__' in properties: - out_schema = properties['__root__'] + if ROOT_KEY in properties: + out_schema = properties[ROOT_KEY] out_schema['title'] = model.__config__.title or model.__name__ else: out_schema = {'type': 'object', 'properties': properties} diff --git a/pydantic/types.py b/pydantic/types.py --- a/pydantic/types.py +++ b/pydantic/types.py @@ -26,11 +26,6 @@ strict_str_validator, ) -try: - import email_validator -except ImportError: - email_validator = None - __all__ = [ 'NoneStr', 'NoneBytes', diff --git a/pydantic/utils.py b/pydantic/utils.py --- a/pydantic/utils.py +++ b/pydantic/utils.py @@ -1,8 +1,8 @@ import inspect from importlib import import_module -from typing import TYPE_CHECKING, Any, List, Optional, Set, Tuple, Type, Union, no_type_check +from typing import TYPE_CHECKING, Any, Iterator, List, Optional, Set, Tuple, Type, Union, no_type_check -from .typing import AnyType +from .typing import AnyType, display_as_type try: from typing_extensions import Literal @@ -93,6 +93,8 @@ def almost_equal_floats(value_1: float, value_2: float, *, delta: float = 1e-8) class GetterDict: """ Hack to make object's smell just enough like dicts for validate_model. + + We can't inherit from Mapping[str, Any] because it upsets cython so we have to implement all methods ourselves. """ __slots__ = ('_obj',) @@ -100,15 +102,52 @@ class GetterDict: def __init__(self, obj: Any): self._obj = obj - def get(self, item: Any, default: Any) -> Any: - return getattr(self._obj, item, default) + def __getitem__(self, key: str) -> Any: + try: + return getattr(self._obj, key) + except AttributeError as e: + raise KeyError(key) from e + + def get(self, key: Any, default: Any = None) -> Any: + return getattr(self._obj, key, default) - def keys(self) -> Set[Any]: + def extra_keys(self) -> Set[Any]: """ We don't want to get any other attributes of obj if the model didn't explicitly ask for them """ return set() + def keys(self) -> List[Any]: + """ + Keys of the pseudo dictionary, uses a list not set so order information can be maintained like python + dictionaries. + """ + return list(self) + + def values(self) -> List[Any]: + return [self[k] for k in self] + + def items(self) -> Iterator[Tuple[str, Any]]: + for k in self: + yield k, self.get(k) + + def __iter__(self) -> Iterator[str]: + for name in dir(self._obj): + if not name.startswith('_'): + yield name + + def __len__(self) -> int: + return sum(1 for _ in self) + + def __contains__(self, item: Any) -> bool: + return item in self.keys() + + def __eq__(self, other: Any) -> bool: + return dict(self) == dict(other.items()) # type: ignore + + def __repr__(self) -> str: + return f'<GetterDict({display_as_type(self._obj)}) {dict(self)}>' # type: ignore + class ValueItems: """
pydantic/pydantic
973de05a0119107fd0caa2b565c25776c41b9fb7
It seems so good to me. > We should change this in v1 to `__root__` to better match other nomenclature, eg. custom root types, where we use `__root__`. I know about custom root type. But, someone might not understand the `__root__` clearly. agreed, documentation will need improving, but better to use one term everywhere. I'm not wedded to the term "root" other offers considered... I agree. My answer is `__root__` for the title of the issue. > We should also implement at some point entire model validation For the sake of discussion, here's a somewhat radical proposal: 1. If the list of fields passed to the validator is empty, it becomes a `__root__`/entire-model validator (depending on whether the model has a non-default `__root__`). (I see no reason to drop support for `@validator('__root__')`, but wouldn't be opposed to it for simplicity's sake.) 2. The `loc` field of `ErrorWrapper` is changed from typically containing `{field.name}` to typically containing`{Model.Config.title or Model.__name__}.{field.name}`. * I recognize that right now, validation happens inside the `Field`, which is not aware of the containing model. I think this could be addressed by the existence of a function/method that returns a modified `ErrorWrapper` where `loc` includes the name of the model. 3. For `__root__` or entire-model validation, drop the `.{field.name}` from `loc`. Technical implementation challenges aside, I think this might be a good way to achieve a unified interface for specifying whole-model *and* `__root__` validators, and for achieving consistent error labeling. I'll open a separate issue to discuss the implications of adding the model name to `ErrorWrapper`, but, any thoughts on this in the context of handling root errors? So you're basically suggesting prefixing `loc` with the model name? The problem is that very often (in few types of case, but the large majority of cases) we're simply doing something like: ```py class LoginModel: email: EmailStr password: constr(max_length=100) def login_view(request): m = LoginModel(**request.json()) ... ``` The user (or frontend developer) has never heard of `LoginModel`, so an error at `loc: ['LoginModel', 'email']` is a lot more confusing than at `loc: ['email']`. We could just use the model name instead of `__root__` for those errors? I know that in theory `loc` is designed to be processed by the middleware of using package and used to generate the final error format, but I for one quite often end up using it directly. @samuelcolvin I was coming from the context of FastAPI, and was imagining that the model name is externally available through the OpenAPI spec. But maybe that is a big assumption (especially if you want validation errors but don't want a public OpenAPI spec). I guess it would be nice if there were a config setting for `include_model_name_in_error_loc` (or something less verbose 😅). That would make it possible to optionally incorporate the change without many changes to code, and without needing to worry about causing conflicts with frameworks using pydantic (like FastAPI). Either way, I think `__root__` would be similarly confusing externally. But it would have the advantage of leaking less implementation information if you wanted to avoid that. I agree `__root__` isn't much better. But at least it won't get added to the majority of errors which have a field. What do others think? Also what do other libraries do? Django (and presumably therefore DRF) uses `__all__` which is no clearer than `__root__`. I've thought this through some more, and given ValidationError tracebacks now include the model name, I think it makes sense to just use `__root__` everywhere (and prefer this to `__all__`). For the sake of debugging, I think it's fine to require access to the tracebacks to determine the model name. I'll take a shot at implementing. @samuelcolvin I tried taking a shot at this, but I think I got in over my head. Validation currently always happens in a field, and I couldn't find a way to add "root" validation for non-custom-root models without substantial and/or very-likely-controversial changes. Given the amount of changes that it seemed like I'd have to make, (not to mention the effort required to get it to actually *work* even if I *was* willing to make large changes), I'm going to leave this to you for now. (If you have an approach in mind that you think should work, I would also be happy to put in some renewed effort given more guidance.) @dmontagu do you have your unfinished code in a fork or branch somewhere where I can take a look at it? @skewty I'll look, but I'd probably advise against basing anything off of it, as I made a number of choices that backed me into a corner that I don't think had any hope of success. And I *suspect* any approach to this will have to get pretty deep into the internals, so it's probably better not to push your thinking down the same line that led me to problems. I was thinking about this recently, and thought it might actually be easier to implement this somehow via something closer to the dataclass `__post_init__` than to how validators currently work. I'm going to work on this soon, just haven't got a chance yet.
diff --git a/tests/test_generics.py b/tests/test_generics.py --- a/tests/test_generics.py +++ b/tests/test_generics.py @@ -4,7 +4,7 @@ import pytest -from pydantic import BaseModel, ValidationError, validator +from pydantic import BaseModel, ValidationError, root_validator, validator from pydantic.generics import GenericModel, _generic_types_cache skip_36 = pytest.mark.skipif(sys.version_info < (3, 7), reason='generics only supported for python 3.7 and above') @@ -42,11 +42,17 @@ class Response(GenericModel, Generic[T]): @validator('data', each_item=True) def validate_value_nonzero(cls, v): - if isinstance(v, dict): - return v # ensure v is actually a value of the dict, not the dict itself if v == 0: raise ValueError('value is zero') + return v + + @root_validator() + def validate_sum(cls, values): + if sum(values.get('data', {}).values()) > 5: + raise ValueError('sum too large') + return values + assert Response[Dict[int, int]](data={1: '4'}).dict() == {'data': {1: 4}} with pytest.raises(ValidationError) as exc_info: Response[Dict[int, int]](data={1: 'a'}) assert exc_info.value.errors() == [ @@ -57,6 +63,10 @@ def validate_value_nonzero(cls, v): Response[Dict[int, int]](data={1: 0}) assert exc_info.value.errors() == [{'loc': ('data', 1), 'msg': 'value is zero', 'type': 'value_error'}] + with pytest.raises(ValidationError) as exc_info: + Response[Dict[int, int]](data={1: 3, 2: 6}) + assert exc_info.value.errors() == [{'loc': ('__root__',), 'msg': 'sum too large', 'type': 'value_error'}] + @skip_36 def test_methods_are_inherited(): diff --git a/tests/test_orm_mode.py b/tests/test_orm_mode.py --- a/tests/test_orm_mode.py +++ b/tests/test_orm_mode.py @@ -1,8 +1,8 @@ -from typing import List +from typing import Any, List import pytest -from pydantic import BaseModel, ConfigError, ValidationError +from pydantic import BaseModel, ConfigError, ValidationError, root_validator from pydantic.utils import GetterDict @@ -26,7 +26,7 @@ def __getattr__(self, key): t = TestCls() gd = GetterDict(t) - assert gd.keys() == set() + assert gd.keys() == ['a', 'c', 'd'] assert gd.get('a', None) == 1 assert gd.get('b', None) is None assert gd.get('b', 1234) == 1234 @@ -34,6 +34,13 @@ def __getattr__(self, key): assert gd.get('d', None) == 4 assert gd.get('e', None) == 5 assert gd.get('f', 'missing') == 'missing' + assert list(gd.values()) == [1, 3, 4] + assert list(gd.items()) == [('a', 1), ('c', 3), ('d', 4)] + assert list(gd) == ['a', 'c', 'd'] + assert gd == {'a': 1, 'c': 3, 'd': 4} + assert 'a' in gd + assert len(gd) == 3 + assert str(gd) == "<GetterDict(TestCls) {'a': 1, 'c': 3, 'd': 4}>" def test_orm_mode(): @@ -166,3 +173,87 @@ class Config: model = Model.from_orm(TestCls()) assert model.dict() == {'x': 1} + + +def test_root_validator(): + validator_value = None + + class TestCls: + x = 1 + y = 2 + + class Model(BaseModel): + x: int + y: int + z: int + + @root_validator(pre=True) + def change_input_data(cls, value): + nonlocal validator_value + validator_value = value + return {**value, 'z': value['x'] + value['y']} + + class Config: + orm_mode = True + + model = Model.from_orm(TestCls()) + assert model.dict() == {'x': 1, 'y': 2, 'z': 3} + assert isinstance(validator_value, GetterDict) + assert validator_value == {'x': 1, 'y': 2} + + +def test_custom_getter_dict(): + class TestCls: + x = 1 + y = 2 + + def custom_getter_dict(obj): + assert isinstance(obj, TestCls) + return {'x': 42, 'y': 24} + + class Model(BaseModel): + x: int + y: int + + class Config: + orm_mode = True + getter_dict = custom_getter_dict + + model = Model.from_orm(TestCls()) + assert model.dict() == {'x': 42, 'y': 24} + + +def test_custom_getter_dict_derived_model_class(): + class CustomCollection: + __custom__ = True + + def __iter__(self): + for elem in range(5): + yield elem + + class Example: + def __init__(self, *args, **kwargs): + self.col = CustomCollection() + self.id = 1 + self.name = 'name' + + class MyGetterDict(GetterDict): + def get(self, key: Any, default: Any = None) -> Any: + res = getattr(self._obj, key, default) + if hasattr(res, '__custom__'): + return list(res) + return res + + class ExampleBase(BaseModel): + name: str + col: List[int] + + class ExampleOrm(ExampleBase): + id: int + + class Config: + orm_mode = True + getter_dict = MyGetterDict + + model = ExampleOrm.from_orm(Example()) + assert model.dict() == {'name': 'name', 'col': [0, 1, 2, 3, 4], 'id': 1} diff --git a/tests/test_parse.py b/tests/test_parse.py --- a/tests/test_parse.py +++ b/tests/test_parse.py @@ -20,7 +20,7 @@ def test_parse_obj_fails(): with pytest.raises(ValidationError) as exc_info: Model.parse_obj([1, 2, 3]) assert exc_info.value.errors() == [ - {'loc': ('__obj__',), 'msg': 'Model expected dict not list', 'type': 'type_error'} + {'loc': ('__root__',), 'msg': 'Model expected dict not list', 'type': 'type_error'} ] @@ -84,14 +84,14 @@ def test_bad_ct(): with pytest.raises(ValidationError) as exc_info: Model.parse_raw('{"a": 12, "b": 8}', content_type='application/missing') assert exc_info.value.errors() == [ - {'loc': ('__obj__',), 'msg': 'Unknown content-type: application/missing', 'type': 'type_error'} + {'loc': ('__root__',), 'msg': 'Unknown content-type: application/missing', 'type': 'type_error'} ] def test_bad_proto(): with pytest.raises(ValidationError) as exc_info: Model.parse_raw('{"a": 12, "b": 8}', proto='foobar') - assert exc_info.value.errors() == [{'loc': ('__obj__',), 'msg': 'Unknown protocol: foobar', 'type': 'type_error'}] + assert exc_info.value.errors() == [{'loc': ('__root__',), 'msg': 'Unknown protocol: foobar', 'type': 'type_error'}] def test_file_json(tmpdir): diff --git a/tests/test_validators.py b/tests/test_validators.py --- a/tests/test_validators.py +++ b/tests/test_validators.py @@ -3,8 +3,8 @@ import pytest -from pydantic import BaseModel, ConfigError, ValidationError, errors, validator -from pydantic.class_validators import make_generic_validator +from pydantic import BaseModel, ConfigError, Extra, ValidationError, errors, validator +from pydantic.class_validators import make_generic_validator, root_validator def test_simple(): @@ -715,3 +715,167 @@ class Model(BaseModel): @validator('x', whole=True) def check_something(cls, v): return v + + +def test_root_validator(): + root_val_values = [] + + class Model(BaseModel): + a: int = 1 + b: str + + @validator('b') + def repeat_b(cls, v): + return v * 2 + + @root_validator + def root_validator(cls, values): + root_val_values.append(values) + if 'snap' in values.get('b', ''): + raise ValueError('foobar') + return dict(values, b='changed') + + assert Model(a='123', b='bar').dict() == {'a': 123, 'b': 'changed'} + + with pytest.raises(ValidationError) as exc_info: + Model(b='snap dragon') + assert exc_info.value.errors() == [{'loc': ('__root__',), 'msg': 'foobar', 'type': 'value_error'}] + + with pytest.raises(ValidationError) as exc_info: + Model(a='broken', b='bar') + assert exc_info.value.errors() == [ + {'loc': ('a',), 'msg': 'value is not a valid integer', 'type': 'type_error.integer'} + ] + + assert root_val_values == [{'a': 123, 'b': 'barbar'}, {'a': 1, 'b': 'snap dragonsnap dragon'}, {'b': 'barbar'}] + + +def test_root_validator_pre(): + root_val_values = [] + + class Model(BaseModel): + a: int = 1 + b: str + + @validator('b') + def repeat_b(cls, v): + return v * 2 + + @root_validator(pre=True) + def root_validator(cls, values): + root_val_values.append(values) + if 'snap' in values.get('b', ''): + raise ValueError('foobar') + return {'a': 42, 'b': 'changed'} + + assert Model(a='123', b='bar').dict() == {'a': 42, 'b': 'changedchanged'} + + with pytest.raises(ValidationError) as exc_info: + Model(b='snap dragon') + + assert root_val_values == [{'a': '123', 'b': 'bar'}, {'b': 'snap dragon'}] + assert exc_info.value.errors() == [{'loc': ('__root__',), 'msg': 'foobar', 'type': 'value_error'}] + + +def test_root_validator_repeat(): + with pytest.raises(errors.ConfigError, match='duplicate validator function'): + + class Model(BaseModel): + a: int = 1 + + @root_validator + def root_validator_repeated(cls, values): + return values + + @root_validator # noqa: F811 + def root_validator_repeated(cls, values): + return values + + +def test_root_validator_repeat2(): + with pytest.raises(errors.ConfigError, match='duplicate validator function'): + + class Model(BaseModel): + a: int = 1 + + @validator('a') + def repeat_validator(cls, v): + return v + + @root_validator(pre=True) # noqa: F811 + def repeat_validator(cls, values): + return values + + +def test_root_validator_self(): + with pytest.raises( + errors.ConfigError, match=r'Invalid signature for root validator root_validator: \(self, values\)' + ): + + class Model(BaseModel): + a: int = 1 + + @root_validator + def root_validator(self, values): + return values + + +def test_root_validator_extra(): + with pytest.raises(errors.ConfigError) as exc_info: + + class Model(BaseModel): + a: int = 1 + + @root_validator + def root_validator(cls, values, another): + return values + + assert str(exc_info.value) == ( + 'Invalid signature for root validator root_validator: (cls, values, another), should be: (cls, values).' + ) + + +def test_root_validator_types(): + root_val_values = None + + class Model(BaseModel): + a: int = 1 + b: str + + @root_validator + def root_validator(cls, values): + nonlocal root_val_values + root_val_values = cls, values + return values + + class Config: + extra = Extra.allow + + assert Model(b='bar', c='wobble').dict() == {'a': 1, 'b': 'bar', 'c': 'wobble'} + + assert root_val_values == (Model, {'a': 1, 'b': 'bar', 'c': 'wobble'}) + + +def test_root_validator_inheritance(): + calls = [] + + class Parent(BaseModel): + pass + + @root_validator + def root_validator_parent(cls, values): + calls.append(f'parent validator: {values}') + return {'extra1': 1, **values} + + class Child(Parent): + a: int + + @root_validator + def root_validator_child(cls, values): + calls.append(f'child validator: {values}') + return {'extra2': 2, **values} + + assert len(Child.__post_root_validators__) == 2 + assert len(Child.__pre_root_validators__) == 0 + assert Child(a=123).dict() == {'extra2': 2, 'extra1': 1, 'a': 123} + assert calls == ["parent validator: {'a': 123}", "child validator: {'extra1': 1, 'a': 123}"] diff --git a/tests/test_validators_dataclass.py b/tests/test_validators_dataclass.py --- a/tests/test_validators_dataclass.py +++ b/tests/test_validators_dataclass.py @@ -3,7 +3,7 @@ import pytest -from pydantic import ValidationError, validator +from pydantic import ValidationError, root_validator, validator from pydantic.dataclasses import dataclass @@ -108,3 +108,31 @@ def add_to_a(cls, v): return v + 5 assert Child(a=0).a == 5 + + +def test_root_validator(): + root_val_values = [] + + @dataclass + class MyDataclass: + a: int + b: str + + @validator('b') + def repeat_b(cls, v): + return v * 2 + + @root_validator + def root_validator(cls, values): + root_val_values.append(values) + if 'snap' in values.get('b', ''): + raise ValueError('foobar') + return dict(values, b='changed') + + assert asdict(MyDataclass(a='123', b='bar')) == {'a': 123, 'b': 'changed'} + + with pytest.raises(ValidationError) as exc_info: + MyDataclass(a=1, b='snap dragon') + assert root_val_values == [{'a': 123, 'b': 'barbar'}, {'a': 1, 'b': 'snap dragonsnap dragon'}] + + assert exc_info.value.errors() == [{'loc': ('__root__',), 'msg': 'foobar', 'type': 'value_error'}]
Root Errors and "__obj__" vs "__root__" Currently [here](https://github.com/samuelcolvin/pydantic/blob/master/pydantic/main.py#L343) (for invalid data to `parse_obj`) and [here](https://github.com/samuelcolvin/pydantic/blob/master/pydantic/main.py#L361) (in `parse_raw`) we use `'__obj__'` as the location for errors to indicate an error which is general to the model, not specific to a field. We should change this in v1 to `__root__` to better match other nomenclature, eg. custom root types, where we use `__root__`. We should also implement at some point entire model validation, as discussed at https://github.com/samuelcolvin/pydantic/issues/691#issuecomment-518318096. I guess to match the above naming, we should do this using a special value to a validator `@validator('__root__')`. If this raised an error it would end up in `ValidationError` details with `'location': '__root__'`, (Unless it's a "`@validator('__root__')`" validator for a submodel, when obviously it should have the location of that model. Perhaps it would would be nice to have a special decorator `@root_validator` which is an alias of `@validator('__root__')`, we should support multiple root validators either as a result of inheritance or on a single class. I guess the `__obj__` > `__root__` change must happen with v1 and the new root validator could go in a later release, but we should be sure we won't need other backwards incompatible changes to implement the root validator. Thoughts?
0.0
973de05a0119107fd0caa2b565c25776c41b9fb7
[ "tests/test_generics.py::test_generic_name", "tests/test_generics.py::test_double_parameterize_error", "tests/test_generics.py::test_value_validation", "tests/test_generics.py::test_methods_are_inherited", "tests/test_generics.py::test_config_is_inherited", "tests/test_generics.py::test_default_argument", "tests/test_generics.py::test_default_argument_for_typevar", "tests/test_generics.py::test_classvar", "tests/test_generics.py::test_non_annotated_field", "tests/test_generics.py::test_must_inherit_from_generic", "tests/test_generics.py::test_parameters_must_be_typevar", "tests/test_generics.py::test_subclass_can_be_genericized", "tests/test_generics.py::test_parameter_count", "tests/test_generics.py::test_cover_cache", "tests/test_generics.py::test_generic_config", "tests/test_generics.py::test_generic_instantiation_error", "tests/test_generics.py::test_parameterized_generic_instantiation_error", "tests/test_generics.py::test_deep_generic", "tests/test_generics.py::test_enum_generic", "tests/test_generics.py::test_generic", "tests/test_generics.py::test_alongside_concrete_generics", "tests/test_generics.py::test_complex_nesting", "tests/test_orm_mode.py::test_getdict", "tests/test_orm_mode.py::test_orm_mode", "tests/test_orm_mode.py::test_not_orm_mode", "tests/test_orm_mode.py::test_object_with_getattr", "tests/test_orm_mode.py::test_properties", "tests/test_orm_mode.py::test_extra_allow", "tests/test_orm_mode.py::test_extra_forbid", "tests/test_orm_mode.py::test_root_validator", "tests/test_orm_mode.py::test_custom_getter_dict", "tests/test_orm_mode.py::test_custom_getter_dict_derived_model_class", "tests/test_parse.py::test_obj", "tests/test_parse.py::test_parse_obj_fails", "tests/test_parse.py::test_parse_obj_submodel", "tests/test_parse.py::test_parse_obj_wrong_model", "tests/test_parse.py::test_parse_obj_root", "tests/test_parse.py::test_parse_root_list", "tests/test_parse.py::test_json", "tests/test_parse.py::test_json_ct", "tests/test_parse.py::test_pickle_ct", "tests/test_parse.py::test_pickle_proto", "tests/test_parse.py::test_pickle_not_allowed", "tests/test_parse.py::test_bad_ct", "tests/test_parse.py::test_bad_proto", "tests/test_parse.py::test_file_json", "tests/test_parse.py::test_file_json_no_ext", "tests/test_parse.py::test_file_pickle", "tests/test_parse.py::test_file_pickle_no_ext", "tests/test_parse.py::test_const_differentiates_union", "tests/test_validators.py::test_simple", "tests/test_validators.py::test_int_validation", "tests/test_validators.py::test_frozenset_validation", "tests/test_validators.py::test_validate_whole", "tests/test_validators.py::test_validate_kwargs", "tests/test_validators.py::test_validate_pre_error", "tests/test_validators.py::test_validating_assignment_ok", "tests/test_validators.py::test_validating_assignment_fail", "tests/test_validators.py::test_validating_assignment_dict", "tests/test_validators.py::test_validate_multiple", "tests/test_validators.py::test_classmethod", "tests/test_validators.py::test_duplicates", "tests/test_validators.py::test_use_bare", "tests/test_validators.py::test_use_no_fields", "tests/test_validators.py::test_validate_always", "tests/test_validators.py::test_validate_not_always", "tests/test_validators.py::test_wildcard_validators", "tests/test_validators.py::test_wildcard_validator_error", "tests/test_validators.py::test_invalid_field", "tests/test_validators.py::test_validate_child", "tests/test_validators.py::test_validate_child_extra", "tests/test_validators.py::test_validate_child_all", "tests/test_validators.py::test_validate_parent", "tests/test_validators.py::test_validate_parent_all", "tests/test_validators.py::test_inheritance_keep", "tests/test_validators.py::test_inheritance_replace", "tests/test_validators.py::test_inheritance_new", "tests/test_validators.py::test_validation_each_item", "tests/test_validators.py::test_key_validation", "tests/test_validators.py::test_validator_always_optional", "tests/test_validators.py::test_validator_always_pre", "tests/test_validators.py::test_validator_always_post", "tests/test_validators.py::test_validator_always_post_optional", "tests/test_validators.py::test_datetime_validator", "tests/test_validators.py::test_pre_called_once", "tests/test_validators.py::test_make_generic_validator[fields0-_v_]", "tests/test_validators.py::test_make_generic_validator[fields1-_v_]", "tests/test_validators.py::test_make_generic_validator[fields2-_v_,_field_]", "tests/test_validators.py::test_make_generic_validator[fields3-_v_,_config_]", "tests/test_validators.py::test_make_generic_validator[fields4-_v_,_values_]", "tests/test_validators.py::test_make_generic_validator[fields5-_v_,_field_,_config_]", "tests/test_validators.py::test_make_generic_validator[fields6-_v_,_field_,_values_]", "tests/test_validators.py::test_make_generic_validator[fields7-_v_,_config_,_values_]", "tests/test_validators.py::test_make_generic_validator[fields8-_v_,_field_,_values_,_config_]", "tests/test_validators.py::test_make_generic_validator[fields9-_cls_,_v_]", "tests/test_validators.py::test_make_generic_validator[fields10-_cls_,_v_]", "tests/test_validators.py::test_make_generic_validator[fields11-_cls_,_v_,_field_]", "tests/test_validators.py::test_make_generic_validator[fields12-_cls_,_v_,_config_]", "tests/test_validators.py::test_make_generic_validator[fields13-_cls_,_v_,_values_]", "tests/test_validators.py::test_make_generic_validator[fields14-_cls_,_v_,_field_,_config_]", "tests/test_validators.py::test_make_generic_validator[fields15-_cls_,_v_,_field_,_values_]", "tests/test_validators.py::test_make_generic_validator[fields16-_cls_,_v_,_config_,_values_]", "tests/test_validators.py::test_make_generic_validator[fields17-_cls_,_v_,_field_,_values_,_config_]", "tests/test_validators.py::test_make_generic_validator_kwargs", "tests/test_validators.py::test_make_generic_validator_invalid", "tests/test_validators.py::test_make_generic_validator_cls_kwargs", "tests/test_validators.py::test_make_generic_validator_cls_invalid", "tests/test_validators.py::test_make_generic_validator_self", "tests/test_validators.py::test_assert_raises_validation_error", "tests/test_validators.py::test_optional_validator", "tests/test_validators.py::test_whole", "tests/test_validators.py::test_root_validator", "tests/test_validators.py::test_root_validator_pre", "tests/test_validators.py::test_root_validator_repeat", "tests/test_validators.py::test_root_validator_repeat2", "tests/test_validators.py::test_root_validator_self", "tests/test_validators.py::test_root_validator_extra", "tests/test_validators.py::test_root_validator_types", "tests/test_validators.py::test_root_validator_inheritance", "tests/test_validators_dataclass.py::test_simple", "tests/test_validators_dataclass.py::test_validate_pre", "tests/test_validators_dataclass.py::test_validate_multiple", "tests/test_validators_dataclass.py::test_classmethod", "tests/test_validators_dataclass.py::test_validate_parent", "tests/test_validators_dataclass.py::test_inheritance_replace", "tests/test_validators_dataclass.py::test_root_validator" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-09-17 17:25:35+00:00
mit
4,909
pydantic__pydantic-823
diff --git a/docs/examples/json_orjson.py b/docs/examples/json_orjson.py new file mode 100644 --- /dev/null +++ b/docs/examples/json_orjson.py @@ -0,0 +1,21 @@ +from datetime import datetime +import orjson +from pydantic import BaseModel + +def orjson_dumps(v, *, default): + # orjson.dumps returns bytes, to match standard json.dumps we need to decode + return orjson.dumps(v, default=default).decode() + +class User(BaseModel): + id: int + name = 'John Doe' + signup_ts: datetime = None + + class Config: + json_loads = orjson.loads + json_dumps = orjson_dumps + + +user = User.parse_raw('{"id": 123, "signup_ts": 1234567890, "name": "John Doe"}') +print(user.json()) +#> {"id":123,"signup_ts":"2009-02-13T23:31:30+00:00","name":"John Doe"} diff --git a/docs/examples/json_ujson.py b/docs/examples/json_ujson.py new file mode 100644 --- /dev/null +++ b/docs/examples/json_ujson.py @@ -0,0 +1,15 @@ +from datetime import datetime +import ujson +from pydantic import BaseModel + +class User(BaseModel): + id: int + name = 'John Doe' + signup_ts: datetime = None + + class Config: + json_loads = ujson.loads + +user = User.parse_raw('{"id": 123, "signup_ts": 1234567890, "name": "John Doe"}') +print(user) +#> User id=123 signup_ts=datetime.datetime(2009, 2, 13, 23, 31, 30, tzinfo=datetime.timezone.utc) name='John Doe' diff --git a/pydantic/env_settings.py b/pydantic/env_settings.py --- a/pydantic/env_settings.py +++ b/pydantic/env_settings.py @@ -1,4 +1,3 @@ -import json import os from typing import Any, Dict, Optional, cast @@ -47,7 +46,7 @@ def _build_environ(self) -> Dict[str, Optional[str]]: if env_val: if field.is_complex(): try: - env_val = json.loads(env_val) + env_val = self.__config__.json_loads(env_val) # type: ignore except ValueError as e: raise SettingsError(f'error parsing JSON for "{env_name}"') from e d[field.alias] = env_val diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -63,11 +63,13 @@ class BaseConfig: validate_assignment = False error_msg_templates: Dict[str, str] = {} arbitrary_types_allowed = False - json_encoders: Dict[AnyType, AnyCallable] = {} orm_mode: bool = False alias_generator: Optional[Callable[[str], str]] = None keep_untouched: Tuple[type, ...] = () schema_extra: Dict[str, Any] = {} + json_loads: Callable[[str], Any] = json.loads + json_dumps: Callable[..., str] = json.dumps + json_encoders: Dict[AnyType, AnyCallable] = {} @classmethod def get_field_schema(cls, name: str) -> Dict[str, str]: @@ -307,7 +309,7 @@ def json( data = self.dict(include=include, exclude=exclude, by_alias=by_alias, skip_defaults=skip_defaults) if self._custom_root_type: data = data['__root__'] - return json.dumps(data, default=encoder, **dumps_kwargs) + return self.__config__.json_dumps(data, default=encoder, **dumps_kwargs) @classmethod def parse_obj(cls: Type['Model'], obj: Any) -> 'Model': @@ -334,7 +336,12 @@ def parse_raw( ) -> 'Model': try: obj = load_str_bytes( - b, proto=proto, content_type=content_type, encoding=encoding, allow_pickle=allow_pickle + b, + proto=proto, + content_type=content_type, + encoding=encoding, + allow_pickle=allow_pickle, + json_loads=cls.__config__.json_loads, ) except (ValueError, TypeError, UnicodeDecodeError) as e: raise ValidationError([ErrorWrapper(e, loc='__obj__')], cls) @@ -437,7 +444,7 @@ def schema(cls, by_alias: bool = True) -> 'DictStrAny': def schema_json(cls, *, by_alias: bool = True, **dumps_kwargs: Any) -> str: from .json import pydantic_encoder - return json.dumps(cls.schema(by_alias=by_alias), default=pydantic_encoder, **dumps_kwargs) + return cls.__config__.json_dumps(cls.schema(by_alias=by_alias), default=pydantic_encoder, **dumps_kwargs) @classmethod def __get_validators__(cls) -> 'CallableGenerator': diff --git a/pydantic/parse.py b/pydantic/parse.py --- a/pydantic/parse.py +++ b/pydantic/parse.py @@ -1,15 +1,11 @@ +import json import pickle from enum import Enum from pathlib import Path -from typing import Any, Union +from typing import Any, Callable, Union from .types import StrBytes -try: - import ujson as json -except ImportError: - import json # type: ignore - class Protocol(str, Enum): json = 'json' @@ -17,7 +13,13 @@ class Protocol(str, Enum): def load_str_bytes( - b: StrBytes, *, content_type: str = None, encoding: str = 'utf8', proto: Protocol = None, allow_pickle: bool = False + b: StrBytes, + *, + content_type: str = None, + encoding: str = 'utf8', + proto: Protocol = None, + allow_pickle: bool = False, + json_loads: Callable[[str], Any] = json.loads, ) -> Any: if proto is None and content_type: if content_type.endswith(('json', 'javascript')): @@ -32,7 +34,7 @@ def load_str_bytes( if proto == Protocol.json: if isinstance(b, bytes): b = b.decode(encoding) - return json.loads(b) + return json_loads(b) elif proto == Protocol.pickle: if not allow_pickle: raise RuntimeError('Trying to decode with pickle with allow_pickle=False') diff --git a/pydantic/validators.py b/pydantic/validators.py --- a/pydantic/validators.py +++ b/pydantic/validators.py @@ -1,4 +1,3 @@ -import json import re import sys from collections import OrderedDict @@ -424,9 +423,9 @@ def constr_strip_whitespace(v: 'StrBytes', field: 'Field', config: 'BaseConfig') return v -def validate_json(v: Any) -> Any: +def validate_json(v: Any, config: 'BaseConfig') -> Any: try: - return json.loads(v) + return config.json_loads(v) # type: ignore except ValueError: raise errors.JsonError() except TypeError: diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -99,7 +99,6 @@ def extra(self): 'dataclasses>=0.6;python_version<"3.7"' ], extras_require={ - 'ujson': ['ujson>=1.35'], 'email': ['email-validator>=1.0.3'], 'typing_extensions': ['typing-extensions>=3.7.2'] },
pydantic/pydantic
cccf39e7c996fd861758a106d291a526a1fc1c48
as discussed in #599 @pablogamboa suggested allowing a custom JSON encoder / decoder library. This would allow libraries like orjson to be used without making them explicit dependencies of pydantic. The problem here is going to be how to deal with the `default` argument with standard lib `json` and `orjson` allow, but not `ujson`. If this requires a breaking change it should be done with the bump to version 1. Did you think about implementing something similar to @JrooTJunior done in https://github.com/aiogram/aiogram/blob/dev-2.x/aiogram/utils/json.py? I would prefer more like the [`json_serialize`](https://docs.aiohttp.org/en/stable/client_quickstart.html#json-request) argument in aiohttp, so the end user is responsible for implementing a function that correct encodes or decodes JSON. Yes. `json_serialize` is more good way. I want to remove this code from aiogram. > https://github.com/aiogram/aiogram/blob/dev-2.x/aiogram/utils/json.py @samuelcolvin is anyone implementing this now? If not, I want to implement this feature. No one has started this. PR very welcome.
diff --git a/tests/test_json.py b/tests/test_json.py --- a/tests/test_json.py +++ b/tests/test_json.py @@ -167,3 +167,29 @@ class Model(BaseModel): __root__: List[str] assert Model(__root__=['a', 'b']).json() == '["a", "b"]' + + +def test_custom_decode_encode(): + load_calls, dump_calls = 0, 0 + + def custom_loads(s): + nonlocal load_calls + load_calls += 1 + return json.loads(s.strip('$')) + + def custom_dumps(s, default=None, **kwargs): + nonlocal dump_calls + dump_calls += 1 + return json.dumps(s, default=default, indent=2) + + class Model(BaseModel): + a: int + b: str + + class Config: + json_loads = custom_loads + json_dumps = custom_dumps + + m = Model.parse_raw('${"a": 1, "b": "foo"}$$') + assert m.dict() == {'a': 1, 'b': 'foo'} + assert m.json() == '{\n "a": 1,\n "b": "foo"\n}'
Allow custom json encoder / decoder makes more sense, perhaps we could have `dump_json` and `load_json` attributes of `Config` which are then used in `parse_json()`, `json()` and `schema_json()` (and anywhere else we use encode/decode json that I've forgotten about). _Originally posted by @samuelcolvin in https://github.com/samuelcolvin/pydantic/pull/599#issuecomment-516968833_
0.0
cccf39e7c996fd861758a106d291a526a1fc1c48
[ "tests/test_json.py::test_custom_decode_encode" ]
[ "tests/test_json.py::test_encoding[input0-\"ebcdab58-6eb8-46fb-a190-d07a33e9eac8\"]", "tests/test_json.py::test_encoding[input1-\"192.168.0.1\"]", "tests/test_json.py::test_encoding[input2-\"black\"]", "tests/test_json.py::test_encoding[input3-\"#010c7b\"]", "tests/test_json.py::test_encoding[input4-\"**********\"]", "tests/test_json.py::test_encoding[input5-\"\"]", "tests/test_json.py::test_encoding[input6-\"**********\"]", "tests/test_json.py::test_encoding[input7-\"\"]", "tests/test_json.py::test_encoding[input8-\"::1:0:1\"]", "tests/test_json.py::test_encoding[input9-\"192.168.0.0/24\"]", "tests/test_json.py::test_encoding[input10-\"2001:db00::/120\"]", "tests/test_json.py::test_encoding[input11-\"192.168.0.0/24\"]", "tests/test_json.py::test_encoding[input12-\"2001:db00::/120\"]", "tests/test_json.py::test_encoding[input13-\"2032-01-01T01:01:00\"]", "tests/test_json.py::test_encoding[input14-\"2032-01-01T01:01:00+00:00\"]", "tests/test_json.py::test_encoding[input15-\"2032-01-01T00:00:00\"]", "tests/test_json.py::test_encoding[input16-\"12:34:56\"]", "tests/test_json.py::test_encoding[input17-1036834.000056]", "tests/test_json.py::test_encoding[input18-[1,", "tests/test_json.py::test_encoding[input19-[1,", "tests/test_json.py::test_encoding[input20-[0,", "tests/test_json.py::test_encoding[this", "tests/test_json.py::test_encoding[input22-12.34]", "tests/test_json.py::test_encoding[input23-{\"a\":", "tests/test_json.py::test_encoding[MyEnum.foo-\"bar\"]", "tests/test_json.py::test_path_encoding", "tests/test_json.py::test_model_encoding", "tests/test_json.py::test_invalid_model", "tests/test_json.py::test_iso_timedelta[input0-P12DT0H0M34.000056S]", "tests/test_json.py::test_iso_timedelta[input1-P1001DT1H2M3.654321S]", "tests/test_json.py::test_custom_encoder", "tests/test_json.py::test_custom_iso_timedelta", "tests/test_json.py::test_custom_encoder_arg", "tests/test_json.py::test_encode_dataclass", "tests/test_json.py::test_encode_pydantic_dataclass", "tests/test_json.py::test_encode_custom_root" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-09-20 12:47:26+00:00
mit
4,910
pydantic__pydantic-824
diff --git a/docs/examples/schema1.py b/docs/examples/schema1.py --- a/docs/examples/schema1.py +++ b/docs/examples/schema1.py @@ -1,5 +1,5 @@ from enum import Enum -from pydantic import BaseModel, Schema +from pydantic import BaseModel, Field class FooBar(BaseModel): count: int @@ -15,12 +15,9 @@ class MainModel(BaseModel): """ This is the description of the main model """ - foo_bar: FooBar = Schema(...) - gender: Gender = Schema( - None, - alias='Gender', - ) - snap: int = Schema( + foo_bar: FooBar = Field(...) + gender: Gender = Field(None, alias='Gender') + snap: int = Field( 42, title='The Snap', description='this is the value of snap', diff --git a/pydantic/__init__.py b/pydantic/__init__.py --- a/pydantic/__init__.py +++ b/pydantic/__init__.py @@ -4,10 +4,9 @@ from .env_settings import BaseSettings from .error_wrappers import ValidationError from .errors import * -from .fields import Required +from .fields import Field, Required, Schema from .main import * from .networks import * from .parse import Protocol -from .schema import Schema from .types import * from .version import VERSION diff --git a/pydantic/class_validators.py b/pydantic/class_validators.py --- a/pydantic/class_validators.py +++ b/pydantic/class_validators.py @@ -31,10 +31,10 @@ def __init__( if TYPE_CHECKING: # pragma: no cover from .main import BaseConfig - from .fields import Field + from .fields import ModelField from .types import ModelOrDc - ValidatorCallable = Callable[[Optional[ModelOrDc], Any, Dict[str, Any], Field, Type[BaseConfig]], Any] + ValidatorCallable = Callable[[Optional[ModelOrDc], Any, Dict[str, Any], ModelField, Type[BaseConfig]], Any] ValidatorsList = List[ValidatorCallable] ValidatorListDict = Dict[str, List[Validator]] diff --git a/pydantic/fields.py b/pydantic/fields.py --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -1,3 +1,4 @@ +import warnings from typing import ( TYPE_CHECKING, Any, @@ -38,13 +39,131 @@ from .class_validators import ValidatorsList # noqa: F401 from .error_wrappers import ErrorList from .main import BaseConfig, BaseModel # noqa: F401 - from .schema import Schema # noqa: F401 from .types import ModelOrDc # noqa: F401 ValidateReturn = Tuple[Optional[Any], Optional[ErrorList]] LocStr = Union[Tuple[Union[int, str], ...], str] +class FieldInfo: + """ + Captures extra information about a field. + """ + + __slots__ = ( + 'default', + 'alias', + 'title', + 'description', + 'const', + 'gt', + 'ge', + 'lt', + 'le', + 'multiple_of', + 'min_items', + 'max_items', + 'min_length', + 'max_length', + 'regex', + 'extra', + ) + + def __init__(self, default: Any, **kwargs: Any) -> None: + self.default = default + self.alias = kwargs.pop('alias', None) + self.title = kwargs.pop('title', None) + self.description = kwargs.pop('description', None) + self.const = kwargs.pop('const', None) + self.gt = kwargs.pop('gt', None) + self.ge = kwargs.pop('ge', None) + self.lt = kwargs.pop('lt', None) + self.le = kwargs.pop('le', None) + self.multiple_of = kwargs.pop('multiple_of', None) + self.min_items = kwargs.pop('min_items', None) + self.max_items = kwargs.pop('max_items', None) + self.min_length = kwargs.pop('min_length', None) + self.max_length = kwargs.pop('max_length', None) + self.regex = kwargs.pop('regex', None) + self.extra = kwargs + + def __repr__(self) -> str: + attrs = ((s, getattr(self, s)) for s in self.__slots__) + return 'FieldInfo({})'.format(', '.join(f'{a}: {v!r}' for a, v in attrs if v is not None)) + + +def Field( + default: Any, + *, + alias: str = None, + title: str = None, + description: str = None, + const: bool = None, + gt: float = None, + ge: float = None, + lt: float = None, + le: float = None, + multiple_of: float = None, + min_items: int = None, + max_items: int = None, + min_length: int = None, + max_length: int = None, + regex: str = None, + **extra: Any, +) -> Any: + """ + Used to provide extra information about a field, either for the model schema or complex valiation. Some arguments + apply only to number fields (``int``, ``float``, ``Decimal``) and some apply only to ``str``. + + :param default: since this is replacing the field’s default, its first argument is used + to set the default, use ellipsis (``...``) to indicate the field is required + :param alias: the public name of the field + :param title: can be any string, used in the schema + :param description: can be any string, used in the schema + :param const: this field is required and *must* take it's default value + :param gt: only applies to numbers, requires the field to be "greater than". The schema + will have an ``exclusiveMinimum`` validation keyword + :param ge: only applies to numbers, requires the field to be "greater than or equal to". The + schema will have a ``minimum`` validation keyword + :param lt: only applies to numbers, requires the field to be "less than". The schema + will have an ``exclusiveMaximum`` validation keyword + :param le: only applies to numbers, requires the field to be "less than or equal to". The + schema will have a ``maximum`` validation keyword + :param multiple_of: only applies to numbers, requires the field to be "a multiple of". The + schema will have a ``multipleOf`` validation keyword + :param min_length: only applies to strings, requires the field to have a minimum length. The + schema will have a ``maximum`` validation keyword + :param max_length: only applies to strings, requires the field to have a maximum length. The + schema will have a ``maxLength`` validation keyword + :param regex: only applies to strings, requires the field match agains a regular expression + pattern string. The schema will have a ``pattern`` validation keyword + :param **extra: any additional keyword arguments will be added as is to the schema + """ + return FieldInfo( + default, + alias=alias, + title=title, + description=description, + const=const, + gt=gt, + ge=ge, + lt=lt, + le=le, + multiple_of=multiple_of, + min_items=min_items, + max_items=max_items, + min_length=min_length, + max_length=max_length, + regex=regex, + **extra, + ) + + +def Schema(default: Any, **kwargs: Any) -> Any: + warnings.warn('`Schema` is deprecated, use `Field` instead', DeprecationWarning) + return Field(default, **kwargs) + + # used to be an enum but changed to int's for small performance improvement as less access overhead SHAPE_SINGLETON = 1 SHAPE_LIST = 2 @@ -56,7 +175,7 @@ SHAPE_FROZENSET = 8 -class Field: +class ModelField: __slots__ = ( 'type_', 'sub_fields', @@ -70,7 +189,7 @@ class Field: 'name', 'alias', 'has_alias', - 'schema', + 'field_info', 'validate_always', 'allow_none', 'shape', @@ -88,7 +207,7 @@ def __init__( default: Any = None, required: bool = True, alias: str = None, - schema: Optional['Schema'] = None, + field_info: Optional[FieldInfo] = None, ) -> None: self.name: str = name @@ -99,12 +218,12 @@ def __init__( self.default: Any = default self.required: bool = required self.model_config = model_config - self.schema: Optional['Schema'] = schema + self.field_info: Optional[FieldInfo] = field_info self.allow_none: bool = False self.validate_always: bool = False - self.sub_fields: Optional[List[Field]] = None - self.key_field: Optional[Field] = None + self.sub_fields: Optional[List[ModelField]] = None + self.key_field: Optional[ModelField] = None self.validators: 'ValidatorsList' = [] self.pre_validators: Optional['ValidatorsList'] = None self.post_validators: Optional['ValidatorsList'] = None @@ -121,36 +240,36 @@ def infer( annotation: Any, class_validators: Optional[Dict[str, Validator]], config: Type['BaseConfig'], - ) -> 'Field': - schema_from_config = config.get_field_schema(name) - from .schema import Schema, get_annotation_from_schema # noqa: F811 + ) -> 'ModelField': + field_info_from_config = config.get_field_info(name) + from .schema import get_annotation_from_field_info - if isinstance(value, Schema): - schema = value - value = schema.default + if isinstance(value, FieldInfo): + field_info = value + value = field_info.default else: - schema = Schema(value, **schema_from_config) # type: ignore - schema.alias = schema.alias or schema_from_config.get('alias') + field_info = FieldInfo(value, **field_info_from_config) + field_info.alias = field_info.alias or field_info_from_config.get('alias') required = value == Required - annotation = get_annotation_from_schema(annotation, schema) + annotation = get_annotation_from_field_info(annotation, field_info) return cls( name=name, type_=annotation, - alias=schema.alias, + alias=field_info.alias, class_validators=class_validators, default=None if required else value, required=required, model_config=config, - schema=schema, + field_info=field_info, ) def set_config(self, config: Type['BaseConfig']) -> None: self.model_config = config - schema_from_config = config.get_field_schema(self.name) + schema_from_config = config.get_field_info(self.name) if schema_from_config: - self.schema = cast('Schema', self.schema) - self.schema.alias = self.schema.alias or schema_from_config.get('alias') - self.alias = cast(str, self.schema.alias) + self.field_info = cast(FieldInfo, self.field_info) + self.field_info.alias = self.field_info.alias or schema_from_config.get('alias') + self.alias = cast(str, self.field_info.alias) @property def alt_alias(self) -> bool: @@ -266,7 +385,7 @@ def _type_analysis(self) -> None: # noqa: C901 (ignore complexity) # type_ has been refined eg. as the type of a List and sub_fields needs to be populated self.sub_fields = [self._create_sub_type(self.type_, '_' + self.name)] - def _create_sub_type(self, type_: AnyType, name: str, *, for_keys: bool = False) -> 'Field': + def _create_sub_type(self, type_: AnyType, name: str, *, for_keys: bool = False) -> 'ModelField': return self.__class__( type_=type_, name=name, @@ -288,7 +407,7 @@ def _populate_validators(self) -> None: # Add const validator self.pre_validators = [] self.post_validators = [] - if self.schema and self.schema.const: + if self.field_info and self.field_info.const: self.pre_validators = [make_generic_validator(constant_validator)] if class_validators_: @@ -488,7 +607,7 @@ def is_complex(self) -> bool: ) def __repr__(self) -> str: - return f'<Field({self})>' + return f'<ModelField({self})>' def __str__(self) -> str: parts = [self.name, 'type=' + display_as_type(self.type_)] diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -12,7 +12,7 @@ from .class_validators import ROOT_KEY, ValidatorGroup, extract_root_validators, extract_validators, inherit_validators from .error_wrappers import ErrorWrapper, ValidationError from .errors import ConfigError, DictError, ExtraError, MissingError -from .fields import SHAPE_MAPPING, Field +from .fields import SHAPE_MAPPING, ModelField from .json import custom_pydantic_encoder, pydantic_encoder from .parse import Protocol, load_file, load_str_bytes from .schema import model_schema @@ -73,16 +73,16 @@ class BaseConfig: json_encoders: Dict[AnyType, AnyCallable] = {} @classmethod - def get_field_schema(cls, name: str) -> Dict[str, str]: - field_config = cls.fields.get(name) or {} - if isinstance(field_config, str): - field_config = {'alias': field_config} - elif cls.alias_generator and 'alias' not in field_config: + def get_field_info(cls, name: str) -> Dict[str, str]: + field_info = cls.fields.get(name) or {} + if isinstance(field_info, str): + field_info = {'alias': field_info} + elif cls.alias_generator and 'alias' not in field_info: alias = cls.alias_generator(name) if not isinstance(alias, str): raise TypeError(f'Config.alias_generator must return str, not {type(alias)}') - field_config['alias'] = alias - return field_config + field_info['alias'] = alias + return field_info def inherit_config(self_config: 'ConfigType', parent_config: 'ConfigType') -> 'ConfigType': @@ -112,7 +112,7 @@ def is_valid_field(name: str) -> bool: return ROOT_KEY == name -def validate_custom_root_type(fields: Dict[str, Field]) -> None: +def validate_custom_root_type(fields: Dict[str, ModelField]) -> None: if len(fields) > 1: raise ValueError('__root__ cannot be mixed with other fields') if fields[ROOT_KEY].shape == SHAPE_MAPPING: @@ -125,7 +125,7 @@ def validate_custom_root_type(fields: Dict[str, Field]) -> None: class MetaModel(ABCMeta): @no_type_check # noqa C901 def __new__(mcs, name, bases, namespace): - fields: Dict[str, Field] = {} + fields: Dict[str, ModelField] = {} config = BaseConfig validators: 'ValidatorListDict' = {} pre_root_validators, post_root_validators = [], [] @@ -164,7 +164,7 @@ def __new__(mcs, name, bases, namespace): value = namespace.get(ann_name, ...) if isinstance(value, untouched_types) and ann_type != PyObject: continue - fields[ann_name] = Field.infer( + fields[ann_name] = ModelField.infer( name=ann_name, value=value, annotation=ann_type, @@ -180,7 +180,7 @@ def __new__(mcs, name, bases, namespace): and var_name not in class_vars ): validate_field_name(bases, var_name) - inferred = Field.infer( + inferred = ModelField.infer( name=var_name, value=value, annotation=annotations.get(var_name), @@ -220,7 +220,7 @@ def __new__(mcs, name, bases, namespace): class BaseModel(metaclass=MetaModel): if TYPE_CHECKING: # pragma: no cover # populated by the metaclass, defined here to help IDEs only - __fields__: Dict[str, Field] = {} + __fields__: Dict[str, ModelField] = {} __validators__: Dict[str, AnyCallable] = {} __pre_root_validators__: List[AnyCallable] __post_root_validators__: List[AnyCallable] @@ -441,7 +441,7 @@ def copy( return m @property - def fields(self) -> Dict[str, Field]: + def fields(self) -> Dict[str, ModelField]: return self.__fields__ @classmethod diff --git a/pydantic/networks.py b/pydantic/networks.py --- a/pydantic/networks.py +++ b/pydantic/networks.py @@ -15,7 +15,7 @@ from .validators import constr_length_validator, str_validator if TYPE_CHECKING: # pragma: no cover - from .fields import Field + from .fields import ModelField from .main import BaseConfig # noqa: F401 from .typing import AnyCallable @@ -143,7 +143,7 @@ def __get_validators__(cls) -> 'CallableGenerator': yield cls.validate @classmethod - def validate(cls, value: Any, field: 'Field', config: 'BaseConfig') -> 'AnyUrl': + def validate(cls, value: Any, field: 'ModelField', config: 'BaseConfig') -> 'AnyUrl': if type(value) == cls: return value value = str_validator(value) diff --git a/pydantic/schema.py b/pydantic/schema.py --- a/pydantic/schema.py +++ b/pydantic/schema.py @@ -12,7 +12,7 @@ from pydantic.color import Color from .class_validators import ROOT_KEY -from .fields import SHAPE_LIST, SHAPE_MAPPING, SHAPE_SET, SHAPE_SINGLETON, SHAPE_TUPLE, Field +from .fields import SHAPE_LIST, SHAPE_MAPPING, SHAPE_SET, SHAPE_SINGLETON, SHAPE_TUPLE, FieldInfo, ModelField from .json import pydantic_encoder from .networks import AnyUrl, EmailStr, IPvAnyAddress, IPvAnyInterface, IPvAnyNetwork, NameEmail from .types import ( @@ -43,121 +43,9 @@ if TYPE_CHECKING: # pragma: no cover from .main import BaseModel # noqa: F401 - -__all__ = [ - 'Schema', - 'schema', - 'model_schema', - 'field_schema', - 'get_model_name_map', - 'get_flat_models_from_model', - 'get_flat_models_from_field', - 'get_flat_models_from_fields', - 'get_flat_models_from_models', - 'get_long_model_name', - 'field_type_schema', - 'model_process_schema', - 'model_type_schema', - 'field_singleton_sub_fields_schema', - 'field_singleton_schema', - 'get_annotation_from_schema', -] - default_prefix = '#/definitions/' -class Schema: - """ - Used to provide extra information about a field in a model schema. The parameters will be - converted to validations and will add annotations to the generated JSON Schema. Some arguments - apply only to number fields (``int``, ``float``, ``Decimal``) and some apply only to ``str`` - - :param default: since the Schema is replacing the field’s default, its first argument is used - to set the default, use ellipsis (``...``) to indicate the field is required - :param alias: the public name of the field - :param title: can be any string, used in the schema - :param description: can be any string, used in the schema - :param const: this field is required and *must* take it's default value - :param gt: only applies to numbers, requires the field to be "greater than". The schema - will have an ``exclusiveMinimum`` validation keyword - :param ge: only applies to numbers, requires the field to be "greater than or equal to". The - schema will have a ``minimum`` validation keyword - :param lt: only applies to numbers, requires the field to be "less than". The schema - will have an ``exclusiveMaximum`` validation keyword - :param le: only applies to numbers, requires the field to be "less than or equal to". The - schema will have a ``maximum`` validation keyword - :param multiple_of: only applies to numbers, requires the field to be "a multiple of". The - schema will have a ``multipleOf`` validation keyword - :param min_length: only applies to strings, requires the field to have a minimum length. The - schema will have a ``maximum`` validation keyword - :param max_length: only applies to strings, requires the field to have a maximum length. The - schema will have a ``maxLength`` validation keyword - :param regex: only applies to strings, requires the field match agains a regular expression - pattern string. The schema will have a ``pattern`` validation keyword - :param **extra: any additional keyword arguments will be added as is to the schema - """ - - __slots__ = ( - 'default', - 'alias', - 'title', - 'description', - 'const', - 'gt', - 'ge', - 'lt', - 'le', - 'multiple_of', - 'min_items', - 'max_items', - 'min_length', - 'max_length', - 'regex', - 'extra', - ) - - def __init__( - self, - default: Any, - *, - alias: str = None, - title: str = None, - description: str = None, - const: bool = None, - gt: float = None, - ge: float = None, - lt: float = None, - le: float = None, - multiple_of: float = None, - min_items: int = None, - max_items: int = None, - min_length: int = None, - max_length: int = None, - regex: str = None, - **extra: Any, - ) -> None: - self.default = default - self.alias = alias - self.title = title - self.description = description - self.const = const - self.extra = extra - self.gt = gt - self.ge = ge - self.lt = lt - self.le = le - self.multiple_of = multiple_of - self.min_items = min_items - self.max_items = max_items - self.min_length = min_length - self.max_length = max_length - self.regex = regex - - def __repr__(self) -> str: - attrs = ((s, getattr(self, s)) for s in self.__slots__) - return 'Schema({})'.format(', '.join(f'{a}: {v!r}' for a, v in attrs if v is not None)) - - def schema( models: Sequence[Type['BaseModel']], *, @@ -234,7 +122,7 @@ def model_schema(model: Type['BaseModel'], by_alias: bool = True, ref_prefix: Op def field_schema( - field: Field, + field: ModelField, *, by_alias: bool = True, model_name_map: Dict[Type['BaseModel'], str], @@ -247,7 +135,7 @@ def field_schema( is a model and has sub-models, and those sub-models don't have overrides (as ``title``, ``default``, etc), they will be included in the definitions and referenced in the schema instead of included recursively. - :param field: a Pydantic ``Field`` + :param field: a Pydantic ``ModelField`` :param by_alias: use the defined alias (if any) in the returned schema :param model_name_map: used to generate the JSON Schema references to other models included in the definitions :param ref_prefix: the JSON Pointer prefix to use for references to other schemas, if None, the default of @@ -257,16 +145,20 @@ def field_schema( """ ref_prefix = ref_prefix or default_prefix schema_overrides = False - schema = cast('Schema', field.schema) - s = dict(title=schema.title or field.alias.title().replace('_', ' ')) - if schema.title: + field_info = cast(FieldInfo, field.field_info) + s = dict(title=field_info.title or field.alias.title().replace('_', ' ')) + if field_info.title: schema_overrides = True - if schema.description: - s['description'] = schema.description + if field_info.description: + s['description'] = field_info.description schema_overrides = True - if not field.required and not (field.schema is not None and field.schema.const) and field.default is not None: + if ( + not field.required + and not (field.field_info is not None and field.field_info.const) + and field.default is not None + ): s['default'] = encode_default(field.default) schema_overrides = True @@ -307,27 +199,27 @@ def field_schema( ) -def get_field_schema_validations(field: Field) -> Dict[str, Any]: +def get_field_schema_validations(field: ModelField) -> Dict[str, Any]: """ Get the JSON Schema validation keywords for a ``field`` with an annotation of - a Pydantic ``Schema`` with validation arguments. + a Pydantic ``FieldInfo`` with validation arguments. """ f_schema: Dict[str, Any] = {} if lenient_issubclass(field.type_, (str, bytes)): for attr_name, t, keyword in _str_types_attrs: - attr = getattr(field.schema, attr_name, None) + attr = getattr(field.field_info, attr_name, None) if isinstance(attr, t): f_schema[keyword] = attr if lenient_issubclass(field.type_, numeric_types) and not issubclass(field.type_, bool): for attr_name, t, keyword in _numeric_types_attrs: - attr = getattr(field.schema, attr_name, None) + attr = getattr(field.field_info, attr_name, None) if isinstance(attr, t): f_schema[keyword] = attr - if field.schema is not None and field.schema.const: + if field.field_info is not None and field.field_info.const: f_schema['const'] = field.default - schema = cast('Schema', field.schema) - if schema.extra: - f_schema.update(schema.extra) + field_info = cast(FieldInfo, field.field_info) + if field_info.extra: + f_schema.update(field_info.extra) return f_schema @@ -376,20 +268,20 @@ def get_flat_models_from_model( flat_models: Set[Type['BaseModel']] = set() flat_models.add(model) known_models |= flat_models - fields = cast(Sequence[Field], model.__fields__.values()) + fields = cast(Sequence[ModelField], model.__fields__.values()) flat_models |= get_flat_models_from_fields(fields, known_models=known_models) return flat_models -def get_flat_models_from_field(field: Field, known_models: Set[Type['BaseModel']]) -> Set[Type['BaseModel']]: +def get_flat_models_from_field(field: ModelField, known_models: Set[Type['BaseModel']]) -> Set[Type['BaseModel']]: """ - Take a single Pydantic ``Field`` (from a model) that could have been declared as a sublcass of BaseModel + Take a single Pydantic ``ModelField`` (from a model) that could have been declared as a sublcass of BaseModel (so, it could be a submodel), and generate a set with its model and all the sub-models in the tree. I.e. if you pass a field that was declared to be of type ``Foo`` (subclass of BaseModel) as ``field``, and that model ``Foo`` has a field of type ``Bar`` (also subclass of ``BaseModel``) and that model ``Bar`` has a field of type ``Baz`` (also subclass of ``BaseModel``), the return value will be ``set([Foo, Bar, Baz])``. - :param field: a Pydantic ``Field`` + :param field: a Pydantic ``ModelField`` :param known_models: used to solve circular references :return: a set with the model used in the declaration for this field, if any, and all its sub-models """ @@ -408,16 +300,16 @@ def get_flat_models_from_field(field: Field, known_models: Set[Type['BaseModel'] def get_flat_models_from_fields( - fields: Sequence[Field], known_models: Set[Type['BaseModel']] + fields: Sequence[ModelField], known_models: Set[Type['BaseModel']] ) -> Set[Type['BaseModel']]: """ - Take a list of Pydantic ``Field``s (from a model) that could have been declared as sublcasses of ``BaseModel`` + Take a list of Pydantic ``ModelField``s (from a model) that could have been declared as sublcasses of ``BaseModel`` (so, any of them could be a submodel), and generate a set with their models and all the sub-models in the tree. I.e. if you pass a the fields of a model ``Foo`` (subclass of ``BaseModel``) as ``fields``, and on of them has a field of type ``Bar`` (also subclass of ``BaseModel``) and that model ``Bar`` has a field of type ``Baz`` (also subclass of ``BaseModel``), the return value will be ``set([Foo, Bar, Baz])``. - :param fields: a list of Pydantic ``Field``s + :param fields: a list of Pydantic ``ModelField``s :param known_models: used to solve circular references :return: a set with any model declared in the fields, and all their sub-models """ @@ -444,7 +336,7 @@ def get_long_model_name(model: Type['BaseModel']) -> str: def field_type_schema( - field: Field, + field: ModelField, *, by_alias: bool, model_name_map: Dict[Type['BaseModel'], str], @@ -477,7 +369,7 @@ def field_type_schema( return {'type': 'array', 'uniqueItems': True, 'items': f_schema}, definitions, nested_models elif field.shape == SHAPE_MAPPING: dict_schema: Dict[str, Any] = {'type': 'object'} - key_field = cast(Field, field.key_field) + key_field = cast(ModelField, field.key_field) regex = getattr(key_field.type_, 'regex', None) f_schema, f_definitions, f_nested_models = field_singleton_schema( field, by_alias=by_alias, model_name_map=model_name_map, ref_prefix=ref_prefix, known_models=known_models @@ -494,7 +386,7 @@ def field_type_schema( return dict_schema, definitions, nested_models elif field.shape == SHAPE_TUPLE: sub_schema = [] - sub_fields = cast(List[Field], field.sub_fields) + sub_fields = cast(List[ModelField], field.sub_fields) for sf in sub_fields: sf_schema, sf_definitions, sf_nested_models = field_type_schema( sf, by_alias=by_alias, model_name_map=model_name_map, ref_prefix=ref_prefix, known_models=known_models @@ -600,7 +492,7 @@ def model_type_schema( def field_singleton_sub_fields_schema( - sub_fields: Sequence[Field], + sub_fields: Sequence[ModelField], *, by_alias: bool, model_name_map: Dict[Type['BaseModel'], str], @@ -611,7 +503,7 @@ def field_singleton_sub_fields_schema( """ This function is indirectly used by ``field_schema()``, you probably should be using that function. - Take a list of Pydantic ``Field`` from the declaration of a type with parameters, and generate their + Take a list of Pydantic ``ModelField`` from the declaration of a type with parameters, and generate their schema. I.e., fields used as "type parameters", like ``str`` and ``int`` in ``Tuple[str, int]``. """ ref_prefix = ref_prefix or default_prefix @@ -706,7 +598,7 @@ def field_singleton_sub_fields_schema( def field_singleton_schema( # noqa: C901 (ignore complexity) - field: Field, + field: ModelField, *, by_alias: bool, model_name_map: Dict[Type['BaseModel'], str], @@ -717,7 +609,7 @@ def field_singleton_schema( # noqa: C901 (ignore complexity) """ This function is indirectly used by ``field_schema()``, you should probably be using that function. - Take a single Pydantic ``Field``, and return its schema and any additional definitions from sub-models. + Take a single Pydantic ``ModelField``, and return its schema and any additional definitions from sub-models. """ from .main import BaseModel # noqa: F811 @@ -741,7 +633,7 @@ def field_singleton_schema( # noqa: C901 (ignore complexity) if is_callable_type(field.type_): raise SkipField(f'Callable {field.name} was excluded from schema since JSON schema has no equivalent type.') f_schema: Dict[str, Any] = {} - if field.schema is not None and field.schema.const: + if field.field_info is not None and field.field_info.const: f_schema['const'] = field.default field_type = field.type_ if is_new_type(field_type): @@ -811,12 +703,12 @@ def encode_default(dft: Any) -> Any: _map_types_constraint: Dict[Any, Callable[..., type]] = {int: conint, float: confloat, Decimal: condecimal} -def get_annotation_from_schema(annotation: Any, schema: Schema) -> Type[Any]: +def get_annotation_from_field_info(annotation: Any, field_info: FieldInfo) -> Type[Any]: """ - Get an annotation with validation implemented for numbers and strings based on the schema. + Get an annotation with validation implemented for numbers and strings based on the field_info. :param annotation: an annotation from a field specification, as ``str``, ``ConstrainedStr`` - :param schema: an instance of Schema, possibly with declarations for validations and JSON Schema + :param field_info: an instance of FieldInfo, possibly with declarations for validations and JSON Schema :return: the same ``annotation`` if unmodified or a new annotation with validation in place """ if isinstance(annotation, type): @@ -838,7 +730,7 @@ def get_annotation_from_schema(annotation: Any, schema: Schema) -> Type[Any]: if attrs: kwargs = { attr_name: attr - for attr_name, attr in ((attr_name, getattr(schema, attr_name)) for attr_name in attrs) + for attr_name, attr in ((attr_name, getattr(field_info, attr_name)) for attr_name in attrs) if attr is not None } if kwargs: diff --git a/pydantic/types.py b/pydantic/types.py --- a/pydantic/types.py +++ b/pydantic/types.py @@ -74,7 +74,6 @@ OptionalIntFloatDecimal = Union[OptionalIntFloat, Decimal] if TYPE_CHECKING: # pragma: no cover - from .fields import Field from .dataclasses import DataclassType # noqa: F401 from .main import BaseModel, BaseConfig # noqa: F401 from .typing import CallableGenerator @@ -118,7 +117,7 @@ def __get_validators__(cls) -> 'CallableGenerator': yield cls.list_length_validator @classmethod - def list_length_validator(cls, v: 'List[T]', field: 'Field', config: 'BaseConfig') -> 'List[T]': + def list_length_validator(cls, v: 'List[T]') -> 'List[T]': v_len = len(v) if cls.min_items is not None and v_len < cls.min_items: diff --git a/pydantic/typing.py b/pydantic/typing.py --- a/pydantic/typing.py +++ b/pydantic/typing.py @@ -53,7 +53,7 @@ def evaluate_forwardref(type_, globalns, localns): # type: ignore if TYPE_CHECKING: # pragma: no cover - from .fields import Field + from .fields import ModelField TupleGenerator = Generator[Tuple[str, Any], None, None] DictStrAny = Dict[str, Any] @@ -183,9 +183,9 @@ def is_classvar(ann_type: AnyType) -> bool: return _check_classvar(ann_type) or _check_classvar(getattr(ann_type, '__origin__', None)) -def update_field_forward_refs(field: 'Field', globalns: Any, localns: Any) -> None: +def update_field_forward_refs(field: 'ModelField', globalns: Any, localns: Any) -> None: """ - Try to update ForwardRefs on fields based on this Field, globalns and localns. + Try to update ForwardRefs on fields based on this ModelField, globalns and localns. """ if type(field.type_) == ForwardRef: field.type_ = evaluate_forwardref(field.type_, globalns, localns or None) diff --git a/pydantic/validators.py b/pydantic/validators.py --- a/pydantic/validators.py +++ b/pydantic/validators.py @@ -30,7 +30,7 @@ from .utils import almost_equal_floats, lenient_issubclass, sequence_like if TYPE_CHECKING: # pragma: no cover - from .fields import Field + from .fields import ModelField from .main import BaseConfig from .types import ConstrainedDecimal, ConstrainedFloat, ConstrainedInt @@ -127,7 +127,7 @@ def strict_float_validator(v: Any) -> float: raise errors.FloatError() -def number_multiple_validator(v: 'Number', field: 'Field') -> 'Number': +def number_multiple_validator(v: 'Number', field: 'ModelField') -> 'Number': field_type: ConstrainedNumber = field.type_ # type: ignore if field_type.multiple_of is not None: mod = float(v) / float(field_type.multiple_of) % 1 @@ -136,7 +136,7 @@ def number_multiple_validator(v: 'Number', field: 'Field') -> 'Number': return v -def number_size_validator(v: 'Number', field: 'Field') -> 'Number': +def number_size_validator(v: 'Number', field: 'ModelField') -> 'Number': field_type: ConstrainedNumber = field.type_ # type: ignore if field_type.gt is not None and not v > field_type.gt: raise errors.NumberNotGtError(limit_value=field_type.gt) @@ -151,7 +151,7 @@ def number_size_validator(v: 'Number', field: 'Field') -> 'Number': return v -def constant_validator(v: 'Any', field: 'Field') -> 'Any': +def constant_validator(v: 'Any', field: 'ModelField') -> 'Any': """Validate ``const`` fields. The value provided for a ``const`` field must be equal to the default value @@ -238,7 +238,7 @@ def frozenset_validator(v: Any) -> FrozenSet[Any]: raise errors.FrozenSetError() -def enum_validator(v: Any, field: 'Field', config: 'BaseConfig') -> Enum: +def enum_validator(v: Any, field: 'ModelField', config: 'BaseConfig') -> Enum: try: enum_v = field.type_(v) except ValueError: @@ -247,7 +247,7 @@ def enum_validator(v: Any, field: 'Field', config: 'BaseConfig') -> Enum: return enum_v.value if config.use_enum_values else enum_v -def uuid_validator(v: Any, field: 'Field') -> UUID: +def uuid_validator(v: Any, field: 'ModelField') -> UUID: try: if isinstance(v, str): v = UUID(v) @@ -401,7 +401,7 @@ def literal_validator(v: Any) -> Any: return literal_validator -def constr_length_validator(v: 'StrBytes', field: 'Field', config: 'BaseConfig') -> 'StrBytes': +def constr_length_validator(v: 'StrBytes', field: 'ModelField', config: 'BaseConfig') -> 'StrBytes': v_len = len(v) min_length = field.type_.min_length or config.min_anystr_length # type: ignore @@ -415,7 +415,7 @@ def constr_length_validator(v: 'StrBytes', field: 'Field', config: 'BaseConfig') return v -def constr_strip_whitespace(v: 'StrBytes', field: 'Field', config: 'BaseConfig') -> 'StrBytes': +def constr_strip_whitespace(v: 'StrBytes', field: 'ModelField', config: 'BaseConfig') -> 'StrBytes': strip_whitespace = field.type_.strip_whitespace or config.anystr_strip_whitespace # type: ignore if strip_whitespace: v = v.strip()
pydantic/pydantic
1d0d98ba19e8603c24b64bb28d469c342b950100
Thanks for tagging me. Yep. I think it makes sense. If we can keep supporting it for a while with a deprecation warning, we should be fine. And thinking about it, it actually makes more sense for it to be `Field`. --- Slightly related, currently `Schema` (soon to be `Field`) is a class. When declaring a Pydantic field with: ```Python a: int = Schema(...) ``` `mypy` complains that `a` should be of type `int` but is being of type `Schema`. One way I'm "hacking" it in FastAPI (for stuff that inherits from `Schema`) is to create a function with a return type annotation of `Any` (while it is returning a `Schema` instance). Then because the return of the function is annotated as `Any`, `mypy` accepts it. I think this is something that could be interesting to have here too, maybe worth considering during this change. In favour of this change too. This seems to align better with dataclass terminology too, https://docs.python.org/3/library/dataclasses.html#dataclasses.field. For consideration: is there a possibility that the similarity would be a bad thing, rather than good? I agree with @jasonkuhrt that using a `field` function would be nice. Being a function that actually returns a class would fix `mypy` errors when using `Schema` (or the next, `Field`), as a function can be typed to return `Any`. In fact, I'm doing something like that in FastAPI. Also, by implementing a `field` function right away we could update the docs and show the new interface to new users, even while `Schema` is not yet renamed to `Field` (and the current `Field` to something else). I wanna take a shot at this. I have some naming questions: * Is it OK a `field` function exposed as the main interface instead of the corresponding class? * Would you prefer another function name? Or a capitalized version (a function `Field`) that simulates the class name, even while it's a function? * What would be an acceptable name for the current `Field` class? --- On the other side, having just a function `field` that returns a `Schema` class would solve the visible naming issue for users, that could be enough, without needing to rename the underlying classes. The drawback is that the internal names would be more difficult for newcomer contributors to the internal code. I think the function should be called `Field`, it should have an alias called `Schema` that also returns a `Field` but also raises a warning. The only question is what do we call the class? It would be confusing to also call it `Field`, how about `FieldInfo`? Please take a shot. I want to work on v1 features once v0.32 is released. Perfect. So, the *current* `Schema` class will be called `FieldInfo`? And how should the *current* `Field` class be called? `FieldAttr`, `FieldObject`, `FieldElement`, `Attr`, (something else). Or should we keep it just `Field`? --- In summary, the next parts will be: * A `Field` *function* that returns a `FieldInfo` *class* instance. * A `Schema` *function* that returns a `FieldInfo` *class* instance and logs a warning. * A `FieldInfo` *class* that will replace the current `Schema` *class*. * A (what?) *class* that will replace the current `Field` *class* (or do we just keep this `Field` *class*)? Looks good, I think current field becomes `Attribute`, we should also rename that file. Correction, `Attribute` is a dumb name since then you would have `model.__fields__: Dict[str, Attribute]` which is confusing. Better to rename what used to be called `Field` as `ModelField`? +1 for `ModelField`, `FieldInfo`, and `Field` function that returns a `FieldInfo` This may be controversial, but the library **attrs** supported typing (before python 3.6) using a type parameter. `Field` could have two positional arguments (type and default) then the `Field` function could actually return the correct type (using a Generic). ```python class Foo(BaseModel): maximum = Field(int, 100) # this would require a different code path class Bar(BaseModel): maximum: int # this would be bad but possible class Foo(BaseModel): maximum: int = Field(str, "100") ``` Would having the type as an arg to the `Field` method provide any additional benefits? I see a variety of approaches to the possible signature of the `Field` function; I've included my breakdown below. (I use `FieldType` to refer to the type of the object actually returned by `Field`.) I'm most in favor of one of the first two approaches, and would be fine with the first one (the current proposal). * Proposed implementation: `def Field(default: Any, **etc) -> Any` * (All pros/cons below are relative to this implementation) * The following overloaded approach (which may require some minor tweaks) ```python @overload def Field(default: T, **etc) -> T: ... @overload def Field(default: None, **etc) -> Any: ... @overload def Field(default: Ellipsis, **etc) -> Any: ... def Field(default: Any, **etc) -> Any: ... ``` * Pro: type-checks default value against the annotated type where possible * Con: Incorrect type hint if you actually want to treat the result as a `FieldType` * Conclusion: currently my favorite alternative to the proposed implementation; depends on whether we might ever want to work with the returned value of the `Field` function as a `FieldType`. * `def Field(type_: Type[T], default: T, **etc) -> T` * Pro: type-checks the default value against the specified type * Con: Incorrect type hint if you actually want to treat the result as a `FieldType` * Con: Requires you to repeat the type if you want to use an annotation. **If you *don't* use an annotation, then the fields may occur out of order, potentially leading to confusing validation errors.** * Conclusion: Given the second con, I would probably prefer the prior approach. * `def Field(type_: Type[T], default: T, **etc) -> Any` * Pro: type-checks the default value against the specified type * Con: Even more so than the previous example, encourages you to drop the annotation to prevent them from getting out of sync (since there is no check they are equal) * Conclusion: given the field-ordering issue described above, I would probably prefer the overload-heavy implementation (despite getting an incorrect type hint for `FieldType`) * Approaches where `FieldType` is generic and `Field` returns a `FieldType[T]` (this is actually what `attrs` does, though the library mechanics are sufficiently different to cause different issues) * E.g.: * `def Field(default: T, **etc) -> FieldType[T]` * `def Field(default: T, type_: Type[T], **etc) -> FieldType[T]` * Pro: provides the type checker with the most accurate information * Con: will cause mypy errors when used to annotate fields in the absence of a mypy plugin; *with* a mypy plugin, this is probably unnecessary anyway. * Conclusion: Probably not even an improvement over the current implementation @skewty do those points change your thinking at all? @dmontagu I hadn't mentally considered "Con: Incorrect type hint if you actually want to treat the result as a FieldType". Thank you. Given the above, I would choose method 1. @skewty for what it’s worth, I’m not sure it’s actually that big of a downside for the following reasons: 1. You can always use the `FieldType` class directly 1. Internally, there is little reason to use the `Field` function anyway 1. Externally, there is little reason to need to interact with the result of `Field` as a `FieldType` anyway 1. Type hinting as Any prevents any type safety benefits anyway, so if `Field` is going to be rarely/never used to produce something interacted with as a `FieldType`, it might make sense to just use `# type: ignore` in the few places you use for that purpose anyway.
diff --git a/tests/mypy/success.py b/tests/mypy/success.py --- a/tests/mypy/success.py +++ b/tests/mypy/success.py @@ -10,6 +10,7 @@ from pydantic import BaseModel, NoneStr from pydantic.dataclasses import dataclass +from pydantic.fields import Field from pydantic.generics import GenericModel @@ -103,3 +104,8 @@ class WrapperModel(GenericModel, Generic[T]): model_instance = WrapperModel[Model](payload=m) model_instance.payload.list_of_ints.append(4) assert model_instance.payload.list_of_ints == [1, 2, 3, 4] + + +class WithField(BaseModel): + age: int + first_name: str = Field('John', const=True) diff --git a/tests/test_edge_cases.py b/tests/test_edge_cases.py --- a/tests/test_edge_cases.py +++ b/tests/test_edge_cases.py @@ -18,6 +18,7 @@ validate_model, validator, ) +from pydantic.fields import Schema def test_str_bytes(): @@ -26,7 +27,7 @@ class Model(BaseModel): m = Model(v='s') assert m.v == 's' - assert '<Field(v type=typing.Union[str, bytes] required)>' == repr(m.fields['v']) + assert '<ModelField(v type=typing.Union[str, bytes] required)>' == repr(m.fields['v']) m = Model(v=b'b') assert m.v == 'b' @@ -323,7 +324,7 @@ class Config: fields = {'a': '_a'} assert Model(_a='different').a == 'different' - assert repr(Model.__fields__['a']) == "<Field(a type=str default='foobar' alias=_a)>" + assert repr(Model.__fields__['a']) == "<ModelField(a type=str default='foobar' alias=_a)>" def test_alias_error(): @@ -661,8 +662,8 @@ class Model(BaseModel): class Config(BaseConfig): @classmethod - def get_field_schema(cls, name): - field_config = super().get_field_schema(name) or {} + def get_field_info(cls, name): + field_config = super().get_field_info(name) or {} if 'alias' not in field_config: field_config['alias'] = re.sub(r'(?:^|_)([a-z])', lambda m: m.group(1).upper(), name) return field_config @@ -673,12 +674,12 @@ def get_field_schema(cls, name): assert v == {'one_thing': 123, 'another_thing': 321} -def test_get_field_schema_inherit(): +def test_get_field_info_inherit(): class ModelOne(BaseModel): class Config(BaseConfig): @classmethod - def get_field_schema(cls, name): - field_config = super().get_field_schema(name) or {} + def get_field_info(cls, name): + field_config = super().get_field_info(name) or {} if 'alias' not in field_config: field_config['alias'] = re.sub(r'_([a-z])', lambda m: m.group(1).upper(), name) return field_config @@ -1006,3 +1007,11 @@ def check_a(cls, v): assert Model().a is None assert Model(a=None).a is None assert Model(a=12).a == 12 + + +def test_scheme_deprecated(): + + with pytest.warns(DeprecationWarning, match='`Schema` is deprecated, use `Field` instead'): + + class Model(BaseModel): + foo: int = Schema(4) diff --git a/tests/test_forward_ref.py b/tests/test_forward_ref.py --- a/tests/test_forward_ref.py +++ b/tests/test_forward_ref.py @@ -257,7 +257,7 @@ def test_self_reference_json_schema(create_module): module = create_module( """ from typing import List -from pydantic import BaseModel, Schema +from pydantic import BaseModel class Account(BaseModel): name: str @@ -294,7 +294,7 @@ def test_self_reference_json_schema_with_future_annotations(create_module): """ from __future__ import annotations from typing import List -from pydantic import BaseModel, Schema +from pydantic import BaseModel class Account(BaseModel): name: str @@ -329,7 +329,7 @@ def test_circular_reference_json_schema(create_module): module = create_module( """ from typing import List -from pydantic import BaseModel, Schema +from pydantic import BaseModel class Owner(BaseModel): account: 'Account' @@ -378,7 +378,7 @@ def test_circular_reference_json_schema_with_future_annotations(create_module): """ from __future__ import annotations from typing import List -from pydantic import BaseModel, Schema +from pydantic import BaseModel class Owner(BaseModel): account: Account diff --git a/tests/test_main.py b/tests/test_main.py --- a/tests/test_main.py +++ b/tests/test_main.py @@ -3,7 +3,7 @@ import pytest -from pydantic import BaseModel, Extra, NoneBytes, NoneStr, Required, Schema, ValidationError, constr +from pydantic import BaseModel, Extra, Field, NoneBytes, NoneStr, Required, ValidationError, constr def test_success(): @@ -40,7 +40,7 @@ def test_ultra_simple_failed(): def test_ultra_simple_repr(): m = UltraSimpleModel(a=10.2) assert repr(m) == '<UltraSimpleModel a=10.2 b=10>' - assert repr(m.fields['a']) == '<Field(a type=float required)>' + assert repr(m.fields['a']) == '<ModelField(a type=float required)>' assert dict(m) == {'a': 10.2, 'b': 10} assert m.dict() == {'a': 10.2, 'b': 10} assert m.json() == '{"a": 10.2, "b": 10}' @@ -366,7 +366,7 @@ class Config: def test_const_validates(): class Model(BaseModel): - a: int = Schema(3, const=True) + a: int = Field(3, const=True) m = Model(a=3) assert m.a == 3 @@ -374,7 +374,7 @@ class Model(BaseModel): def test_const_uses_default(): class Model(BaseModel): - a: int = Schema(3, const=True) + a: int = Field(3, const=True) m = Model() assert m.a == 3 @@ -382,7 +382,7 @@ class Model(BaseModel): def test_const_with_wrong_value(): class Model(BaseModel): - a: int = Schema(3, const=True) + a: int = Field(3, const=True) with pytest.raises(ValidationError) as exc_info: Model(a=4) @@ -402,8 +402,8 @@ class SubModel(BaseModel): b: int class Model(BaseModel): - a: List[SubModel] = Schema([SubModel(b=1), SubModel(b=2), SubModel(b=3)], const=True) - b: List[SubModel] = Schema([{'b': 4}, {'b': 5}, {'b': 6}], const=True) + a: List[SubModel] = Field([SubModel(b=1), SubModel(b=2), SubModel(b=3)], const=True) + b: List[SubModel] = Field([{'b': 4}, {'b': 5}, {'b': 6}], const=True) m = Model() assert m.a == [SubModel(b=1), SubModel(b=2), SubModel(b=3)] @@ -441,8 +441,8 @@ class SubModel(BaseModel): b: int class Model(BaseModel): - a: List[SubModel] = Schema([SubModel(b=1), SubModel(b=2), SubModel(b=3)], const=True) - b: List[SubModel] = Schema([{'b': 4}, {'b': 5}, {'b': 6}], const=True) + a: List[SubModel] = Field([SubModel(b=1), SubModel(b=2), SubModel(b=3)], const=True) + b: List[SubModel] = Field([{'b': 4}, {'b': 5}, {'b': 6}], const=True) with pytest.raises(ValidationError) as exc_info: Model(a=[{'b': 3}, {'b': 1}, {'b': 2}], b=[{'b': 6}, {'b': 5}]) @@ -492,8 +492,8 @@ class SubForm(BaseModel): field: int class Form(BaseModel): - field1: SubForm = Schema({'field': 2}, const=True) - field2: List[SubForm] = Schema([{'field': 2}], const=True) + field1: SubForm = Field({'field': 2}, const=True) + field2: List[SubForm] = Field([{'field': 2}], const=True) with pytest.raises(ValidationError) as exc_info: # Fails @@ -780,8 +780,8 @@ class ModelB(BaseModel): def test_dict_skip_defaults_populated_by_alias(): class MyModel(BaseModel): - a: str = Schema('default', alias='alias_a') - b: str = Schema('default', alias='alias_b') + a: str = Field('default', alias='alias_a') + b: str = Field('default', alias='alias_b') class Config: allow_population_by_alias = True @@ -794,8 +794,8 @@ class Config: def test_dict_skip_defaults_populated_by_alias_with_extra(): class MyModel(BaseModel): - a: str = Schema('default', alias='alias_a') - b: str = Schema('default', alias='alias_b') + a: str = Field('default', alias='alias_a') + b: str = Field('default', alias='alias_b') class Config: extra = 'allow' @@ -821,7 +821,7 @@ class MyModel(BaseModel): def test_dict_with_extra_keys(): class MyModel(BaseModel): - a: str = Schema(None, alias='alias_a') + a: str = Field(None, alias='alias_a') class Config: extra = Extra.allow diff --git a/tests/test_parse.py b/tests/test_parse.py --- a/tests/test_parse.py +++ b/tests/test_parse.py @@ -3,7 +3,7 @@ import pytest -from pydantic import BaseModel, Protocol, Schema, ValidationError +from pydantic import BaseModel, Field, Protocol, ValidationError class Model(BaseModel): @@ -120,11 +120,11 @@ def test_file_pickle_no_ext(tmpdir): def test_const_differentiates_union(): class SubModelA(BaseModel): - key: str = Schema('A', const=True) + key: str = Field('A', const=True) foo: int class SubModelB(BaseModel): - key: str = Schema('B', const=True) + key: str = Field('B', const=True) foo: int class Model(BaseModel): diff --git a/tests/test_schema.py b/tests/test_schema.py --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -11,7 +11,7 @@ import pytest -from pydantic import BaseModel, Extra, Schema, ValidationError, validator +from pydantic import BaseModel, Extra, Field, ValidationError, validator from pydantic.color import Color from pydantic.networks import AnyUrl, EmailStr, IPvAnyAddress, IPvAnyInterface, IPvAnyNetwork, NameEmail, stricturl from pydantic.schema import ( @@ -142,8 +142,8 @@ class Bar(BaseModel): def test_schema_class(): class Model(BaseModel): - foo: int = Schema(4, title='Foo is Great') - bar: str = Schema(..., description='this description of bar') + foo: int = Field(4, title='Foo is Great') + bar: str = Field(..., description='this description of bar') with pytest.raises(ValidationError): Model() @@ -163,14 +163,14 @@ class Model(BaseModel): def test_schema_repr(): - s = Schema(4, title='Foo is Great') - assert repr(s) == "Schema(default: 4, title: 'Foo is Great', extra: {})" - assert str(s) == "Schema(default: 4, title: 'Foo is Great', extra: {})" + s = Field(4, title='Foo is Great') + assert repr(s) == "FieldInfo(default: 4, title: 'Foo is Great', extra: {})" + assert str(s) == "FieldInfo(default: 4, title: 'Foo is Great', extra: {})" def test_schema_class_by_alias(): class Model(BaseModel): - foo: int = Schema(4, alias='foofoo') + foo: int = Field(4, alias='foofoo') assert list(Model.schema()['properties'].keys()) == ['foofoo'] assert list(Model.schema(by_alias=False)['properties'].keys()) == ['foo'] @@ -187,7 +187,7 @@ class SpamEnum(str, Enum): class Model(BaseModel): foo: FooEnum bar: BarEnum - spam: SpamEnum = Schema(None) + spam: SpamEnum = Field(None) assert Model.schema() == { 'type': 'object', @@ -287,7 +287,7 @@ class Model(BaseModel): def test_const_str(): class Model(BaseModel): - a: str = Schema('some string', const=True) + a: str = Field('some string', const=True) assert Model.schema() == { 'title': 'Model', @@ -298,7 +298,7 @@ class Model(BaseModel): def test_const_false(): class Model(BaseModel): - a: str = Schema('some string', const=False) + a: str = Field('some string', const=False) assert Model.schema() == { 'title': 'Model', @@ -1115,7 +1115,7 @@ class UserModel(BaseModel): ) def test_constraints_schema(kwargs, type_, expected_extra): class Foo(BaseModel): - a: type_ = Schema('foo', title='A title', description='A description', **kwargs) + a: type_ = Field('foo', title='A title', description='A description', **kwargs) expected_schema = { 'title': 'Foo', @@ -1142,7 +1142,7 @@ class Foo(BaseModel): ) def test_not_constraints_schema(kwargs, type_, expected): class Foo(BaseModel): - a: type_ = Schema('foo', title='A title', description='A description', **kwargs) + a: type_ = Field('foo', title='A title', description='A description', **kwargs) base_schema = { 'title': 'Foo', @@ -1190,7 +1190,7 @@ class Foo(BaseModel): ) def test_constraints_schema_validation(kwargs, type_, value): class Foo(BaseModel): - a: type_ = Schema('foo', title='A title', description='A description', **kwargs) + a: type_ = Field('foo', title='A title', description='A description', **kwargs) assert Foo(a=value) @@ -1217,7 +1217,7 @@ class Foo(BaseModel): ) def test_constraints_schema_validation_raises(kwargs, type_, value): class Foo(BaseModel): - a: type_ = Schema('foo', title='A title', description='A description', **kwargs) + a: type_ = Field('foo', title='A title', description='A description', **kwargs) with pytest.raises(ValidationError): Foo(a=value) @@ -1225,7 +1225,7 @@ class Foo(BaseModel): def test_schema_kwargs(): class Foo(BaseModel): - a: str = Schema('foo', examples=['bar']) + a: str = Field('foo', examples=['bar']) assert Foo.schema() == { 'title': 'Foo', diff --git a/tests/test_settings.py b/tests/test_settings.py --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -3,7 +3,7 @@ import pytest -from pydantic import BaseModel, BaseSettings, NoneStr, Schema, ValidationError, dataclasses +from pydantic import BaseModel, BaseSettings, Field, NoneStr, ValidationError, dataclasses from pydantic.env_settings import SettingsError @@ -137,7 +137,7 @@ class Config: def test_case_sensitive(monkeypatch): class Settings(BaseSettings): - foo: str = Schema(..., alias='foo') + foo: str = Field(..., alias='foo') class Config: case_sensitive = True
Rename Schema to Field? Currently we have the class `Schema` for when you need to define more stuff on a field than just the type and default. But this is a confusing name since not all it's arguments refer to the schema. It'll get more confusing if we want to add more arguments to `Schema/Field`, eg. a more complex alias system #477. Therefore we should rename it to `Field`. This would require: * renaming the current `Field` class, perhaps renaming the entire `fields.py` module. * `Schema` needs to carry on working for a while but with a deprecation warning What does everyone thing? @tiangolo `Schema` was your work originally, are you ok with this?
0.0
1d0d98ba19e8603c24b64bb28d469c342b950100
[ "tests/test_edge_cases.py::test_str_bytes", "tests/test_edge_cases.py::test_str_bytes_none", "tests/test_edge_cases.py::test_union_int_str", "tests/test_edge_cases.py::test_union_priority", "tests/test_edge_cases.py::test_typed_list", "tests/test_edge_cases.py::test_typed_set", "tests/test_edge_cases.py::test_dict_dict", "tests/test_edge_cases.py::test_typed_dict[value0-result0]", "tests/test_edge_cases.py::test_typed_dict[value1-result1]", "tests/test_edge_cases.py::test_typed_dict[value2-result2]", "tests/test_edge_cases.py::test_typed_dict_error[1-errors0]", "tests/test_edge_cases.py::test_typed_dict_error[value1-errors1]", "tests/test_edge_cases.py::test_typed_dict_error[value2-errors2]", "tests/test_edge_cases.py::test_dict_key_error", "tests/test_edge_cases.py::test_tuple", "tests/test_edge_cases.py::test_tuple_more", "tests/test_edge_cases.py::test_tuple_length_error", "tests/test_edge_cases.py::test_tuple_invalid", "tests/test_edge_cases.py::test_tuple_value_error", "tests/test_edge_cases.py::test_recursive_list", "tests/test_edge_cases.py::test_recursive_list_error", "tests/test_edge_cases.py::test_list_unions", "tests/test_edge_cases.py::test_recursive_lists", "tests/test_edge_cases.py::test_str_enum", "tests/test_edge_cases.py::test_any_dict", "tests/test_edge_cases.py::test_infer_alias", "tests/test_edge_cases.py::test_alias_error", "tests/test_edge_cases.py::test_annotation_config", "tests/test_edge_cases.py::test_success_values_include", "tests/test_edge_cases.py::test_include_exclude_default", "tests/test_edge_cases.py::test_advanced_exclude", "tests/test_edge_cases.py::test_advanced_value_inclide", "tests/test_edge_cases.py::test_advanced_value_exclude_include", "tests/test_edge_cases.py::test_field_set_ignore_extra", "tests/test_edge_cases.py::test_field_set_allow_extra", "tests/test_edge_cases.py::test_field_set_field_name", "tests/test_edge_cases.py::test_values_order", "tests/test_edge_cases.py::test_inheritance", "tests/test_edge_cases.py::test_invalid_type", "tests/test_edge_cases.py::test_valid_string_types[a", "tests/test_edge_cases.py::test_valid_string_types[some", "tests/test_edge_cases.py::test_valid_string_types[value2-foobar]", "tests/test_edge_cases.py::test_valid_string_types[123-123]", "tests/test_edge_cases.py::test_valid_string_types[123.45-123.45]", "tests/test_edge_cases.py::test_valid_string_types[value5-12.45]", "tests/test_edge_cases.py::test_valid_string_types[True-True]", "tests/test_edge_cases.py::test_valid_string_types[False-False]", "tests/test_edge_cases.py::test_valid_string_types[a10-a10]", "tests/test_edge_cases.py::test_valid_string_types[whatever-whatever]", "tests/test_edge_cases.py::test_invalid_string_types[value0-errors0]", "tests/test_edge_cases.py::test_invalid_string_types[value1-errors1]", "tests/test_edge_cases.py::test_inheritance_config", "tests/test_edge_cases.py::test_partial_inheritance_config", "tests/test_edge_cases.py::test_annotation_inheritance", "tests/test_edge_cases.py::test_string_none", "tests/test_edge_cases.py::test_alias_camel_case", "tests/test_edge_cases.py::test_get_field_info_inherit", "tests/test_edge_cases.py::test_return_errors_ok", "tests/test_edge_cases.py::test_return_errors_error", "tests/test_edge_cases.py::test_optional_required", "tests/test_edge_cases.py::test_invalid_validator", "tests/test_edge_cases.py::test_unable_to_infer", "tests/test_edge_cases.py::test_multiple_errors", "tests/test_edge_cases.py::test_pop_by_alias", "tests/test_edge_cases.py::test_validate_all", "tests/test_edge_cases.py::test_force_extra", "tests/test_edge_cases.py::test_illegal_extra_value", "tests/test_edge_cases.py::test_multiple_inheritance_config", "tests/test_edge_cases.py::test_submodel_different_type", "tests/test_edge_cases.py::test_self", "tests/test_edge_cases.py::test_self_recursive[BaseModel]", "tests/test_edge_cases.py::test_self_recursive[BaseSettings]", "tests/test_edge_cases.py::test_nested_init[BaseModel]", "tests/test_edge_cases.py::test_nested_init[BaseSettings]", "tests/test_edge_cases.py::test_values_attr_deprecation", "tests/test_edge_cases.py::test_init_inspection", "tests/test_edge_cases.py::test_ignored_type", "tests/test_edge_cases.py::test_optional_subfields", "tests/test_edge_cases.py::test_not_optional_subfields", "tests/test_edge_cases.py::test_scheme_deprecated", "tests/test_forward_ref.py::test_postponed_annotations", "tests/test_forward_ref.py::test_postponed_annotations_optional", "tests/test_forward_ref.py::test_basic_forward_ref", "tests/test_forward_ref.py::test_missing_update_forward_refs", "tests/test_forward_ref.py::test_forward_ref_dataclass", "tests/test_forward_ref.py::test_forward_ref_dataclass_with_future_annotations", "tests/test_main.py::test_success", "tests/test_main.py::test_ultra_simple_missing", "tests/test_main.py::test_ultra_simple_failed", "tests/test_main.py::test_ultra_simple_repr", "tests/test_main.py::test_str_truncate", "tests/test_main.py::test_comparing", "tests/test_main.py::test_nullable_strings_success", "tests/test_main.py::test_nullable_strings_fails", "tests/test_main.py::test_recursion", "tests/test_main.py::test_recursion_fails", "tests/test_main.py::test_not_required", "tests/test_main.py::test_infer_type", "tests/test_main.py::test_allow_extra", "tests/test_main.py::test_forbidden_extra_success", "tests/test_main.py::test_forbidden_extra_fails", "tests/test_main.py::test_disallow_mutation", "tests/test_main.py::test_extra_allowed", "tests/test_main.py::test_extra_ignored", "tests/test_main.py::test_set_attr", "tests/test_main.py::test_set_attr_invalid", "tests/test_main.py::test_any", "tests/test_main.py::test_alias", "tests/test_main.py::test_population_by_alias", "tests/test_main.py::test_field_order", "tests/test_main.py::test_required", "tests/test_main.py::test_not_immutability", "tests/test_main.py::test_immutability", "tests/test_main.py::test_const_validates", "tests/test_main.py::test_const_uses_default", "tests/test_main.py::test_const_with_wrong_value", "tests/test_main.py::test_const_list", "tests/test_main.py::test_const_list_with_wrong_value", "tests/test_main.py::test_const_validation_json_serializable", "tests/test_main.py::test_validating_assignment_pass", "tests/test_main.py::test_validating_assignment_fail", "tests/test_main.py::test_enum_values", "tests/test_main.py::test_enum_raw", "tests/test_main.py::test_set_tuple_values", "tests/test_main.py::test_default_copy", "tests/test_main.py::test_arbitrary_type_allowed_validation_success", "tests/test_main.py::test_arbitrary_type_allowed_validation_fails", "tests/test_main.py::test_arbitrary_types_not_allowed", "tests/test_main.py::test_type_type_validation_success", "tests/test_main.py::test_type_type_subclass_validation_success", "tests/test_main.py::test_type_type_validation_fails_for_instance", "tests/test_main.py::test_type_type_validation_fails_for_basic_type", "tests/test_main.py::test_annotation_field_name_shadows_attribute", "tests/test_main.py::test_value_field_name_shadows_attribute", "tests/test_main.py::test_class_var", "tests/test_main.py::test_fields_set", "tests/test_main.py::test_skip_defaults_dict", "tests/test_main.py::test_skip_defaults_recursive", "tests/test_main.py::test_dict_skip_defaults_populated_by_alias", "tests/test_main.py::test_dict_skip_defaults_populated_by_alias_with_extra", "tests/test_main.py::test_dir_fields", "tests/test_main.py::test_dict_with_extra_keys", "tests/test_main.py::test_alias_generator", "tests/test_main.py::test_alias_generator_with_field_schema", "tests/test_main.py::test_alias_generator_wrong_type_error", "tests/test_main.py::test_root", "tests/test_main.py::test_root_list", "tests/test_main.py::test_root_failed", "tests/test_main.py::test_root_undefined_failed", "tests/test_main.py::test_parse_root_as_mapping", "tests/test_main.py::test_untouched_types", "tests/test_main.py::test_custom_types_fail_without_keep_untouched", "tests/test_main.py::test_model_iteration", "tests/test_parse.py::test_obj", "tests/test_parse.py::test_parse_obj_fails", "tests/test_parse.py::test_parse_obj_submodel", "tests/test_parse.py::test_parse_obj_wrong_model", "tests/test_parse.py::test_parse_obj_root", "tests/test_parse.py::test_parse_root_list", "tests/test_parse.py::test_json", "tests/test_parse.py::test_json_ct", "tests/test_parse.py::test_pickle_ct", "tests/test_parse.py::test_pickle_proto", "tests/test_parse.py::test_pickle_not_allowed", "tests/test_parse.py::test_bad_ct", "tests/test_parse.py::test_bad_proto", "tests/test_parse.py::test_file_json", "tests/test_parse.py::test_file_json_no_ext", "tests/test_parse.py::test_file_pickle", "tests/test_parse.py::test_file_pickle_no_ext", "tests/test_parse.py::test_const_differentiates_union", "tests/test_schema.py::test_key", "tests/test_schema.py::test_by_alias", "tests/test_schema.py::test_sub_model", "tests/test_schema.py::test_schema_class", "tests/test_schema.py::test_schema_repr", "tests/test_schema.py::test_schema_class_by_alias", "tests/test_schema.py::test_choices", "tests/test_schema.py::test_json_schema", "tests/test_schema.py::test_list_sub_model", "tests/test_schema.py::test_optional", "tests/test_schema.py::test_any", "tests/test_schema.py::test_set", "tests/test_schema.py::test_const_str", "tests/test_schema.py::test_const_false", "tests/test_schema.py::test_tuple[tuple-expected_schema0]", "tests/test_schema.py::test_tuple[field_type1-expected_schema1]", "tests/test_schema.py::test_tuple[field_type2-expected_schema2]", "tests/test_schema.py::test_bool", "tests/test_schema.py::test_strict_bool", "tests/test_schema.py::test_dict", "tests/test_schema.py::test_list", "tests/test_schema.py::test_list_union_dict[field_type0-expected_schema0]", "tests/test_schema.py::test_list_union_dict[field_type1-expected_schema1]", "tests/test_schema.py::test_list_union_dict[field_type2-expected_schema2]", "tests/test_schema.py::test_list_union_dict[field_type3-expected_schema3]", "tests/test_schema.py::test_list_union_dict[field_type4-expected_schema4]", "tests/test_schema.py::test_date_types[datetime-expected_schema0]", "tests/test_schema.py::test_date_types[date-expected_schema1]", "tests/test_schema.py::test_date_types[time-expected_schema2]", "tests/test_schema.py::test_date_types[timedelta-expected_schema3]", "tests/test_schema.py::test_str_basic_types[field_type0-expected_schema0]", "tests/test_schema.py::test_str_basic_types[field_type1-expected_schema1]", "tests/test_schema.py::test_str_basic_types[field_type2-expected_schema2]", "tests/test_schema.py::test_str_basic_types[field_type3-expected_schema3]", "tests/test_schema.py::test_str_constrained_types[StrictStr-expected_schema0]", "tests/test_schema.py::test_str_constrained_types[ConstrainedStr-expected_schema1]", "tests/test_schema.py::test_str_constrained_types[ConstrainedStrValue-expected_schema2]", "tests/test_schema.py::test_special_str_types[AnyUrl-expected_schema0]", "tests/test_schema.py::test_special_str_types[UrlValue-expected_schema1]", "tests/test_schema.py::test_email_str_types[EmailStr-email]", "tests/test_schema.py::test_email_str_types[NameEmail-name-email]", "tests/test_schema.py::test_secret_types[SecretBytes-string]", "tests/test_schema.py::test_secret_types[SecretStr-string]", "tests/test_schema.py::test_special_int_types[ConstrainedInt-expected_schema0]", "tests/test_schema.py::test_special_int_types[ConstrainedIntValue-expected_schema1]", "tests/test_schema.py::test_special_int_types[ConstrainedIntValue-expected_schema2]", "tests/test_schema.py::test_special_int_types[ConstrainedIntValue-expected_schema3]", "tests/test_schema.py::test_special_int_types[PositiveInt-expected_schema4]", "tests/test_schema.py::test_special_int_types[NegativeInt-expected_schema5]", "tests/test_schema.py::test_special_float_types[ConstrainedFloat-expected_schema0]", "tests/test_schema.py::test_special_float_types[ConstrainedFloatValue-expected_schema1]", "tests/test_schema.py::test_special_float_types[ConstrainedFloatValue-expected_schema2]", "tests/test_schema.py::test_special_float_types[ConstrainedFloatValue-expected_schema3]", "tests/test_schema.py::test_special_float_types[PositiveFloat-expected_schema4]", "tests/test_schema.py::test_special_float_types[NegativeFloat-expected_schema5]", "tests/test_schema.py::test_special_float_types[ConstrainedDecimal-expected_schema6]", "tests/test_schema.py::test_special_float_types[ConstrainedDecimalValue-expected_schema7]", "tests/test_schema.py::test_special_float_types[ConstrainedDecimalValue-expected_schema8]", "tests/test_schema.py::test_special_float_types[ConstrainedDecimalValue-expected_schema9]", "tests/test_schema.py::test_uuid_types[UUID-uuid]", "tests/test_schema.py::test_uuid_types[UUID1-uuid1]", "tests/test_schema.py::test_uuid_types[UUID3-uuid3]", "tests/test_schema.py::test_uuid_types[UUID4-uuid4]", "tests/test_schema.py::test_uuid_types[UUID5-uuid5]", "tests/test_schema.py::test_path_types[FilePath-file-path]", "tests/test_schema.py::test_path_types[DirectoryPath-directory-path]", "tests/test_schema.py::test_path_types[Path-path]", "tests/test_schema.py::test_json_type", "tests/test_schema.py::test_ipv4address_type", "tests/test_schema.py::test_ipv6address_type", "tests/test_schema.py::test_ipvanyaddress_type", "tests/test_schema.py::test_ipv4interface_type", "tests/test_schema.py::test_ipv6interface_type", "tests/test_schema.py::test_ipvanyinterface_type", "tests/test_schema.py::test_ipv4network_type", "tests/test_schema.py::test_ipv6network_type", "tests/test_schema.py::test_ipvanynetwork_type", "tests/test_schema.py::test_callable_type[annotation0]", "tests/test_schema.py::test_callable_type[annotation1]", "tests/test_schema.py::test_error_non_supported_types", "tests/test_schema.py::test_flat_models_unique_models", "tests/test_schema.py::test_flat_models_with_submodels", "tests/test_schema.py::test_flat_models_with_submodels_from_sequence", "tests/test_schema.py::test_model_name_maps", "tests/test_schema.py::test_schema_overrides", "tests/test_schema.py::test_schema_from_models", "tests/test_schema.py::test_schema_with_ref_prefix", "tests/test_schema.py::test_schema_no_definitions", "tests/test_schema.py::test_list_default", "tests/test_schema.py::test_dict_default", "tests/test_schema.py::test_constraints_schema[kwargs0-str-expected_extra0]", "tests/test_schema.py::test_constraints_schema[kwargs1-ConstrainedStrValue-expected_extra1]", "tests/test_schema.py::test_constraints_schema[kwargs2-str-expected_extra2]", "tests/test_schema.py::test_constraints_schema[kwargs3-bytes-expected_extra3]", "tests/test_schema.py::test_constraints_schema[kwargs4-str-expected_extra4]", "tests/test_schema.py::test_constraints_schema[kwargs5-int-expected_extra5]", "tests/test_schema.py::test_constraints_schema[kwargs6-int-expected_extra6]", "tests/test_schema.py::test_constraints_schema[kwargs7-int-expected_extra7]", "tests/test_schema.py::test_constraints_schema[kwargs8-int-expected_extra8]", "tests/test_schema.py::test_constraints_schema[kwargs9-int-expected_extra9]", "tests/test_schema.py::test_constraints_schema[kwargs10-float-expected_extra10]", "tests/test_schema.py::test_constraints_schema[kwargs11-float-expected_extra11]", "tests/test_schema.py::test_constraints_schema[kwargs12-float-expected_extra12]", "tests/test_schema.py::test_constraints_schema[kwargs13-float-expected_extra13]", "tests/test_schema.py::test_constraints_schema[kwargs14-float-expected_extra14]", "tests/test_schema.py::test_constraints_schema[kwargs15-Decimal-expected_extra15]", "tests/test_schema.py::test_constraints_schema[kwargs16-Decimal-expected_extra16]", "tests/test_schema.py::test_constraints_schema[kwargs17-Decimal-expected_extra17]", "tests/test_schema.py::test_constraints_schema[kwargs18-Decimal-expected_extra18]", "tests/test_schema.py::test_constraints_schema[kwargs19-Decimal-expected_extra19]", "tests/test_schema.py::test_not_constraints_schema[kwargs0-int-expected0]", "tests/test_schema.py::test_not_constraints_schema[kwargs1-float-expected1]", "tests/test_schema.py::test_not_constraints_schema[kwargs2-Decimal-expected2]", "tests/test_schema.py::test_not_constraints_schema[kwargs3-int-expected3]", "tests/test_schema.py::test_not_constraints_schema[kwargs4-str-expected4]", "tests/test_schema.py::test_not_constraints_schema[kwargs5-bytes-expected5]", "tests/test_schema.py::test_not_constraints_schema[kwargs6-str-expected6]", "tests/test_schema.py::test_not_constraints_schema[kwargs7-bool-expected7]", "tests/test_schema.py::test_constraints_schema_validation[kwargs0-str-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs1-ConstrainedStrValue-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs2-str-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs3-bytes-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs4-str-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs5-bool-True]", "tests/test_schema.py::test_constraints_schema_validation[kwargs6-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs7-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs8-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs9-int-2]", "tests/test_schema.py::test_constraints_schema_validation[kwargs10-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs11-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs12-int-5]", "tests/test_schema.py::test_constraints_schema_validation[kwargs13-float-3.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs14-float-2.1]", "tests/test_schema.py::test_constraints_schema_validation[kwargs15-float-3.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs16-float-4.9]", "tests/test_schema.py::test_constraints_schema_validation[kwargs17-float-3.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs18-float-2.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs19-float-3.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs20-float-5.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs21-float-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs22-float-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs23-Decimal-value23]", "tests/test_schema.py::test_constraints_schema_validation[kwargs24-Decimal-value24]", "tests/test_schema.py::test_constraints_schema_validation[kwargs25-Decimal-value25]", "tests/test_schema.py::test_constraints_schema_validation[kwargs26-Decimal-value26]", "tests/test_schema.py::test_constraints_schema_validation[kwargs27-Decimal-value27]", "tests/test_schema.py::test_constraints_schema_validation[kwargs28-Decimal-value28]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs0-str-foobar]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs1-str-f]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs2-str-bar]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs3-int-2]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs4-int-5]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs5-int-1]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs6-int-6]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs7-float-2.0]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs8-float-5.0]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs9-float-1.9]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs10-float-5.1]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs11-Decimal-value11]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs12-Decimal-value12]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs13-Decimal-value13]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs14-Decimal-value14]", "tests/test_schema.py::test_schema_kwargs", "tests/test_schema.py::test_schema_dict_constr", "tests/test_schema.py::test_bytes_constrained_types[ConstrainedBytes-expected_schema0]", "tests/test_schema.py::test_bytes_constrained_types[ConstrainedBytesValue-expected_schema1]", "tests/test_schema.py::test_optional_dict", "tests/test_schema.py::test_optional_validator", "tests/test_schema.py::test_field_with_validator", "tests/test_schema.py::test_known_model_optimization", "tests/test_schema.py::test_root", "tests/test_schema.py::test_root_list", "tests/test_schema.py::test_root_nested_model", "tests/test_schema.py::test_new_type_schema", "tests/test_schema.py::test_literal_schema", "tests/test_schema.py::test_color_type", "tests/test_schema.py::test_model_with_schema_extra", "tests/test_schema.py::test_model_with_extra_forbidden", "tests/test_settings.py::test_sub_env", "tests/test_settings.py::test_sub_env_override", "tests/test_settings.py::test_sub_env_missing", "tests/test_settings.py::test_other_setting", "tests/test_settings.py::test_env_with_aliass", "tests/test_settings.py::test_list", "tests/test_settings.py::test_set_dict_model", "tests/test_settings.py::test_invalid_json", "tests/test_settings.py::test_required_sub_model", "tests/test_settings.py::test_non_class", "tests/test_settings.py::test_alias_matches_name", "tests/test_settings.py::test_case_insensitive", "tests/test_settings.py::test_case_sensitive", "tests/test_settings.py::test_nested_dataclass", "tests/test_settings.py::test_config_file_settings", "tests/test_settings.py::test_config_file_settings_nornir" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2019-09-20 14:35:37+00:00
mit
4,911
pydantic__pydantic-847
diff --git a/docs/examples/settings.py b/docs/examples/settings.py --- a/docs/examples/settings.py +++ b/docs/examples/settings.py @@ -1,44 +1,57 @@ from typing import Set -from pydantic import BaseModel, DSN, BaseSettings, PyObject - +from devtools import debug +from pydantic import BaseModel, BaseSettings, PyObject, RedisDsn, PostgresDsn, Field class SubModel(BaseModel): foo = 'bar' apple = 1 - class Settings(BaseSettings): - redis_host = 'localhost' - redis_port = 6379 - redis_database = 0 - redis_password: str = None + auth_key: str + api_key: str = Field(..., env='my_api_key') - auth_key: str = ... + redis_dsn: RedisDsn = 'redis://user:pass@localhost:6379/1' + pg_dsn: PostgresDsn = 'postgres://user:pass@localhost:5432/foobar' - invoicing_cls: PyObject = 'path.to.Invoice' - - db_name = 'foobar' - db_user = 'postgres' - db_password: str = None - db_host = 'localhost' - db_port = '5432' - db_driver = 'postgres' - db_query: dict = None - dsn: DSN = None + special_function: PyObject = 'math.cos' # to override domains: - # export MY_PREFIX_DOMAINS = '["foo.com", "bar.com"]' + # export my_prefix_domains='["foo.com", "bar.com"]' domains: Set[str] = set() # to override more_settings: - # export MY_PREFIX_MORE_SETTINGS = '{"foo": "x", "apple": 1}' + # export my_prefix_more_settings='{"foo": "x", "apple": 1}' more_settings: SubModel = SubModel() class Config: - env_prefix = 'MY_PREFIX_' # defaults to 'APP_' + env_prefix = 'my_prefix_' # defaults to no prefix, e.g. "" fields = { 'auth_key': { - 'alias': 'my_api_key' + 'env': 'my_auth_key', + }, + 'redis_dsn': { + 'env': ['service_redis_dsn', 'redis_url'] } } + +""" +When calling with +my_auth_key=a \ +MY_API_KEY=b \ +my_prefix_domains='["foo.com", "bar.com"]' \ +python docs/examples/settings.py +""" +debug(Settings().dict()) +""" +docs/examples/settings.py:45 <module> + Settings().dict(): { + 'auth_key': 'a', + 'api_key': 'b', + 'redis_dsn': <RedisDsn('redis://user:pass@localhost:6379/1' scheme='redis' ...)>, + 'pg_dsn': <PostgresDsn('postgres://user:pass@localhost:5432/foobar' scheme='postgres' ...)>, + 'special_function': <built-in function cos>, + 'domains': {'bar.com', 'foo.com'}, + 'more_settings': {'foo': 'bar', 'apple': 1}, + } (dict) len=7 +""" diff --git a/pydantic/env_settings.py b/pydantic/env_settings.py --- a/pydantic/env_settings.py +++ b/pydantic/env_settings.py @@ -1,7 +1,10 @@ import os -from typing import Any, Dict, Optional, cast +import warnings +from typing import Any, Dict, Iterable, Mapping, Optional +from .fields import ModelField from .main import BaseModel, Extra +from .typing import display_as_type class SettingsError(ValueError): @@ -30,26 +33,26 @@ def _build_environ(self) -> Dict[str, Optional[str]]: d: Dict[str, Optional[str]] = {} if self.__config__.case_sensitive: - env_vars = cast(Dict[str, str], os.environ) + env_vars: Mapping[str, str] = os.environ else: env_vars = {k.lower(): v for k, v in os.environ.items()} for field in self.__fields__.values(): - if field.has_alias: - env_name = field.alias - else: - env_name = self.__config__.env_prefix + field.name.upper() - - env_name_ = env_name if self.__config__.case_sensitive else env_name.lower() - env_val = env_vars.get(env_name_, None) - - if env_val: - if field.is_complex(): - try: - env_val = self.__config__.json_loads(env_val) # type: ignore - except ValueError as e: - raise SettingsError(f'error parsing JSON for "{env_name}"') from e - d[field.alias] = env_val + env_val: Optional[str] = None + for env_name in field.field_info.extra['env_names']: # type: ignore + env_val = env_vars.get(env_name) + if env_val is not None: + break + + if env_val is None: + continue + + if field.is_complex(): + try: + env_val = self.__config__.json_loads(env_val) # type: ignore + except ValueError as e: + raise SettingsError(f'error parsing JSON for "{env_name}"') from e + d[field.alias] = env_val return d class Config: @@ -59,4 +62,30 @@ class Config: arbitrary_types_allowed = True case_sensitive = False + @classmethod + def prepare_field(cls, field: ModelField) -> None: + if not field.field_info: + return + + env_names: Iterable[str] + env = field.field_info.extra.pop('env', None) + if env is None: + if field.has_alias: + warnings.warn( + 'aliases are no longer used by BaseSettings to define which environment variables to read. ' + 'Instead use the "env" field setting. See https://pydantic-docs.helpmanual.io/#settings', + DeprecationWarning, + ) + env_names = [cls.env_prefix + field.name] + elif isinstance(env, str): + env_names = {env} + elif isinstance(env, (list, set, tuple)): + env_names = env + else: + raise TypeError(f'invalid field env: {env!r} ({display_as_type(env)}); should be string, list or set') + + if not cls.case_sensitive: + env_names = type(env_names)(n.lower() for n in env_names) + field.field_info.extra['env_names'] = env_names + __config__: Config # type: ignore diff --git a/pydantic/fields.py b/pydantic/fields.py --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -229,6 +229,7 @@ def __init__( self.post_validators: Optional['ValidatorsList'] = None self.parse_json: bool = False self.shape: int = SHAPE_SINGLETON + self.model_config.prepare_field(self) self.prepare() @classmethod diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -73,7 +73,7 @@ class BaseConfig: json_encoders: Dict[AnyType, AnyCallable] = {} @classmethod - def get_field_info(cls, name: str) -> Dict[str, str]: + def get_field_info(cls, name: str) -> Dict[str, Any]: field_info = cls.fields.get(name) or {} if isinstance(field_info, str): field_info = {'alias': field_info} @@ -84,6 +84,13 @@ def get_field_info(cls, name: str) -> Dict[str, str]: field_info['alias'] = alias 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') -> 'ConfigType': if not self_config:
pydantic/pydantic
12f4e0d08286c5416c40243d11d3d818b4cdd517
I definitely agree about `case_insensitive`, not so sure about `env_prefix`, but I guess you're probably right. I've got extremely frustrated with aliases in `BaseSettings` a number of times: * they don't work well with inheritance * you very often want to look for more than one alias, eg. [here](https://github.com/samuelcolvin/aiohttp-toolbox/blob/4846214cd9523cc50683ec6b08350412ec13d81b/atoolbox/settings.py#L107) I have redis `'redis_settings': 'REDISCLOUD_URL'` so aiohttp-toolbox works "out of the box" (no pun intended) on heroku with the redis cloud plugin I regularly use, but it's a slightly mad default. It would be much better if I could set multiple env varibles to inspect `{'REDISCLOUD_URL', 'REDIS_URL'}` or whatever. * aliases are weird when initialising normally using arguments (eg. for testing) when you don't want to look for env variables, eg. I'd expect to do `Settings(pg_dsn='postgres://postgres@localhost:5432/test_db')` not have to respect the env var name and do `Settings(DATABASE_URL='postgres://postgres@localhost:5432/test_db')` How do we work around this? I'd therefore like to completely change how environment variables are interpreted in `BaseSettings`: ```py from pydantic import BaseSettings class Settings(BaseSettings): pg_dsn: str = 'postgres://postgres@localhost:5432/app' class Config: fields = {'pg_dsn': {'env': {'DATABASE_URL', 'PG_DSN'}}} # or using Field (#577): class Settings(BaseSettings): pg_dsn: str = Field('postgres://postgres@localhost:5432/app', env={'DATABASE_URL', 'PG_DSN'}) # creating manually for testing (here i can use the raw field name since alias hasn't changed): settings = Settings(pg_dsn='postgres://postgres@localhost:5432/testing') ``` as discussed on #747 `env` would be completely case insensitive. thoughts? > It would be much better if I could set multiple env varibles to inspect {'REDISCLOUD_URL', 'REDIS_URL'} or whatever. +1 In general aliases seem to make more sense to me in the context of `BaseModel` than `BaseSettings`. This proposal seems good to me. I personally prefer the 2nd `Field` method as a developer new to **pydantic** is more likely to notice and use parameters there. The nested `Config` from my experience with my team here is less common and comes as a surprise :tada:. While the usage of `set` for `env` is correct in your example, I also think using a `list` there would be more typical and reduce confusion of it being a `dict`. Are the additional features of `set` being used? Was it chosen simply because items should be unique and because order is not important? Perhaps the ordering offered by a `list` is an important **feature** to some. Yes order of `env` may well be important. Either should work.
diff --git a/tests/test_settings.py b/tests/test_settings.py --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -10,19 +10,15 @@ class SimpleSettings(BaseSettings): apple: str - class Config: - env_prefix = 'APP_' - case_sensitive = True - def test_sub_env(env): - env.set('APP_APPLE', 'hello') + env.set('apple', 'hello') s = SimpleSettings() assert s.apple == 'hello' def test_sub_env_override(env): - env.set('APP_APPLE', 'hello') + env.set('apple', 'hello') s = SimpleSettings(apple='goodbye') assert s.apple == 'goodbye' @@ -33,20 +29,23 @@ def test_sub_env_missing(): assert exc_info.value.errors() == [{'loc': ('apple',), 'msg': 'field required', 'type': 'value_error.missing'}] -def test_other_setting(env): +def test_other_setting(): with pytest.raises(ValidationError): SimpleSettings(apple='a', foobar=42) -def test_env_with_aliass(env): +def test_with_prefix(env): class Settings(BaseSettings): - apple: str = ... + apple: str class Config: - fields = {'apple': 'BOOM'} + env_prefix = 'foobar_' - env.set('BOOM', 'hello') - assert Settings().apple == 'hello' + with pytest.raises(ValidationError): + Settings() + env.set('foobar_apple', 'has_prefix') + s = Settings() + assert s.apple == 'has_prefix' class DateModel(BaseModel): @@ -59,22 +58,18 @@ class ComplexSettings(BaseSettings): carrots: dict = {} date: DateModel = DateModel() - class Config: - env_prefix = 'APP_' - case_sensitive = True - def test_list(env): - env.set('APP_APPLES', '["russet", "granny smith"]') + env.set('apples', '["russet", "granny smith"]') s = ComplexSettings() assert s.apples == ['russet', 'granny smith'] assert s.date.pips is False def test_set_dict_model(env): - env.set('APP_BANANAS', '[1, 2, 3, 3]') - env.set('APP_CARROTS', '{"a": null, "b": 4}') - env.set('APP_DATE', '{"pips": true}') + env.set('bananas', '[1, 2, 3, 3]') + env.set('CARROTS', '{"a": null, "b": 4}') + env.set('daTE', '{"pips": true}') s = ComplexSettings() assert s.bananas == {1, 2, 3} assert s.carrots == {'a': None, 'b': 4} @@ -82,8 +77,8 @@ def test_set_dict_model(env): def test_invalid_json(env): - env.set('APP_APPLES', '["russet", "granny smith",]') - with pytest.raises(SettingsError): + env.set('apples', '["russet", "granny smith",]') + with pytest.raises(SettingsError, match='error parsing JSON for "apples"'): ComplexSettings() @@ -107,37 +102,145 @@ class Settings(BaseSettings): assert s.foobar == 'xxx' -def test_alias_matches_name(env): +def test_env_str(env): + class Settings(BaseSettings): + apple: str = ... + + class Config: + fields = {'apple': {'env': 'BOOM'}} + + env.set('BOOM', 'hello') + assert Settings().apple == 'hello' + + +def test_env_list(env): class Settings(BaseSettings): foobar: str class Config: - fields = {'foobar': 'foobar'} + fields = {'foobar': {'env': ['different1', 'different2']}} - env.set('foobar', 'xxx') + env.set('different1', 'value 1') + env.set('different2', 'value 2') s = Settings() - assert s.foobar == 'xxx' + assert s.foobar == 'value 1' -def test_case_insensitive(env): +def test_env_list_field(env): class Settings(BaseSettings): - foo: str - bAR: str + foobar: str = Field(..., env='foobar_env_name') + + env.set('FOOBAR_ENV_NAME', 'env value') + s = Settings() + assert s.foobar == 'env value' + + +def test_env_list_last(env): + class Settings(BaseSettings): + foobar: str class Config: - env_prefix = 'APP_' - case_sensitive = False + fields = {'foobar': {'env': ['different2']}} - env.set('apP_foO', 'foo') - env.set('app_bar', 'bar') + env.set('different1', 'value 1') + env.set('different2', 'value 2') s = Settings() - assert s.foo == 'foo' - assert s.bAR == 'bar' + assert s.foobar == 'value 2' + assert Settings(foobar='abc').foobar == 'abc' + + +def test_env_inheritance(env): + class SettingsParent(BaseSettings): + foobar: str = 'parent default' + + class Config: + fields = {'foobar': {'env': 'different'}} + + class SettingsChild(SettingsParent): + foobar: str = 'child default' + + assert SettingsParent().foobar == 'parent default' + assert SettingsParent(foobar='abc').foobar == 'abc' + + assert SettingsChild().foobar == 'child default' + assert SettingsChild(foobar='abc').foobar == 'abc' + env.set('different', 'env value') + assert SettingsParent().foobar == 'env value' + assert SettingsParent(foobar='abc').foobar == 'abc' + assert SettingsChild().foobar == 'env value' + assert SettingsChild(foobar='abc').foobar == 'abc' + + +def test_env_inheritance_field(env): + class SettingsParent(BaseSettings): + foobar: str = Field('parent default', env='foobar_env') + + class SettingsChild(SettingsParent): + foobar: str = 'child default' + + assert SettingsParent().foobar == 'parent default' + assert SettingsParent(foobar='abc').foobar == 'abc' + + assert SettingsChild().foobar == 'child default' + assert SettingsChild(foobar='abc').foobar == 'abc' + env.set('foobar_env', 'env value') + assert SettingsParent().foobar == 'env value' + assert SettingsParent(foobar='abc').foobar == 'abc' + assert SettingsChild().foobar == 'child default' + assert SettingsChild(foobar='abc').foobar == 'abc' + + +def test_env_invalid(env): + with pytest.raises(TypeError, match=r'invalid field env: 123 \(int\); should be string, list or set'): + + class Settings(BaseSettings): + foobar: str + + class Config: + fields = {'foobar': {'env': 123}} + + +def test_env_field(env): + with pytest.raises(TypeError, match=r'invalid field env: 123 \(int\); should be string, list or set'): + + class Settings(BaseSettings): + foobar: str = Field(..., env=123) + + +def test_aliases_warning(env): + with pytest.warns(DeprecationWarning, match='aliases are no longer used by BaseSettings'): + + class Settings(BaseSettings): + foobar: str = 'default value' + + class Config: + fields = {'foobar': 'foobar_alias'} + + assert Settings().foobar == 'default value' + env.set('foobar_alias', 'xxx') + assert Settings().foobar == 'default value' + assert Settings(foobar_alias='42').foobar == '42' + + +def test_aliases_no_warning(env): + class Settings(BaseSettings): + foobar: str = 'default value' + + class Config: + fields = {'foobar': {'alias': 'foobar_alias', 'env': 'foobar_env'}} + + assert Settings().foobar == 'default value' + assert Settings(foobar_alias='42').foobar == '42' + env.set('foobar_alias', 'xxx') + assert Settings().foobar == 'default value' + env.set('foobar_env', 'xxx') + assert Settings().foobar == 'xxx' + assert Settings(foobar_alias='42').foobar == '42' def test_case_sensitive(monkeypatch): class Settings(BaseSettings): - foo: str = Field(..., alias='foo') + foo: str class Config: case_sensitive = True @@ -165,7 +268,7 @@ class Settings(BaseSettings): assert s.n.bar == 'bar value' -def test_config_file_settings(env): +def test_env_takes_precedence(env): class Settings(BaseSettings): foo: int bar: str
Change BaseSettings defaults > So, to do before version 1: I would like to see these two BaseSettings Config fields default to the following: ```py class Settings(BaseSettings): class Config: env_prefix = "" case_insensitive = True ``` _Originally posted by @jasonkuhrt in https://github.com/samuelcolvin/pydantic/issues/576#issuecomment-518889641_
0.0
12f4e0d08286c5416c40243d11d3d818b4cdd517
[ "tests/test_settings.py::test_invalid_json", "tests/test_settings.py::test_env_str", "tests/test_settings.py::test_env_list", "tests/test_settings.py::test_env_list_field", "tests/test_settings.py::test_env_list_last", "tests/test_settings.py::test_env_inheritance", "tests/test_settings.py::test_env_inheritance_field", "tests/test_settings.py::test_env_invalid", "tests/test_settings.py::test_env_field", "tests/test_settings.py::test_aliases_warning", "tests/test_settings.py::test_aliases_no_warning" ]
[ "tests/test_settings.py::test_sub_env", "tests/test_settings.py::test_sub_env_override", "tests/test_settings.py::test_sub_env_missing", "tests/test_settings.py::test_other_setting", "tests/test_settings.py::test_with_prefix", "tests/test_settings.py::test_list", "tests/test_settings.py::test_set_dict_model", "tests/test_settings.py::test_required_sub_model", "tests/test_settings.py::test_non_class", "tests/test_settings.py::test_case_sensitive", "tests/test_settings.py::test_nested_dataclass", "tests/test_settings.py::test_env_takes_precedence", "tests/test_settings.py::test_config_file_settings_nornir" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2019-10-01 12:42:20+00:00
mit
4,912
pydantic__pydantic-860
diff --git a/docs/examples/generics-naming.py b/docs/examples/generics-naming.py new file mode 100644 --- /dev/null +++ b/docs/examples/generics-naming.py @@ -0,0 +1,17 @@ +from typing import Generic, TypeVar, Type, Any, Tuple + +from pydantic.generics import GenericModel + +DataT = TypeVar('DataT') + +class Response(GenericModel, Generic[DataT]): + data: DataT + + @classmethod + def __concrete_name__(cls: Type[Any], params: Tuple[Type[Any], ...]) -> str: + return f'{params[0].__name__.title()}Response' + +print(Response[int](data=1)) +# IntResponse data=1 +print(Response[str](data='a')) +# StrResponse data='a' diff --git a/pydantic/generics.py b/pydantic/generics.py --- a/pydantic/generics.py +++ b/pydantic/generics.py @@ -40,7 +40,7 @@ def __class_getitem__( # type: ignore k: resolve_type_hint(v, typevars_map) for k, v in instance_type_hints.items() } - model_name = concrete_name(cls, params) + model_name = cls.__concrete_name__(params) validators = gather_all_validators(cls) fields: Dict[str, Tuple[Type[Any], Any]] = { k: (v, cls.__fields__[k].field_info) for k, v in concrete_type_hints.items() if k in cls.__fields__ @@ -60,11 +60,14 @@ def __class_getitem__( # type: ignore _generic_types_cache[(cls, params[0])] = created_model return created_model - -def concrete_name(cls: Type[Any], params: Tuple[Type[Any], ...]) -> str: - param_names = [param.__name__ if hasattr(param, '__name__') else str(param) for param in params] - params_component = ', '.join(param_names) - return f'{cls.__name__}[{params_component}]' + @classmethod + def __concrete_name__(cls: Type[Any], params: Tuple[Type[Any], ...]) -> str: + """ + This method can be overridden to achieve a custom naming scheme for GenericModels + """ + param_names = [param.__name__ if hasattr(param, '__name__') else str(param) for param in params] + params_component = ', '.join(param_names) + return f'{cls.__name__}[{params_component}]' def resolve_type_hint(type_: Any, typevars_map: Dict[Any, Any]) -> Type[Any]:
pydantic/pydantic
425fac634312dab910d2fc6ae161ed461e16bab3
diff --git a/tests/test_generics.py b/tests/test_generics.py --- a/tests/test_generics.py +++ b/tests/test_generics.py @@ -1,6 +1,6 @@ import sys from enum import Enum -from typing import Any, ClassVar, Dict, Generic, List, Optional, TypeVar, Union +from typing import Any, ClassVar, Dict, Generic, List, Optional, Tuple, Type, TypeVar, Union import pytest @@ -421,3 +421,20 @@ class MyModel(GenericModel, Generic[T]): schema = MyModel[int].schema() assert schema['properties']['a'].get('description') == 'Custom' + + +@skip_36 +def test_custom_generic_naming(): + T = TypeVar('T') + + class MyModel(GenericModel, Generic[T]): + value: Optional[T] + + @classmethod + def __concrete_name__(cls: Type[Any], params: Tuple[Type[Any], ...]) -> str: + param_names = [param.__name__ if hasattr(param, '__name__') else str(param) for param in params] + title = param_names[0].title() + return f'Optional{title}Wrapper' + + assert str(MyModel[int](value=1)) == 'OptionalIntWrapper value=1' + assert str(MyModel[str](value=None)) == 'OptionalStrWrapper value=None'
Support custom naming for GenericModel subclasses # Feature Request Right now, it is not easy to use a custom naming scheme for a generic models. But I think this could be useful in some cases. ------ I recently faced this problem when I realized that the generated schema for `List[Optional[T]]` types doesn't actually mark the value type as optional (strangely/sadly I think there isn't currently a well-supported way to do this under OpenAPI). My workaround was to create a wrapper class for optionals: ```python class OptionalWrapper(GenericModel, Generic[T]): value: Optional[T] ``` But I wanted to override the `cls.__name__` since that is used by FastAPI when generating the openapi spec. (For example, I wanted to see `OptionalInt` instead of `OptionalWrapper[int]`.) Given how small a code change this requires, I think it should be reasonable, but I figured I'd create an issue for discussion just in case.
0.0
425fac634312dab910d2fc6ae161ed461e16bab3
[ "tests/test_generics.py::test_custom_generic_naming" ]
[ "tests/test_generics.py::test_generic_name", "tests/test_generics.py::test_double_parameterize_error", "tests/test_generics.py::test_value_validation", "tests/test_generics.py::test_methods_are_inherited", "tests/test_generics.py::test_config_is_inherited", "tests/test_generics.py::test_default_argument", "tests/test_generics.py::test_default_argument_for_typevar", "tests/test_generics.py::test_classvar", "tests/test_generics.py::test_non_annotated_field", "tests/test_generics.py::test_must_inherit_from_generic", "tests/test_generics.py::test_parameters_must_be_typevar", "tests/test_generics.py::test_subclass_can_be_genericized", "tests/test_generics.py::test_parameter_count", "tests/test_generics.py::test_cover_cache", "tests/test_generics.py::test_generic_config", "tests/test_generics.py::test_generic_instantiation_error", "tests/test_generics.py::test_parameterized_generic_instantiation_error", "tests/test_generics.py::test_deep_generic", "tests/test_generics.py::test_enum_generic", "tests/test_generics.py::test_generic", "tests/test_generics.py::test_alongside_concrete_generics", "tests/test_generics.py::test_complex_nesting", "tests/test_generics.py::test_required_value", "tests/test_generics.py::test_optional_value", "tests/test_generics.py::test_custom_schema" ]
{ "failed_lite_validators": [ "has_added_files" ], "has_test_patch": true, "is_lite": false }
2019-10-03 08:57:17+00:00
mit
4,913
pydantic__pydantic-868
diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -130,7 +130,7 @@ def validate_custom_root_type(fields: Dict[str, ModelField]) -> None: class ModelMetaclass(ABCMeta): @no_type_check # noqa C901 - def __new__(mcs, name, bases, namespace): + def __new__(mcs, name, bases, namespace, **kwargs): fields: Dict[str, ModelField] = {} config = BaseConfig validators: 'ValidatorListDict' = {} @@ -220,7 +220,7 @@ def __new__(mcs, name, bases, namespace): '__custom_root_type__': _custom_root_type, **{n: v for n, v in namespace.items() if n not in fields}, } - return super().__new__(mcs, name, bases, new_namespace) + return super().__new__(mcs, name, bases, new_namespace, **kwargs) class BaseModel(metaclass=ModelMetaclass):
pydantic/pydantic
799cd370fe78b4172a81f5dc6ea5ad086bbd2978
diff --git a/tests/test_main.py b/tests/test_main.py --- a/tests/test_main.py +++ b/tests/test_main.py @@ -1001,3 +1001,19 @@ class Bar(BaseModel): assert m.dict() == {'c': 3, 'd': {'a': 1, 'b': 2}} assert list(m) == [('c', 3), ('d', Foo())] assert dict(m) == {'c': 3, 'd': Foo()} + + +def test_custom_init_subclass_params(): + class DerivedModel(BaseModel): + def __init_subclass__(cls, something): + cls.something = something + + # if this raises a TypeError, then there is a regression of issue 867: + # pydantic.main.MetaModel.__new__ should include **kwargs at the end of the + # method definition and pass them on to the super call at the end in order + # to allow the special method __init_subclass__ to be defined with custom + # parameters on extended BaseModel classes. + class NewModel(DerivedModel, something=2): + something = 1 + + assert NewModel.something == 2
Allow extra keyword arguments in MetaModel.__new__ # Bug `pydantic.main.ModelMetaclass.__new__` should include `**kwargs` at the end of the method definition and pass them on to the `super` call at the end in order to allow the special method [`__init_subclass__`](https://docs.python.org/3/reference/datamodel.html#object.__init_subclass__) to be defined with custom parameters on extended `BaseModel` classes. Environment: * OS: Ubuntu 1804 * Python version `import sys; print(sys.version)`: `3.7.3 (default, Apr 3 2019, 19:16:38) \n[GCC 8.0.1 20180414 (experimental) [trunk revision 259383]]` * Pydantic version `import pydantic; print(pydantic.VERSION)`: 0.31 For example: ```py import pydantic class CustomBaseModel(pydantic.BaseModel): def __init_subclass__(cls, special_parameter): # do something with special_parameter ... class NewModel(CustomBaseModel, special_parameter=42): # model definition here ... ``` should not raise any exceptions. But: ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> class NewModel(CustomBaseModel, special_parameter=42): File "pydantic/main.py", line 178, in pydantic.main.ModelMetaclass.__new__ TypeError: __new__() got an unexpected keyword argument 'special_parameter' ``` I can (and will) submit a PR for this if you accept it; it is an extremely simple fix (plus not-so-simple tests because metaclasses). Allow extra keyword arguments in MetaModel.__new__ # Bug `pydantic.main.ModelMetaclass.__new__` should include `**kwargs` at the end of the method definition and pass them on to the `super` call at the end in order to allow the special method [`__init_subclass__`](https://docs.python.org/3/reference/datamodel.html#object.__init_subclass__) to be defined with custom parameters on extended `BaseModel` classes. Environment: * OS: Ubuntu 1804 * Python version `import sys; print(sys.version)`: `3.7.3 (default, Apr 3 2019, 19:16:38) \n[GCC 8.0.1 20180414 (experimental) [trunk revision 259383]]` * Pydantic version `import pydantic; print(pydantic.VERSION)`: 0.31 For example: ```py import pydantic class CustomBaseModel(pydantic.BaseModel): def __init_subclass__(cls, special_parameter): # do something with special_parameter ... class NewModel(CustomBaseModel, special_parameter=42): # model definition here ... ``` should not raise any exceptions. But: ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> class NewModel(CustomBaseModel, special_parameter=42): File "pydantic/main.py", line 178, in pydantic.main.ModelMetaclass.__new__ TypeError: __new__() got an unexpected keyword argument 'special_parameter' ``` I can (and will) submit a PR for this if you accept it; it is an extremely simple fix (plus not-so-simple tests because metaclasses).
0.0
799cd370fe78b4172a81f5dc6ea5ad086bbd2978
[ "tests/test_main.py::test_custom_init_subclass_params" ]
[ "tests/test_main.py::test_success", "tests/test_main.py::test_ultra_simple_missing", "tests/test_main.py::test_ultra_simple_failed", "tests/test_main.py::test_ultra_simple_repr", "tests/test_main.py::test_str_truncate", "tests/test_main.py::test_comparing", "tests/test_main.py::test_nullable_strings_success", "tests/test_main.py::test_nullable_strings_fails", "tests/test_main.py::test_recursion", "tests/test_main.py::test_recursion_fails", "tests/test_main.py::test_not_required", "tests/test_main.py::test_infer_type", "tests/test_main.py::test_allow_extra", "tests/test_main.py::test_forbidden_extra_success", "tests/test_main.py::test_forbidden_extra_fails", "tests/test_main.py::test_disallow_mutation", "tests/test_main.py::test_extra_allowed", "tests/test_main.py::test_extra_ignored", "tests/test_main.py::test_set_attr", "tests/test_main.py::test_set_attr_invalid", "tests/test_main.py::test_any", "tests/test_main.py::test_alias", "tests/test_main.py::test_population_by_alias", "tests/test_main.py::test_field_order", "tests/test_main.py::test_required", "tests/test_main.py::test_not_immutability", "tests/test_main.py::test_immutability", "tests/test_main.py::test_const_validates", "tests/test_main.py::test_const_uses_default", "tests/test_main.py::test_const_with_wrong_value", "tests/test_main.py::test_const_list", "tests/test_main.py::test_const_list_with_wrong_value", "tests/test_main.py::test_const_validation_json_serializable", "tests/test_main.py::test_validating_assignment_pass", "tests/test_main.py::test_validating_assignment_fail", "tests/test_main.py::test_enum_values", "tests/test_main.py::test_enum_raw", "tests/test_main.py::test_set_tuple_values", "tests/test_main.py::test_default_copy", "tests/test_main.py::test_arbitrary_type_allowed_validation_success", "tests/test_main.py::test_arbitrary_type_allowed_validation_fails", "tests/test_main.py::test_arbitrary_types_not_allowed", "tests/test_main.py::test_type_type_validation_success", "tests/test_main.py::test_type_type_subclass_validation_success", "tests/test_main.py::test_type_type_validation_fails_for_instance", "tests/test_main.py::test_type_type_validation_fails_for_basic_type", "tests/test_main.py::test_annotation_field_name_shadows_attribute", "tests/test_main.py::test_value_field_name_shadows_attribute", "tests/test_main.py::test_class_var", "tests/test_main.py::test_fields_set", "tests/test_main.py::test_skip_defaults_dict", "tests/test_main.py::test_skip_defaults_recursive", "tests/test_main.py::test_dict_skip_defaults_populated_by_alias", "tests/test_main.py::test_dict_skip_defaults_populated_by_alias_with_extra", "tests/test_main.py::test_dir_fields", "tests/test_main.py::test_dict_with_extra_keys", "tests/test_main.py::test_alias_generator", "tests/test_main.py::test_alias_generator_with_field_schema", "tests/test_main.py::test_alias_generator_wrong_type_error", "tests/test_main.py::test_root", "tests/test_main.py::test_root_list", "tests/test_main.py::test_root_failed", "tests/test_main.py::test_root_undefined_failed", "tests/test_main.py::test_parse_root_as_mapping", "tests/test_main.py::test_untouched_types", "tests/test_main.py::test_custom_types_fail_without_keep_untouched", "tests/test_main.py::test_model_iteration" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2019-10-06 19:28:07+00:00
mit
4,914
pydantic__pydantic-891
diff --git a/pydantic/env_settings.py b/pydantic/env_settings.py --- a/pydantic/env_settings.py +++ b/pydantic/env_settings.py @@ -5,6 +5,7 @@ from .fields import ModelField from .main import BaseModel, Extra from .typing import display_as_type +from .utils import deep_update class SettingsError(ValueError): @@ -24,7 +25,7 @@ def __init__(__pydantic_self__, **values: Any) -> None: super().__init__(**__pydantic_self__._build_values(values)) def _build_values(self, init_kwargs: Dict[str, Any]) -> Dict[str, Any]: - return {**self._build_environ(), **init_kwargs} + return deep_update(self._build_environ(), init_kwargs) def _build_environ(self) -> Dict[str, Optional[str]]: """ diff --git a/pydantic/utils.py b/pydantic/utils.py --- a/pydantic/utils.py +++ b/pydantic/utils.py @@ -5,6 +5,7 @@ TYPE_CHECKING, Any, Callable, + Dict, Generator, Iterator, List, @@ -12,6 +13,7 @@ Set, Tuple, Type, + TypeVar, Union, no_type_check, ) @@ -23,11 +25,12 @@ except ImportError: Literal = None # type: ignore - if TYPE_CHECKING: from .main import BaseModel # noqa: F401 from .typing import SetIntStr, DictIntStrAny, IntStr, ReprArgs # noqa: F401 +KeyType = TypeVar('KeyType') + def import_string(dotted_path: str) -> Any: """ @@ -98,6 +101,16 @@ def in_ipython() -> bool: return True +def deep_update(mapping: Dict[KeyType, Any], updating_mapping: Dict[KeyType, Any]) -> Dict[KeyType, Any]: + updated_mapping = mapping.copy() + for k, v in updating_mapping.items(): + if k in mapping and isinstance(mapping[k], dict) and isinstance(v, dict): + updated_mapping[k] = deep_update(mapping[k], v) + else: + updated_mapping[k] = v + return updated_mapping + + def almost_equal_floats(value_1: float, value_2: float, *, delta: float = 1e-8) -> bool: """ Return True if two floats are almost equal
pydantic/pydantic
6cda388c7a1af29d17973f72dfebd98cff626988
Yeah this seems like a good feature request to me. I've never tried nesting BaseSettings classes but it seems totally reasonable to me and I don't see any reason it shouldn't work like this. (But maybe @samuelcolvin does?) Could you produce a failing test case or two as a starting point for implementation work? Sounds good to me. Do you want to use dot notation e.g. `db.host`? Also should this work for dictionaries too? This isn't required for v1 since it would be entirely backwards compatible. It's great to hear! I think the only logic that needs to change is merging of `self._build_environ()` and `init_kwargs` dictionaries, so I don't see why it wouldn't work for dictionaries. Should I start a merge request with the changes and tests or would you like to tackle this one yourselves? @idmitrievsky It would be great if you could start a pull request for this. Your approach to the logic sounds right to me (though admittedly there could be some edge cases I'm not considering).
diff --git a/tests/test_settings.py b/tests/test_settings.py --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -1,5 +1,5 @@ import os -from typing import List, Set +from typing import Dict, List, Set import pytest @@ -48,6 +48,32 @@ class Config: assert s.apple == 'has_prefix' +def test_nested_env_with_basemodel(env): + class TopValue(BaseModel): + apple: str + banana: str + + class Settings(BaseSettings): + top: TopValue + + with pytest.raises(ValidationError): + Settings() + env.set('top', '{"banana": "secret_value"}') + s = Settings(top={'apple': 'value'}) + assert s.top == {'apple': 'value', 'banana': 'secret_value'} + + +def test_nested_env_with_dict(env): + class Settings(BaseSettings): + top: Dict[str, str] + + with pytest.raises(ValidationError): + Settings() + env.set('top', '{"banana": "secret_value"}') + s = Settings(top={'apple': 'value'}) + assert s.top == {'apple': 'value', 'banana': 'secret_value'} + + class DateModel(BaseModel): pips: bool = False diff --git a/tests/test_utils.py b/tests/test_utils.py --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -8,7 +8,7 @@ from pydantic import BaseModel from pydantic.color import Color from pydantic.typing import display_as_type, is_new_type, new_type_supertype -from pydantic.utils import ValueItems, import_string, lenient_issubclass, truncate +from pydantic.utils import ValueItems, deep_update, import_string, lenient_issubclass, truncate try: import devtools @@ -222,3 +222,43 @@ class Model(BaseModel): ' ],\n' ')' ) + + [email protected]( + 'mapping, updating_mapping, expected_mapping, msg', + [ + ( + {'key': {'inner_key': 0}}, + {'other_key': 1}, + {'key': {'inner_key': 0}, 'other_key': 1}, + 'extra keys are inserted', + ), + ( + {'key': {'inner_key': 0}, 'other_key': 1}, + {'key': [1, 2, 3]}, + {'key': [1, 2, 3], 'other_key': 1}, + 'values that can not be merged are updated', + ), + ( + {'key': {'inner_key': 0}}, + {'key': {'other_key': 1}}, + {'key': {'inner_key': 0, 'other_key': 1}}, + 'values that have corresponding keys are merged', + ), + ( + {'key': {'inner_key': {'deep_key': 0}}}, + {'key': {'inner_key': {'other_deep_key': 1}}}, + {'key': {'inner_key': {'deep_key': 0, 'other_deep_key': 1}}}, + 'deeply nested values that have corresponding keys are merged', + ), + ], +) +def test_deep_update(mapping, updating_mapping, expected_mapping, msg): + assert deep_update(mapping, updating_mapping) == expected_mapping, msg + + +def test_deep_update_is_not_mutating(): + mapping = {'key': {'inner_key': {'deep_key': 1}}} + updated_mapping = deep_update(mapping, {'key': {'inner_key': {'other_deep_key': 1}}}) + assert updated_mapping == {'key': {'inner_key': {'deep_key': 1, 'other_deep_key': 1}}} + assert mapping == {'key': {'inner_key': {'deep_key': 1}}}
Providing only one nested value from environment variable # Feature Request * OS: **macOS** * Python version `import sys; print(sys.version)`: **3.6.8 (default, Jun 24 2019, 16:49:13) [GCC 4.2.1 Compatible Apple LLVM 10.0.1 (clang-1001.0.46.4)]** * Pydantic version `import pydantic; print(pydantic.VERSION)`: **1.0b2** Hello, great work on the library! I can't find the reason, why environment variables don't work in nested settings. I have a class ```python class Credentials(pydantic.BaseModel): host: str user: str database: str password: pydantic.SecretStr class Settings(pydantic.BaseSettings): db: Credentials class Config: env_prefix = 'APP_' ``` and I want to specify `password` as an environment variable ``` export APP_DB='{"password": ""}' ``` but pass other fields in as values in code. Right now `BaseSettings` does simple top-level merging of dictionaries that doesn't consider nested values ```python def _build_values(self, init_kwargs: Dict[str, Any]) -> Dict[str, Any]: return {**self._build_environ(), **init_kwargs} ``` but dictionaries could be merged recursively, so users could provide values for any of their settings in environment variables. What do you think, would it be useful?
0.0
6cda388c7a1af29d17973f72dfebd98cff626988
[ "tests/test_settings.py::test_sub_env", "tests/test_settings.py::test_sub_env_override", "tests/test_settings.py::test_sub_env_missing", "tests/test_settings.py::test_other_setting", "tests/test_settings.py::test_with_prefix", "tests/test_settings.py::test_nested_env_with_basemodel", "tests/test_settings.py::test_nested_env_with_dict", "tests/test_settings.py::test_list", "tests/test_settings.py::test_set_dict_model", "tests/test_settings.py::test_invalid_json", "tests/test_settings.py::test_required_sub_model", "tests/test_settings.py::test_non_class", "tests/test_settings.py::test_env_str", "tests/test_settings.py::test_env_list", "tests/test_settings.py::test_env_list_field", "tests/test_settings.py::test_env_list_last", "tests/test_settings.py::test_env_inheritance", "tests/test_settings.py::test_env_inheritance_field", "tests/test_settings.py::test_env_invalid", "tests/test_settings.py::test_env_field", "tests/test_settings.py::test_aliases_warning", "tests/test_settings.py::test_aliases_no_warning", "tests/test_settings.py::test_case_sensitive", "tests/test_settings.py::test_case_insensitive", "tests/test_settings.py::test_nested_dataclass", "tests/test_settings.py::test_env_takes_precedence", "tests/test_settings.py::test_config_file_settings_nornir", "tests/test_settings.py::test_alias_set", "tests/test_utils.py::test_import_module", "tests/test_utils.py::test_import_module_invalid", "tests/test_utils.py::test_import_no_attr", "tests/test_utils.py::test_display_as_type[str-str]", "tests/test_utils.py::test_display_as_type[string-str]", "tests/test_utils.py::test_display_as_type[value2-typing.Union[str,", "tests/test_utils.py::test_display_as_type_enum", "tests/test_utils.py::test_display_as_type_enum_int", "tests/test_utils.py::test_display_as_type_enum_str", "tests/test_utils.py::test_lenient_issubclass", "tests/test_utils.py::test_lenient_issubclass_is_lenient", "tests/test_utils.py::test_truncate[object-<class", "tests/test_utils.py::test_truncate[abcdefghijklmnopqrstuvwxyz-'abcdefghijklmnopq\\u2026']", "tests/test_utils.py::test_truncate[input_value2-[0,", "tests/test_utils.py::test_value_items", "tests/test_utils.py::test_value_items_error", "tests/test_utils.py::test_is_new_type", "tests/test_utils.py::test_new_type_supertype", "tests/test_utils.py::test_pretty", "tests/test_utils.py::test_pretty_color", "tests/test_utils.py::test_devtools_output", "tests/test_utils.py::test_devtools_output_validation_error", "tests/test_utils.py::test_deep_update[mapping0-updating_mapping0-expected_mapping0-extra", "tests/test_utils.py::test_deep_update[mapping1-updating_mapping1-expected_mapping1-values", "tests/test_utils.py::test_deep_update[mapping2-updating_mapping2-expected_mapping2-values", "tests/test_utils.py::test_deep_update[mapping3-updating_mapping3-expected_mapping3-deeply", "tests/test_utils.py::test_deep_update_is_not_mutating" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-10-13 19:30:15+00:00
mit
4,915
pydantic__pydantic-898
diff --git a/docs/examples/ex_construct.py b/docs/examples/ex_construct.py new file mode 100644 --- /dev/null +++ b/docs/examples/ex_construct.py @@ -0,0 +1,27 @@ +from pydantic import BaseModel + +class User(BaseModel): + id: int + age: int + name: str = 'John Doe' + +original_user = User(id=123, age=32) + +user_data = original_user.dict() +print(user_data) +fields_set = original_user.__fields_set__ +print(fields_set) + +# ... +# pass user_data and fields_set to RPC or save to the database etc. +# ... + +# you can then create a new instance of User without +# re-running validation which would be unnecessary at this point: +new_user = User.construct(_fields_set=fields_set, **user_data) +print(repr(new_user)) +print(new_user.__fields_set__) + +# construct can be dangerous, only use it with validated data!: +bad_user = User.construct(id='dog') +print(repr(bad_user)) diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -439,14 +439,16 @@ def from_orm(cls: Type['Model'], obj: Any) -> 'Model': return m @classmethod - def construct(cls: Type['Model'], values: 'DictAny', fields_set: 'SetStr') -> 'Model': + def construct(cls: Type['Model'], _fields_set: Optional['SetStr'] = None, **values: Any) -> 'Model': """ - Creates a new model and set __dict__ without any validation, thus values should already be trusted. - Chances are you don't want to use this method directly. + Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. + Default values are respected, but no other validation is performed. """ m = cls.__new__(cls) - object.__setattr__(m, '__dict__', values) - object.__setattr__(m, '__fields_set__', fields_set) + object.__setattr__(m, '__dict__', {**deepcopy(cls.__field_defaults__), **values}) + if _fields_set is None: + _fields_set = set(values.keys()) + object.__setattr__(m, '__fields_set__', _fields_set) return m def copy( @@ -491,7 +493,11 @@ def copy( if deep: v = deepcopy(v) - m = self.__class__.construct(v, self.__fields_set__.copy()) + + cls = self.__class__ + m = cls.__new__(cls) + object.__setattr__(m, '__dict__', v) + object.__setattr__(m, '__fields_set__', self.__fields_set__.copy()) return m @classmethod
pydantic/pydantic
6b5adcc977a205d56bd8fc106ac2e6b3fd1104b4
I am also very interested in this question, as in many cases in my code I *know* the values are correct and don't require validation. It would also be nice to have an API for initializing a model instance from known-valid inputs without needing to go through the various alias-lookups etc. In general though I wouldn't want to disable the validation at the *model* level, but rather on a per-initialization basis. (So a separate classmethod for initializing from known-valid values would be nice.) I *think* this is possible in one way or another; I'll see if I can make any progress. ---- @prostomarkeloff if you really do want "models" with validation completely disabled under all circumstances, you might try using vanilla dataclasses? Okay, yes, I got this working (based on `BaseModel.validate`): The following method could be added to your model subclass if you want to do 100% unvalidated assignment (beyond checking field names and falling back to default values): ```python @classmethod def unvalidated(__pydantic_cls__: "Type[Model]", **data: Any) -> "Model": for name, field in __pydantic_cls__.__fields__.items(): try: data[name] except KeyError: if field.required: raise TypeError(f"Missing required keyword argument {name!r}") if field.default is None: # deepcopy is quite slow on None value = None else: value = deepcopy(field.default) data[name] = value self = __pydantic_cls__.__new__(__pydantic_cls__) object.__setattr__(self, "__dict__", data) object.__setattr__(self, "__fields_set__", set(data.keys())) return self ``` I did some performance tests and for data-heavy models, and the performance difference is enormous: <details> <summary>Click to expand the benchmark script</summary> ```python from contextlib import contextmanager import time from datetime import datetime from typing import List, Dict, Iterator from pydantic import BaseModel class DoubleNestedModel(BaseModel): number: int message: str class SubDoubleNestedModel(DoubleNestedModel): timestamps: List[datetime] class NestedModel(BaseModel): number: int message: str double_nested: DoubleNestedModel class SubNestedModel(NestedModel): timestamps: List[datetime] class Model(BaseModel): nested: List[Dict[str, NestedModel]] class SubModel(Model): other_nested: Dict[str, List[NestedModel]] timestamps: List[datetime] def get_sub_model(timestamp: datetime) -> SubModel: timestamps = [timestamp] * 5 sub_double_nested = SubDoubleNestedModel(number=1, message="a", timestamps=timestamps) sub_nested = SubNestedModel(number=2, message="b", double_nested=sub_double_nested, timestamps=timestamps) nested = [{letter: sub_nested for letter in 'abcdefg'}] other_nested = {letter: [sub_nested] * 5 for letter in 'abcdefg'} return SubModel(nested=nested, other_nested=other_nested, timestamps=timestamps) def get_sub_model_unvalidated(timestamp: datetime) -> SubModel: timestamps = [timestamp] * 5 sub_double_nested = SubDoubleNestedModel.unvalidated(number=1, message="a", timestamps=timestamps) sub_nested = SubNestedModel.unvalidated(number=2, message="b", double_nested=sub_double_nested, timestamps=timestamps) nested = [{letter: sub_nested for letter in 'abcdefg'}] other_nested = {letter: [sub_nested] * 5 for letter in 'abcdefg'} return SubModel.unvalidated(nested=nested, other_nested=other_nested, timestamps=timestamps) @contextmanager def basic_profile(label: str) -> Iterator[None]: t0 = time.time() yield t1 = time.time() print(f"{label}: {(t1 - t0):,.3f}s") def run(): n_warmup_runs = 1000 n_runs = 10000 timestamp = datetime.utcnow() sub_model = get_sub_model(timestamp) unvalidated_sub_model = get_sub_model_unvalidated(timestamp) assert sub_model == unvalidated_sub_model for _ in range(n_warmup_runs): get_sub_model(timestamp) get_sub_model_unvalidated(timestamp) with basic_profile("validated"): for _ in range(n_runs): get_sub_model(timestamp) with basic_profile("unvalidated"): for _ in range(n_runs): get_sub_model_unvalidated(timestamp) run() ``` </details> The result: ``` validated: 2.918s unvalidated: 0.083s ``` That's a 35x speedup. Not surprising, given that validators are called on each list element / dict value. But given the performance benefits I think it may be worth using an API like this if you know it's safe. Currently it's probably bit risky due to the lack of type checking, but it would be very easy to use a mypy plugin to set the signature in the same way currently done in https://github.com/samuelcolvin/pydantic/pull/722 for the `__init__` function. So I think this could be supported in a statically checked way. (Note: this would not call any custom validators or similar.) Note: in my testing, removing the field checks and default value inference sped things up even further to an ~43x speedup, but I think having the field and default checks are worthwhile. @samuelcolvin do you think there is any room for a method like this on the `BaseModel` class in pydantic proper? (Maybe with a little more polish in case I'm mishandling some edge cases?) Or do you think this should be left to users to implement at their own risk? This is what `construct` is for: https://github.com/samuelcolvin/pydantic/blob/6cda388c7a1af29d17973f72dfebd98cff626988/pydantic/main.py#L417 It definitely needs documenting but I don't think we need a new method. If it's signature needs changing to do what you want, we should do that pre v1 if possible. @samuelcolvin I wasn't aware of that, that's nice. It seems to me that 1) support for default values, and 2) not needing to manually specify the `fields_set` would go a long way toward making it more of a drop in replacement for `__init__` when the input data is known-valid. I think it would be easier to justify the refactor efforts (in a pydantic-using codebase where I want to use `construct` for performance reasons) if it was literally just a matter of adding `.construct` for the speed up, as opposed to the more potentially involved refactor currently required. I would be in favor of a private method like `_construct` instead of what is currently called `construct`, and have `construct` use defaults if missing and set the `fields_set` based on the keyword arguments provided. I would also understand if you didn't want to add a breaking API change this far into the 1.0 beta. I would definitely be in favor of adding the above-described functionality though even if it needs to be a different method name or a private call. But I can always just define it on custom base class, so it's not the end of the world. > I am also very interested in this question, as in many cases in my code I _know_ the values are correct and don't require validation. It would also be nice to have an API for initializing a model instance from known-valid inputs without needing to go through the various alias-lookups etc. > > In general though I wouldn't want to disable the validation at the _model_ level, but rather on a per-initialization basis. (So a separate classmethod for initializing from known-valid values would be nice.) > > I _think_ this is possible in one way or another; I'll see if I can make any progress. > > @prostomarkeloff if you really do want "models" with validation completely disabled under all circumstances, you might try using vanilla dataclasses? Thank you for answer! What about dataclasses? Firstly, i don't want to mix really different libraries in one project, secondly, dataclasses slower than pydantic. Some models in my project need this feature.
diff --git a/tests/test_construction.py b/tests/test_construction.py --- a/tests/test_construction.py +++ b/tests/test_construction.py @@ -12,18 +12,27 @@ class Model(BaseModel): def test_simple_construct(): - m = Model.construct(dict(a=40, b=10), {'a', 'b'}) - assert m.a == 40 + m = Model.construct(a=3.14) + assert m.a == 3.14 assert m.b == 10 + assert m.__fields_set__ == {'a'} + assert m.dict() == {'a': 3.14, 'b': 10} -def test_construct_missing(): - m = Model.construct(dict(a='not a float'), {'a'}) - assert m.a == 'not a float' - with pytest.raises(AttributeError) as exc_info: - print(m.b) +def test_construct_misuse(): + m = Model.construct(b='foobar') + assert m.b == 'foobar' + assert m.dict() == {'b': 'foobar'} + with pytest.raises(AttributeError, match="'Model' object has no attribute 'a'"): + print(m.a) - assert "'Model' object has no attribute 'b'" in exc_info.value.args[0] + +def test_construct_fields_set(): + m = Model.construct(a=3.0, b=-1, _fields_set={'a'}) + assert m.a == 3 + assert m.b == -1 + assert m.__fields_set__ == {'a'} + assert m.dict() == {'a': 3, 'b': -1} def test_large_any_str(): diff --git a/tests/test_edge_cases.py b/tests/test_edge_cases.py --- a/tests/test_edge_cases.py +++ b/tests/test_edge_cases.py @@ -554,7 +554,7 @@ class Model(BaseModel): assert Model(a=1, field_set=2).dict() == {'a': 1, 'field_set': 2, 'b': 3} assert Model(a=1, field_set=2).dict(exclude_unset=True) == {'a': 1, 'field_set': 2} - assert Model.construct(dict(a=1, field_set=3), {'a', 'field_set'}).dict() == {'a': 1, 'field_set': 3} + assert Model.construct(a=1, field_set=3).dict() == {'a': 1, 'field_set': 3, 'b': 3} def test_values_order():
Disable all validations # Question Please complete: * OS: Ubuntu 18.04 * Python version `import sys; print(sys.version)`: 3.7.3 (default, Apr 3 2019, 19:16:38) [GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] * Pydantic version `import pydantic; print(pydantic.VERSION)`: 0.32.2 Hello anyone, It possible to disable all validations of incoming data? ```py import pydantic class MyModel(pydantic.BaseModel): class Config: validation = False ... ```
0.0
6b5adcc977a205d56bd8fc106ac2e6b3fd1104b4
[ "tests/test_construction.py::test_simple_construct", "tests/test_construction.py::test_construct_misuse", "tests/test_construction.py::test_construct_fields_set", "tests/test_edge_cases.py::test_field_set_field_name" ]
[ "tests/test_construction.py::test_large_any_str", "tests/test_construction.py::test_simple_copy", "tests/test_construction.py::test_deep_copy", "tests/test_construction.py::test_copy_exclude", "tests/test_construction.py::test_copy_include", "tests/test_construction.py::test_copy_include_exclude", "tests/test_construction.py::test_copy_advanced_exclude", "tests/test_construction.py::test_copy_advanced_include", "tests/test_construction.py::test_copy_advanced_include_exclude", "tests/test_construction.py::test_copy_update", "tests/test_construction.py::test_copy_set_fields", "tests/test_construction.py::test_simple_pickle", "tests/test_construction.py::test_recursive_pickle", "tests/test_construction.py::test_immutable_copy", "tests/test_construction.py::test_pickle_fields_set", "tests/test_construction.py::test_copy_update_exclude", "tests/test_edge_cases.py::test_str_bytes", "tests/test_edge_cases.py::test_str_bytes_none", "tests/test_edge_cases.py::test_union_int_str", "tests/test_edge_cases.py::test_union_priority", "tests/test_edge_cases.py::test_typed_list", "tests/test_edge_cases.py::test_typed_set", "tests/test_edge_cases.py::test_dict_dict", "tests/test_edge_cases.py::test_typed_dict[value0-result0]", "tests/test_edge_cases.py::test_typed_dict[value1-result1]", "tests/test_edge_cases.py::test_typed_dict[value2-result2]", "tests/test_edge_cases.py::test_typed_dict_error[1-errors0]", "tests/test_edge_cases.py::test_typed_dict_error[value1-errors1]", "tests/test_edge_cases.py::test_typed_dict_error[value2-errors2]", "tests/test_edge_cases.py::test_dict_key_error", "tests/test_edge_cases.py::test_tuple", "tests/test_edge_cases.py::test_tuple_more", "tests/test_edge_cases.py::test_tuple_length_error", "tests/test_edge_cases.py::test_tuple_invalid", "tests/test_edge_cases.py::test_tuple_value_error", "tests/test_edge_cases.py::test_recursive_list", "tests/test_edge_cases.py::test_recursive_list_error", "tests/test_edge_cases.py::test_list_unions", "tests/test_edge_cases.py::test_recursive_lists", "tests/test_edge_cases.py::test_str_enum", "tests/test_edge_cases.py::test_any_dict", "tests/test_edge_cases.py::test_infer_alias", "tests/test_edge_cases.py::test_alias_error", "tests/test_edge_cases.py::test_annotation_config", "tests/test_edge_cases.py::test_success_values_include", "tests/test_edge_cases.py::test_include_exclude_unset", "tests/test_edge_cases.py::test_include_exclude_defaults", "tests/test_edge_cases.py::test_skip_defaults_deprecated", "tests/test_edge_cases.py::test_advanced_exclude", "tests/test_edge_cases.py::test_advanced_value_inclide", "tests/test_edge_cases.py::test_advanced_value_exclude_include", "tests/test_edge_cases.py::test_field_set_ignore_extra", "tests/test_edge_cases.py::test_field_set_allow_extra", "tests/test_edge_cases.py::test_values_order", "tests/test_edge_cases.py::test_inheritance", "tests/test_edge_cases.py::test_invalid_type", "tests/test_edge_cases.py::test_valid_string_types[a", "tests/test_edge_cases.py::test_valid_string_types[some", "tests/test_edge_cases.py::test_valid_string_types[value2-foobar]", "tests/test_edge_cases.py::test_valid_string_types[123-123]", "tests/test_edge_cases.py::test_valid_string_types[123.45-123.45]", "tests/test_edge_cases.py::test_valid_string_types[value5-12.45]", "tests/test_edge_cases.py::test_valid_string_types[True-True]", "tests/test_edge_cases.py::test_valid_string_types[False-False]", "tests/test_edge_cases.py::test_valid_string_types[a10-a10]", "tests/test_edge_cases.py::test_valid_string_types[whatever-whatever]", "tests/test_edge_cases.py::test_invalid_string_types[value0-errors0]", "tests/test_edge_cases.py::test_invalid_string_types[value1-errors1]", "tests/test_edge_cases.py::test_inheritance_config", "tests/test_edge_cases.py::test_partial_inheritance_config", "tests/test_edge_cases.py::test_annotation_inheritance", "tests/test_edge_cases.py::test_string_none", "tests/test_edge_cases.py::test_alias_camel_case", "tests/test_edge_cases.py::test_get_field_info_inherit", "tests/test_edge_cases.py::test_return_errors_ok", "tests/test_edge_cases.py::test_return_errors_error", "tests/test_edge_cases.py::test_optional_required", "tests/test_edge_cases.py::test_invalid_validator", "tests/test_edge_cases.py::test_unable_to_infer", "tests/test_edge_cases.py::test_multiple_errors", "tests/test_edge_cases.py::test_pop_by_alias", "tests/test_edge_cases.py::test_validate_all", "tests/test_edge_cases.py::test_force_extra", "tests/test_edge_cases.py::test_illegal_extra_value", "tests/test_edge_cases.py::test_multiple_inheritance_config", "tests/test_edge_cases.py::test_submodel_different_type", "tests/test_edge_cases.py::test_self", "tests/test_edge_cases.py::test_self_recursive[BaseModel]", "tests/test_edge_cases.py::test_self_recursive[BaseSettings]", "tests/test_edge_cases.py::test_nested_init[BaseModel]", "tests/test_edge_cases.py::test_nested_init[BaseSettings]", "tests/test_edge_cases.py::test_values_attr_deprecation", "tests/test_edge_cases.py::test_init_inspection", "tests/test_edge_cases.py::test_type_on_annotation", "tests/test_edge_cases.py::test_assign_type", "tests/test_edge_cases.py::test_optional_subfields", "tests/test_edge_cases.py::test_not_optional_subfields", "tests/test_edge_cases.py::test_scheme_deprecated", "tests/test_edge_cases.py::test_population_by_alias", "tests/test_edge_cases.py::test_fields_deprecated", "tests/test_edge_cases.py::test_alias_child_precedence", "tests/test_edge_cases.py::test_alias_generator_parent", "tests/test_edge_cases.py::test_optional_field_constraints", "tests/test_edge_cases.py::test_field_str_shape", "tests/test_edge_cases.py::test_field_type_display[int-int]", "tests/test_edge_cases.py::test_field_type_display[type_1-Optional[int]]", "tests/test_edge_cases.py::test_field_type_display[type_2-Union[NoneType,", "tests/test_edge_cases.py::test_field_type_display[type_3-Union[int,", "tests/test_edge_cases.py::test_field_type_display[type_4-List[int]]", "tests/test_edge_cases.py::test_field_type_display[type_5-Tuple[int,", "tests/test_edge_cases.py::test_field_type_display[type_6-Union[List[int],", "tests/test_edge_cases.py::test_field_type_display[type_7-List[Tuple[int,", "tests/test_edge_cases.py::test_field_type_display[type_8-Mapping[int,", "tests/test_edge_cases.py::test_field_type_display[type_9-Tuple[int,", "tests/test_edge_cases.py::test_field_type_display[type_10-Optional[List[int]]]" ]
{ "failed_lite_validators": [ "has_added_files", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2019-10-15 10:51:27+00:00
mit
4,916
pydantic__pydantic-904
diff --git a/docs/examples/alias_generator_config.py b/docs/examples/alias_generator_config.py --- a/docs/examples/alias_generator_config.py +++ b/docs/examples/alias_generator_config.py @@ -5,12 +5,11 @@ def to_camel(string: str) -> str: class Voice(BaseModel): name: str - gender: str language_code: str class Config: alias_generator = to_camel -voice = Voice(Name='Filiz', Gender='Female', LanguageCode='tr-TR') +voice = Voice(Name='Filiz', LanguageCode='tr-TR') print(voice.language_code) print(voice.dict(by_alias=True)) diff --git a/docs/examples/alias_precedence.py b/docs/examples/alias_precedence.py new file mode 100644 --- /dev/null +++ b/docs/examples/alias_precedence.py @@ -0,0 +1,21 @@ +from pydantic import BaseModel + +class Voice(BaseModel): + name: str + language_code: str + + class Config: + @classmethod + def alias_generator(cls, string: str) -> str: + # this is the same as `alias_generator = to_camel` above + return ''.join(word.capitalize() for word in string.split('_')) + +class Character(Voice): + mood: str + + class Config: + fields = {'mood': 'Mood', 'language_code': 'lang'} + +c = Character(Mood='happy', Name='Filiz', lang='tr-TR') +print(c) +print(c.dict(by_alias=True)) diff --git a/pydantic/fields.py b/pydantic/fields.py --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -263,10 +263,10 @@ def infer( def set_config(self, config: Type['BaseConfig']) -> None: self.model_config = config - schema_from_config = config.get_field_info(self.name) - if schema_from_config: + info_from_config = config.get_field_info(self.name) + if info_from_config: self.field_info = cast(FieldInfo, self.field_info) - self.field_info.alias = self.field_info.alias or schema_from_config.get('alias') or self.name + self.field_info.alias = info_from_config.get('alias') or self.field_info.alias or self.name self.alias = cast(str, self.field_info.alias) @property
pydantic/pydantic
806eba3810d4bc0ed02e0060521a779f12d16416
thanks for reporting, agreed it should apply to all fields. Could you try on master or v1.0b2 and confirm if it's still broken? Just tested it on `master` and can confirm it is still broken.
diff --git a/tests/test_edge_cases.py b/tests/test_edge_cases.py --- a/tests/test_edge_cases.py +++ b/tests/test_edge_cases.py @@ -1079,3 +1079,43 @@ class Model(BaseModel): assert Model().__fields__.keys() == {'v'} assert Model.__fields__.keys() == {'v'} + + +def test_alias_child_precedence(): + class Parent(BaseModel): + x: int + + class Config: + fields = {'x': 'x1'} + + class Child(Parent): + y: int + + class Config: + fields = {'y': 'y2', 'x': 'x2'} + + assert Child.__fields__['y'].alias == 'y2' + assert Child.__fields__['x'].alias == 'x2' + + +def test_alias_generator_parent(): + class Parent(BaseModel): + x: int + + class Config: + allow_population_by_field_name = True + + @classmethod + def alias_generator(cls, f_name): + return f_name + '1' + + class Child(Parent): + y: int + + class Config: + @classmethod + def alias_generator(cls, f_name): + return f_name + '2' + + assert Child.__fields__['y'].alias == 'y2' + assert Child.__fields__['x'].alias == 'x2'
Alias generator not working on inherited attributes # Alias generator not working on inherited attributes * OS: **Debian GNU/Linux 9 (stretch)** * Python version `import sys; print(sys.version)`: **3.7.3** * Pydantic version `import pydantic; print(pydantic.VERSION)`: **0.32.2** On inherited attributes, the alias generators do not work, if the base class also has an alias generator set. Minimal example: ```py from pydantic import BaseModel def alias_generator_1(field_name: str) -> str: return field_name + '1' def alias_generator_2(field_name: str) -> str: return field_name + '2' class Base(BaseModel): x: int class Config: allow_population_by_alias = True alias_generator = alias_generator_1 class Impl(Base): y: int class Config(Base.Config): alias_generator = alias_generator_2 i = Impl(x=1, y=2) # expected: {'x2': 1, 'y2': 2} # actual: {'x1': 1, 'y2': 2} print(i.dict(by_alias=True)) ``` A simple fix is to just define the attribute again on the child like so: ``` class Impl(Base): x: int y: int class Config(Base.Config): alias_generator = alias_generator_2 ``` But i would expect the `alias_generator` to be overridden for all attributes, when defined in subclasses.
0.0
806eba3810d4bc0ed02e0060521a779f12d16416
[ "tests/test_edge_cases.py::test_alias_child_precedence", "tests/test_edge_cases.py::test_alias_generator_parent" ]
[ "tests/test_edge_cases.py::test_str_bytes", "tests/test_edge_cases.py::test_str_bytes_none", "tests/test_edge_cases.py::test_union_int_str", "tests/test_edge_cases.py::test_union_priority", "tests/test_edge_cases.py::test_typed_list", "tests/test_edge_cases.py::test_typed_set", "tests/test_edge_cases.py::test_dict_dict", "tests/test_edge_cases.py::test_typed_dict[value0-result0]", "tests/test_edge_cases.py::test_typed_dict[value1-result1]", "tests/test_edge_cases.py::test_typed_dict[value2-result2]", "tests/test_edge_cases.py::test_typed_dict_error[1-errors0]", "tests/test_edge_cases.py::test_typed_dict_error[value1-errors1]", "tests/test_edge_cases.py::test_typed_dict_error[value2-errors2]", "tests/test_edge_cases.py::test_dict_key_error", "tests/test_edge_cases.py::test_tuple", "tests/test_edge_cases.py::test_tuple_more", "tests/test_edge_cases.py::test_tuple_length_error", "tests/test_edge_cases.py::test_tuple_invalid", "tests/test_edge_cases.py::test_tuple_value_error", "tests/test_edge_cases.py::test_recursive_list", "tests/test_edge_cases.py::test_recursive_list_error", "tests/test_edge_cases.py::test_list_unions", "tests/test_edge_cases.py::test_recursive_lists", "tests/test_edge_cases.py::test_str_enum", "tests/test_edge_cases.py::test_any_dict", "tests/test_edge_cases.py::test_infer_alias", "tests/test_edge_cases.py::test_alias_error", "tests/test_edge_cases.py::test_annotation_config", "tests/test_edge_cases.py::test_success_values_include", "tests/test_edge_cases.py::test_include_exclude_default", "tests/test_edge_cases.py::test_advanced_exclude", "tests/test_edge_cases.py::test_advanced_value_inclide", "tests/test_edge_cases.py::test_advanced_value_exclude_include", "tests/test_edge_cases.py::test_field_set_ignore_extra", "tests/test_edge_cases.py::test_field_set_allow_extra", "tests/test_edge_cases.py::test_field_set_field_name", "tests/test_edge_cases.py::test_values_order", "tests/test_edge_cases.py::test_inheritance", "tests/test_edge_cases.py::test_invalid_type", "tests/test_edge_cases.py::test_valid_string_types[a", "tests/test_edge_cases.py::test_valid_string_types[some", "tests/test_edge_cases.py::test_valid_string_types[value2-foobar]", "tests/test_edge_cases.py::test_valid_string_types[123-123]", "tests/test_edge_cases.py::test_valid_string_types[123.45-123.45]", "tests/test_edge_cases.py::test_valid_string_types[value5-12.45]", "tests/test_edge_cases.py::test_valid_string_types[True-True]", "tests/test_edge_cases.py::test_valid_string_types[False-False]", "tests/test_edge_cases.py::test_valid_string_types[a10-a10]", "tests/test_edge_cases.py::test_valid_string_types[whatever-whatever]", "tests/test_edge_cases.py::test_invalid_string_types[value0-errors0]", "tests/test_edge_cases.py::test_invalid_string_types[value1-errors1]", "tests/test_edge_cases.py::test_inheritance_config", "tests/test_edge_cases.py::test_partial_inheritance_config", "tests/test_edge_cases.py::test_annotation_inheritance", "tests/test_edge_cases.py::test_string_none", "tests/test_edge_cases.py::test_alias_camel_case", "tests/test_edge_cases.py::test_get_field_info_inherit", "tests/test_edge_cases.py::test_return_errors_ok", "tests/test_edge_cases.py::test_return_errors_error", "tests/test_edge_cases.py::test_optional_required", "tests/test_edge_cases.py::test_invalid_validator", "tests/test_edge_cases.py::test_unable_to_infer", "tests/test_edge_cases.py::test_multiple_errors", "tests/test_edge_cases.py::test_pop_by_alias", "tests/test_edge_cases.py::test_validate_all", "tests/test_edge_cases.py::test_force_extra", "tests/test_edge_cases.py::test_illegal_extra_value", "tests/test_edge_cases.py::test_multiple_inheritance_config", "tests/test_edge_cases.py::test_submodel_different_type", "tests/test_edge_cases.py::test_self", "tests/test_edge_cases.py::test_self_recursive[BaseModel]", "tests/test_edge_cases.py::test_self_recursive[BaseSettings]", "tests/test_edge_cases.py::test_nested_init[BaseModel]", "tests/test_edge_cases.py::test_nested_init[BaseSettings]", "tests/test_edge_cases.py::test_values_attr_deprecation", "tests/test_edge_cases.py::test_init_inspection", "tests/test_edge_cases.py::test_type_on_annotation", "tests/test_edge_cases.py::test_assign_type", "tests/test_edge_cases.py::test_optional_subfields", "tests/test_edge_cases.py::test_not_optional_subfields", "tests/test_edge_cases.py::test_scheme_deprecated", "tests/test_edge_cases.py::test_population_by_alias", "tests/test_edge_cases.py::test_fields_deprecated" ]
{ "failed_lite_validators": [ "has_added_files", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2019-10-16 13:32:28+00:00
mit
4,917
pydantic__pydantic-909
diff --git a/docs/examples/constrained_types.py b/docs/examples/constrained_types.py --- a/docs/examples/constrained_types.py +++ b/docs/examples/constrained_types.py @@ -12,6 +12,7 @@ conint, conlist, constr, + Field, ) class Model(BaseModel): @@ -40,25 +41,4 @@ class Model(BaseModel): decimal_max_digits_and_places: condecimal(max_digits=2, decimal_places=2) mod_decimal: condecimal(multiple_of=Decimal('0.25')) -m = Model( - short_bytes=b'foo', - strip_bytes=b' bar', - short_str='foo', - regex_str='apple pie', - strip_str=' bar', - big_int=1001, - mod_int=155, - pos_int=1, - neg_int=-1, - big_float=1002.1, - mod_float=1.5, - pos_float=2.2, - neg_float=-2.3, - unit_interval=0.5, - short_list=[1, 2], - decimal_positive='21.12', - decimal_negative='-21.12', - decimal_max_digits_and_places='0.99', - mod_decimal='2.75', -) -print(m.dict()) + bigger_int: int = Field(..., gt=10000) diff --git a/docs/examples/unenforced_constraints.py b/docs/examples/unenforced_constraints.py new file mode 100644 --- /dev/null +++ b/docs/examples/unenforced_constraints.py @@ -0,0 +1,26 @@ +from pydantic import BaseModel, Field, PositiveInt + +try: + # this won't work since PositiveInt takes precedence over the + # constraints defined in Field meaning they're ignored + class Model(BaseModel): + foo: PositiveInt = Field(..., lt=10) +except ValueError as e: + print(e) + +# but you can set the schema attribute directly: +# (Note: here exclusiveMaximum will not be enforce) +class Model(BaseModel): + foo: PositiveInt = Field(..., exclusiveMaximum=10) + +print(Model.schema()) + +# if you find yourself needing this, an alternative is to declare +# the constraints in Field (or you could use conint()) +# here both constraints will be enforced: +class Model(BaseModel): + # Here both constraints will be applied and the schema + # will be generated correctly + foo: int = Field(..., gt=0, lt=10) + +print(Model.schema()) diff --git a/pydantic/fields.py b/pydantic/fields.py --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -23,7 +23,7 @@ from .error_wrappers import ErrorWrapper from .errors import NoneIsNotAllowedError from .types import Json, JsonWrapper -from .typing import AnyType, Callable, ForwardRef, display_as_type, is_literal_type +from .typing import AnyType, Callable, ForwardRef, NoneType, display_as_type, is_literal_type from .utils import PyObjectStr, Representation, lenient_issubclass, sequence_like from .validators import constant_validator, dict_validator, find_validators, validate_json @@ -33,7 +33,6 @@ Literal = None # type: ignore Required: Any = Ellipsis -NoneType = type(None) if TYPE_CHECKING: from .class_validators import ValidatorsList # noqa: F401 @@ -256,7 +255,7 @@ def infer( field_info = FieldInfo(value, **field_info_from_config) field_info.alias = field_info.alias or field_info_from_config.get('alias') required = value == Required - annotation = get_annotation_from_field_info(annotation, field_info) + annotation = get_annotation_from_field_info(annotation, field_info, name) return cls( name=name, type_=annotation, diff --git a/pydantic/schema.py b/pydantic/schema.py --- a/pydantic/schema.py +++ b/pydantic/schema.py @@ -6,12 +6,38 @@ from enum import Enum from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network from pathlib import Path -from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Sequence, Set, Tuple, Type, TypeVar, Union, cast +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + FrozenSet, + List, + Optional, + Sequence, + Set, + Tuple, + Type, + TypeVar, + Union, + cast, +) from uuid import UUID from .class_validators import ROOT_KEY from .color import Color -from .fields import SHAPE_LIST, SHAPE_MAPPING, SHAPE_SET, SHAPE_SINGLETON, SHAPE_TUPLE, FieldInfo, ModelField +from .fields import ( + SHAPE_FROZENSET, + SHAPE_LIST, + SHAPE_MAPPING, + SHAPE_SEQUENCE, + SHAPE_SET, + SHAPE_SINGLETON, + SHAPE_TUPLE, + SHAPE_TUPLE_ELLIPSIS, + FieldInfo, + ModelField, +) from .json import pydantic_encoder from .networks import AnyUrl, EmailStr, IPvAnyAddress, IPvAnyInterface, IPvAnyNetwork, NameEmail from .types import ( @@ -30,13 +56,21 @@ SecretBytes, SecretStr, StrictBool, + conbytes, condecimal, confloat, conint, - conlist, constr, ) -from .typing import Literal, is_callable_type, is_literal_type, is_new_type, literal_values, new_type_supertype +from .typing import ( + ForwardRef, + Literal, + is_callable_type, + is_literal_type, + is_new_type, + literal_values, + new_type_supertype, +) from .utils import lenient_issubclass if TYPE_CHECKING: @@ -352,14 +386,14 @@ def field_type_schema( definitions = {} nested_models: Set[str] = set() ref_prefix = ref_prefix or default_prefix - if field.shape == SHAPE_LIST: + if field.shape in {SHAPE_LIST, SHAPE_TUPLE_ELLIPSIS, SHAPE_SEQUENCE}: f_schema, f_definitions, f_nested_models = field_singleton_schema( field, by_alias=by_alias, model_name_map=model_name_map, ref_prefix=ref_prefix, known_models=known_models ) definitions.update(f_definitions) nested_models.update(f_nested_models) return {'type': 'array', 'items': f_schema}, definitions, nested_models - elif field.shape == SHAPE_SET: + elif field.shape in {SHAPE_SET, SHAPE_FROZENSET}: f_schema, f_definitions, f_nested_models = field_singleton_schema( field, by_alias=by_alias, model_name_map=model_name_map, ref_prefix=ref_prefix, known_models=known_models ) @@ -723,31 +757,64 @@ def encode_default(dft: Any) -> Any: _map_types_constraint: Dict[Any, Callable[..., type]] = {int: conint, float: confloat, Decimal: condecimal} -def get_annotation_from_field_info(annotation: Any, field_info: FieldInfo) -> Type[Any]: +def get_annotation_from_field_info(annotation: Any, field_info: FieldInfo, field_name: str) -> Type[Any]: # noqa: C901 """ Get an annotation with validation implemented for numbers and strings based on the field_info. :param annotation: an annotation from a field specification, as ``str``, ``ConstrainedStr`` :param field_info: an instance of FieldInfo, possibly with declarations for validations and JSON Schema + :param field_name: name of the field for use in error messages :return: the same ``annotation`` if unmodified or a new annotation with validation in place """ - if isinstance(annotation, type): + constraints = {f for f in validation_attribute_to_schema_keyword if getattr(field_info, f) is not None} + if not constraints: + return annotation + used_constraints: Set[str] = set() + + def go(type_: Any) -> Type[Any]: + if is_literal_type(annotation) or isinstance(type_, ForwardRef) or lenient_issubclass(type_, ConstrainedList): + return type_ + origin = getattr(type_, '__origin__', None) + if origin is not None: + args: Tuple[Any, ...] = type_.__args__ + if any(isinstance(a, ForwardRef) for a in args): + # forward refs cause infinite recursion below + return type_ + + if origin is Union: + return Union[tuple(go(a) for a in args)] + + # conlist isn't working properly with schema #913 + # if issubclass(origin, List): + # used_constraints.update({'min_items', 'max_items'}) + # return conlist(go(args[0]), min_items=field_info.min_items, max_items=field_info.max_items) + + for t in (Tuple, List, Set, FrozenSet, Sequence): + if issubclass(origin, t): # type: ignore + return t[tuple(go(a) for a in args)] # type: ignore + + if issubclass(origin, Dict): + return Dict[args[0], go(args[1])] # type: ignore + attrs: Optional[Tuple[str, ...]] = None constraint_func: Optional[Callable[..., type]] = None - if issubclass(annotation, str) and not issubclass(annotation, (EmailStr, AnyUrl, ConstrainedStr)): - attrs = ('max_length', 'min_length', 'regex') - constraint_func = constr - elif lenient_issubclass(annotation, numeric_types) and not issubclass( - annotation, (ConstrainedInt, ConstrainedFloat, ConstrainedDecimal, ConstrainedList, bool) - ): - # Is numeric type - attrs = ('gt', 'lt', 'ge', 'le', 'multiple_of') - numeric_type = next(t for t in numeric_types if issubclass(annotation, t)) # pragma: no branch - constraint_func = _map_types_constraint[numeric_type] - elif issubclass(annotation, ConstrainedList): - attrs = ('min_items', 'max_items') - constraint_func = conlist + if isinstance(type_, type): + if issubclass(type_, str) and not issubclass(type_, (EmailStr, AnyUrl, ConstrainedStr)): + attrs = ('max_length', 'min_length', 'regex') + constraint_func = constr + elif issubclass(type_, bytes): + attrs = ('max_length', 'min_length', 'regex') + constraint_func = conbytes + elif issubclass(type_, numeric_types) and not issubclass( + type_, (ConstrainedInt, ConstrainedFloat, ConstrainedDecimal, ConstrainedList, bool) + ): + # Is numeric type + attrs = ('gt', 'lt', 'ge', 'le', 'multiple_of') + numeric_type = next(t for t in numeric_types if issubclass(type_, t)) # pragma: no branch + constraint_func = _map_types_constraint[numeric_type] + if attrs: + used_constraints.update(set(attrs)) kwargs = { attr_name: attr for attr_name, attr in ((attr_name, getattr(field_info, attr_name)) for attr_name in attrs) @@ -756,7 +823,19 @@ def get_annotation_from_field_info(annotation: Any, field_info: FieldInfo) -> Ty if kwargs: constraint_func = cast(Callable[..., type], constraint_func) return constraint_func(**kwargs) - return annotation + return type_ + + ans = go(annotation) + + unused_constraints = constraints - used_constraints + if unused_constraints: + raise ValueError( + f'On field "{field_name}" the following field constraints are set but not enforced: ' + f'{", ".join(unused_constraints)}. ' + f'\nFor more details see https://pydantic-docs.helpmanual.io/usage/schema/#unenforced-field-constraints' + ) + + return ans class SkipField(Exception): diff --git a/pydantic/typing.py b/pydantic/typing.py --- a/pydantic/typing.py +++ b/pydantic/typing.py @@ -72,6 +72,7 @@ def evaluate_forwardref(type_, globalns, localns): # type: ignore 'Callable', 'AnyCallable', 'AnyType', + 'NoneType', 'display_as_type', 'resolve_annotations', 'is_callable_type', @@ -96,6 +97,7 @@ def evaluate_forwardref(type_, globalns, localns): # type: ignore AnyType = Type[Any] +NoneType = type(None) def display_as_type(v: AnyType) -> str:
pydantic/pydantic
78921da35353c9d875c01acde0dc2c6986810ab5
@vdwees I've traced the source of this issue to [this line](https://github.com/samuelcolvin/pydantic/blob/5015a7e48bc869adf99b78eb38075951549e9ea7/pydantic/schema.py#L833). The problem here is that `Optional[X]` is not considered by python to be a `type`. I definitely don't think the way it is currently handled is ideal, but it might be somewhat involved to fix this properly. For now, here's a workaround: ```python from pydantic import BaseModel, Schema, ConstrainedInt from typing import Optional class ConInt3(ConstrainedInt): ge = 3 class MyModel(BaseModel): my_int: Optional[ConInt3] = Schema(...) print(MyModel.schema()) # {'title': 'MyModel', 'type': 'object', 'properties': {'my_int': {'title': 'My_Int', 'minimum': 3, 'type': 'integer'}}} print(MyModel(my_int=2)) """ pydantic.error_wrappers.ValidationError: 2 validation errors for MyModel my_int ensure this value is greater than or equal to 3 (type=value_error.number.not_ge; limit_value=3) my_int value is not none (type=type_error.none.allowed) """ ``` ------- @samuelcolvin I'm not sure whether it would be better to modify the `get_annotation_from_schema` function to deal with the whole `typing` introspection rigamarole (like in, e.g., `Field._populate_sub_fields`), or to just require more careful handling (like in the "workaround" I provided above). Thoughts? Thanks for reporting. Definitely looks like a bug, I'll look into in and see what I can do. Firstly thank you both for your contributions to this library, and +1 for resolving this issue if possible. @dmontagu I have tried your workaround but I believe it has uncovered a second bug - if you look at your code snippet the schema now raises two issues when I would expect one (i.e. I assume it should not complain that the optional value is not none). For a simpler example (using Pydantic 0.32.2)on MacOSX: ``` >>> from pydantic import BaseModel, PositiveInt >>> from typing import Optional >>> class ExampleModel(BaseModel): ... foo: Optional[PositiveInt] ... >>> ExampleModel(foo=0) pydantic.error_wrappers.ValidationError: 2 validation errors for ExampleModel foo ensure this value is greater than 0 (type=value_error.number.not_gt; limit_value=0) foo value is not none (type=type_error.none.allowed) ``` hi @dannymilsom I'm not clear what second bug you've uncovered? Please can you elaborate. @dannymilsom what's happening is that it's showing you, for each option in the union, why it can't be that option. The first option was PositiveInt, which fails. The second is None, which also fails (obviously). This is because `Optional[PositiveInt]` is basically the same as `Union[PositiveInt, None]`. @samuelcolvin I feel like maybe some of this stuff has changed in v1 anyway; not sure whether the error messages still look the same? Either way, I don't think this is a buggy error message, just a slightly confusing one. @dmontagu yes, you're right on all: it's not an error and it's clearer in v1. It's also not related in anyway to this issue.
diff --git a/tests/test_edge_cases.py b/tests/test_edge_cases.py --- a/tests/test_edge_cases.py +++ b/tests/test_edge_cases.py @@ -19,7 +19,7 @@ validate_model, validator, ) -from pydantic.fields import Schema +from pydantic.fields import Field, Schema def test_str_bytes(): @@ -1122,6 +1122,22 @@ def alias_generator(cls, f_name): assert Child.__fields__['x'].alias == 'x2' +def test_optional_field_constraints(): + class MyModel(BaseModel): + my_int: Optional[int] = Field(..., ge=3) + + with pytest.raises(ValidationError) as exc_info: + MyModel(my_int=2) + assert exc_info.value.errors() == [ + { + 'loc': ('my_int',), + 'msg': 'ensure this value is greater than or equal to 3', + 'type': 'value_error.number.not_ge', + 'ctx': {'limit_value': 3}, + } + ] + + def test_field_str_shape(): class Model(BaseModel): a: List[int] diff --git a/tests/test_forward_ref.py b/tests/test_forward_ref.py --- a/tests/test_forward_ref.py +++ b/tests/test_forward_ref.py @@ -419,3 +419,23 @@ class Account(BaseModel): }, }, } + + +def test_forward_ref_with_field(create_module): + create_module( + """ +from typing import List +from pydantic import BaseModel, Field +from pydantic.typing import ForwardRef + +Foo = ForwardRef('Foo') + +try: + class Foo(BaseModel): + c: List[Foo] = Field(..., gt=0) +except ValueError: + pass +else: + raise AssertionError('error not raised') + """ + ) diff --git a/tests/test_schema.py b/tests/test_schema.py --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -11,7 +11,7 @@ import pytest -from pydantic import BaseModel, Extra, Field, ValidationError, validator +from pydantic import BaseModel, Extra, Field, ValidationError, conlist, validator from pydantic.color import Color from pydantic.networks import AnyUrl, EmailStr, IPvAnyAddress, IPvAnyInterface, IPvAnyNetwork, NameEmail, stricturl from pydantic.schema import ( @@ -1092,7 +1092,7 @@ class UserModel(BaseModel): 'kwargs,type_,expected_extra', [ ({'max_length': 5}, str, {'type': 'string', 'maxLength': 5}), - ({'max_length': 5}, constr(max_length=6), {'type': 'string', 'maxLength': 6}), + ({}, constr(max_length=6), {'type': 'string', 'maxLength': 6}), ({'min_length': 2}, str, {'type': 'string', 'minLength': 2}), ({'max_length': 5}, bytes, {'type': 'string', 'maxLength': 5, 'format': 'binary'}), ({'regex': '^foo$'}, str, {'type': 'string', 'pattern': '^foo$'}), @@ -1128,41 +1128,35 @@ class Foo(BaseModel): @pytest.mark.parametrize( - 'kwargs,type_,expected', + 'kwargs,type_', [ - ({'max_length': 5}, int, {'type': 'integer'}), - ({'min_length': 2}, float, {'type': 'number'}), - ({'max_length': 5}, Decimal, {'type': 'number'}), - ({'regex': '^foo$'}, int, {'type': 'integer'}), - ({'gt': 2}, str, {'type': 'string'}), - ({'lt': 5}, bytes, {'type': 'string', 'format': 'binary'}), - ({'ge': 2}, str, {'type': 'string'}), - ({'le': 5}, bool, {'type': 'boolean'}), + ({'max_length': 5}, int), + ({'min_length': 2}, float), + ({'max_length': 5}, Decimal), + ({'regex': '^foo$'}, int), + ({'gt': 2}, str), + ({'lt': 5}, bytes), + ({'ge': 2}, str), + ({'le': 5}, bool), + ({'gt': 0}, Callable), + ({'gt': 0}, Callable[[int], int]), + ({'gt': 0}, conlist(int, min_items=4)), ], ) -def test_not_constraints_schema(kwargs, type_, expected): - class Foo(BaseModel): - a: type_ = Field('foo', title='A title', description='A description', **kwargs) - - base_schema = { - 'title': 'Foo', - 'type': 'object', - 'properties': {'a': {'title': 'A title', 'description': 'A description', 'default': 'foo'}}, - } +def test_unenforced_constraints_schema(kwargs, type_): + with pytest.raises(ValueError, match='On field "a" the following field constraints are set but not enforced'): - base_schema['properties']['a'].update(expected) - assert Foo.schema() == base_schema + class Foo(BaseModel): + a: type_ = Field('foo', title='A title', description='A description', **kwargs) @pytest.mark.parametrize( 'kwargs,type_,value', [ ({'max_length': 5}, str, 'foo'), - ({'max_length': 5}, constr(max_length=6), 'foo'), ({'min_length': 2}, str, 'foo'), ({'max_length': 5}, bytes, b'foo'), ({'regex': '^foo$'}, str, 'foo'), - ({'max_length': 5}, bool, True), ({'gt': 2}, int, 3), ({'lt': 5}, int, 3), ({'ge': 2}, int, 3), @@ -1508,3 +1502,95 @@ class Config: 'required': ['a'], 'additionalProperties': False, } + + [email protected]( + 'annotation,kwargs,field_schema', + [ + (int, dict(gt=0), {'title': 'A', 'exclusiveMinimum': 0, 'type': 'integer'}), + (Optional[int], dict(gt=0), {'title': 'A', 'exclusiveMinimum': 0, 'type': 'integer'}), + ( + Tuple[int, ...], + dict(gt=0), + {'title': 'A', 'exclusiveMinimum': 0, 'type': 'array', 'items': {'exclusiveMinimum': 0, 'type': 'integer'}}, + ), + ( + Tuple[int, int, int], + dict(gt=0), + { + 'title': 'A', + 'type': 'array', + 'items': [ + {'exclusiveMinimum': 0, 'type': 'integer'}, + {'exclusiveMinimum': 0, 'type': 'integer'}, + {'exclusiveMinimum': 0, 'type': 'integer'}, + ], + }, + ), + ( + Union[int, float], + dict(gt=0), + { + 'title': 'A', + 'anyOf': [{'exclusiveMinimum': 0, 'type': 'integer'}, {'exclusiveMinimum': 0, 'type': 'number'}], + }, + ), + ( + List[int], + dict(gt=0), + {'title': 'A', 'exclusiveMinimum': 0, 'type': 'array', 'items': {'exclusiveMinimum': 0, 'type': 'integer'}}, + ), + ( + Dict[str, int], + dict(gt=0), + { + 'title': 'A', + 'exclusiveMinimum': 0, + 'type': 'object', + 'additionalProperties': {'exclusiveMinimum': 0, 'type': 'integer'}, + }, + ), + ( + Union[str, int], + dict(gt=0, max_length=5), + {'title': 'A', 'anyOf': [{'maxLength': 5, 'type': 'string'}, {'exclusiveMinimum': 0, 'type': 'integer'}]}, + ), + ], +) +def test_enforced_constraints(annotation, kwargs, field_schema): + class Model(BaseModel): + a: annotation = Field(..., **kwargs) + + schema = Model.schema() + # debug(schema['properties']['a']) + assert schema['properties']['a'] == field_schema + + +def test_real_vs_phony_constraints(): + class Model1(BaseModel): + foo: int = Field(..., gt=123) + + class Config: + title = 'Test Model' + + class Model2(BaseModel): + foo: int = Field(..., exclusiveMinimum=123) + + class Config: + title = 'Test Model' + + with pytest.raises(ValidationError, match='ensure this value is greater than 123'): + Model1(foo=122) + + assert Model2(foo=122).dict() == {'foo': 122} + + assert ( + Model1.schema() + == Model2.schema() + == { + 'title': 'Test Model', + 'type': 'object', + 'properties': {'foo': {'title': 'Foo', 'exclusiveMinimum': 123, 'type': 'integer'}}, + 'required': ['foo'], + } + )
Optional fields loose some validation # Bug * OS: **Ubuntu 18.04** * Python version: **3.7.3** * Pydantic versions: **0.30(pypi), 1.0a1 (master)** Example code: ```py from pydantic import BaseModel, Schema from typing import Optional class MyModel(BaseModel): my_int: Optional[int] = Schema(..., ge=3) MyModel(my_int=2) ``` I would expect: ``` pydantic.error_wrappers.ValidationError: 1 validation error my_int ensure this value is greater than or equal to 3 (type=value_error.number.not_ge; limit_value=3) ``` but `MyModel` gets instantiated just fine. If I make `my_int` not optional, the behaviour is as expected.
0.0
78921da35353c9d875c01acde0dc2c6986810ab5
[ "tests/test_edge_cases.py::test_optional_field_constraints", "tests/test_forward_ref.py::test_forward_ref_with_field", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs0-int]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs1-float]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs2-Decimal]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs3-int]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs4-str]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs5-bytes]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs6-str]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs7-bool]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs9-type_9]", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs10-ConstrainedListValue]", "tests/test_schema.py::test_enforced_constraints[annotation2-kwargs2-field_schema2]", "tests/test_schema.py::test_enforced_constraints[annotation3-kwargs3-field_schema3]", "tests/test_schema.py::test_enforced_constraints[annotation4-kwargs4-field_schema4]", "tests/test_schema.py::test_enforced_constraints[annotation5-kwargs5-field_schema5]", "tests/test_schema.py::test_enforced_constraints[annotation6-kwargs6-field_schema6]", "tests/test_schema.py::test_enforced_constraints[annotation7-kwargs7-field_schema7]" ]
[ "tests/test_edge_cases.py::test_str_bytes", "tests/test_edge_cases.py::test_str_bytes_none", "tests/test_edge_cases.py::test_union_int_str", "tests/test_edge_cases.py::test_union_priority", "tests/test_edge_cases.py::test_typed_list", "tests/test_edge_cases.py::test_typed_set", "tests/test_edge_cases.py::test_dict_dict", "tests/test_edge_cases.py::test_typed_dict[value0-result0]", "tests/test_edge_cases.py::test_typed_dict[value1-result1]", "tests/test_edge_cases.py::test_typed_dict[value2-result2]", "tests/test_edge_cases.py::test_typed_dict_error[1-errors0]", "tests/test_edge_cases.py::test_typed_dict_error[value1-errors1]", "tests/test_edge_cases.py::test_typed_dict_error[value2-errors2]", "tests/test_edge_cases.py::test_dict_key_error", "tests/test_edge_cases.py::test_tuple", "tests/test_edge_cases.py::test_tuple_more", "tests/test_edge_cases.py::test_tuple_length_error", "tests/test_edge_cases.py::test_tuple_invalid", "tests/test_edge_cases.py::test_tuple_value_error", "tests/test_edge_cases.py::test_recursive_list", "tests/test_edge_cases.py::test_recursive_list_error", "tests/test_edge_cases.py::test_list_unions", "tests/test_edge_cases.py::test_recursive_lists", "tests/test_edge_cases.py::test_str_enum", "tests/test_edge_cases.py::test_any_dict", "tests/test_edge_cases.py::test_infer_alias", "tests/test_edge_cases.py::test_alias_error", "tests/test_edge_cases.py::test_annotation_config", "tests/test_edge_cases.py::test_success_values_include", "tests/test_edge_cases.py::test_include_exclude_default", "tests/test_edge_cases.py::test_advanced_exclude", "tests/test_edge_cases.py::test_advanced_value_inclide", "tests/test_edge_cases.py::test_advanced_value_exclude_include", "tests/test_edge_cases.py::test_field_set_ignore_extra", "tests/test_edge_cases.py::test_field_set_allow_extra", "tests/test_edge_cases.py::test_field_set_field_name", "tests/test_edge_cases.py::test_values_order", "tests/test_edge_cases.py::test_inheritance", "tests/test_edge_cases.py::test_invalid_type", "tests/test_edge_cases.py::test_valid_string_types[a", "tests/test_edge_cases.py::test_valid_string_types[some", "tests/test_edge_cases.py::test_valid_string_types[value2-foobar]", "tests/test_edge_cases.py::test_valid_string_types[123-123]", "tests/test_edge_cases.py::test_valid_string_types[123.45-123.45]", "tests/test_edge_cases.py::test_valid_string_types[value5-12.45]", "tests/test_edge_cases.py::test_valid_string_types[True-True]", "tests/test_edge_cases.py::test_valid_string_types[False-False]", "tests/test_edge_cases.py::test_valid_string_types[a10-a10]", "tests/test_edge_cases.py::test_valid_string_types[whatever-whatever]", "tests/test_edge_cases.py::test_invalid_string_types[value0-errors0]", "tests/test_edge_cases.py::test_invalid_string_types[value1-errors1]", "tests/test_edge_cases.py::test_inheritance_config", "tests/test_edge_cases.py::test_partial_inheritance_config", "tests/test_edge_cases.py::test_annotation_inheritance", "tests/test_edge_cases.py::test_string_none", "tests/test_edge_cases.py::test_alias_camel_case", "tests/test_edge_cases.py::test_get_field_info_inherit", "tests/test_edge_cases.py::test_return_errors_ok", "tests/test_edge_cases.py::test_return_errors_error", "tests/test_edge_cases.py::test_optional_required", "tests/test_edge_cases.py::test_invalid_validator", "tests/test_edge_cases.py::test_unable_to_infer", "tests/test_edge_cases.py::test_multiple_errors", "tests/test_edge_cases.py::test_pop_by_alias", "tests/test_edge_cases.py::test_validate_all", "tests/test_edge_cases.py::test_force_extra", "tests/test_edge_cases.py::test_illegal_extra_value", "tests/test_edge_cases.py::test_multiple_inheritance_config", "tests/test_edge_cases.py::test_submodel_different_type", "tests/test_edge_cases.py::test_self", "tests/test_edge_cases.py::test_self_recursive[BaseModel]", "tests/test_edge_cases.py::test_self_recursive[BaseSettings]", "tests/test_edge_cases.py::test_nested_init[BaseModel]", "tests/test_edge_cases.py::test_nested_init[BaseSettings]", "tests/test_edge_cases.py::test_values_attr_deprecation", "tests/test_edge_cases.py::test_init_inspection", "tests/test_edge_cases.py::test_type_on_annotation", "tests/test_edge_cases.py::test_assign_type", "tests/test_edge_cases.py::test_optional_subfields", "tests/test_edge_cases.py::test_not_optional_subfields", "tests/test_edge_cases.py::test_scheme_deprecated", "tests/test_edge_cases.py::test_population_by_alias", "tests/test_edge_cases.py::test_fields_deprecated", "tests/test_edge_cases.py::test_alias_child_precedence", "tests/test_edge_cases.py::test_alias_generator_parent", "tests/test_edge_cases.py::test_field_str_shape", "tests/test_edge_cases.py::test_field_type_display[int-int]", "tests/test_edge_cases.py::test_field_type_display[type_1-Optional[int]]", "tests/test_edge_cases.py::test_field_type_display[type_2-Union[NoneType,", "tests/test_edge_cases.py::test_field_type_display[type_3-Union[int,", "tests/test_edge_cases.py::test_field_type_display[type_4-List[int]]", "tests/test_edge_cases.py::test_field_type_display[type_5-Tuple[int,", "tests/test_edge_cases.py::test_field_type_display[type_6-Union[List[int],", "tests/test_edge_cases.py::test_field_type_display[type_7-List[Tuple[int,", "tests/test_edge_cases.py::test_field_type_display[type_8-Mapping[int,", "tests/test_edge_cases.py::test_field_type_display[type_9-Tuple[int,", "tests/test_edge_cases.py::test_field_type_display[type_10-Optional[List[int]]]", "tests/test_forward_ref.py::test_postponed_annotations", "tests/test_forward_ref.py::test_postponed_annotations_optional", "tests/test_forward_ref.py::test_basic_forward_ref", "tests/test_forward_ref.py::test_missing_update_forward_refs", "tests/test_forward_ref.py::test_forward_ref_dataclass", "tests/test_forward_ref.py::test_forward_ref_dataclass_with_future_annotations", "tests/test_schema.py::test_key", "tests/test_schema.py::test_by_alias", "tests/test_schema.py::test_sub_model", "tests/test_schema.py::test_schema_class", "tests/test_schema.py::test_schema_repr", "tests/test_schema.py::test_schema_class_by_alias", "tests/test_schema.py::test_choices", "tests/test_schema.py::test_json_schema", "tests/test_schema.py::test_list_sub_model", "tests/test_schema.py::test_optional", "tests/test_schema.py::test_any", "tests/test_schema.py::test_set", "tests/test_schema.py::test_const_str", "tests/test_schema.py::test_const_false", "tests/test_schema.py::test_tuple[tuple-expected_schema0]", "tests/test_schema.py::test_tuple[field_type1-expected_schema1]", "tests/test_schema.py::test_tuple[field_type2-expected_schema2]", "tests/test_schema.py::test_bool", "tests/test_schema.py::test_strict_bool", "tests/test_schema.py::test_dict", "tests/test_schema.py::test_list", "tests/test_schema.py::test_list_union_dict[field_type0-expected_schema0]", "tests/test_schema.py::test_list_union_dict[field_type1-expected_schema1]", "tests/test_schema.py::test_list_union_dict[field_type2-expected_schema2]", "tests/test_schema.py::test_list_union_dict[field_type3-expected_schema3]", "tests/test_schema.py::test_list_union_dict[field_type4-expected_schema4]", "tests/test_schema.py::test_date_types[datetime-expected_schema0]", "tests/test_schema.py::test_date_types[date-expected_schema1]", "tests/test_schema.py::test_date_types[time-expected_schema2]", "tests/test_schema.py::test_date_types[timedelta-expected_schema3]", "tests/test_schema.py::test_str_basic_types[field_type0-expected_schema0]", "tests/test_schema.py::test_str_basic_types[field_type1-expected_schema1]", "tests/test_schema.py::test_str_basic_types[field_type2-expected_schema2]", "tests/test_schema.py::test_str_basic_types[field_type3-expected_schema3]", "tests/test_schema.py::test_str_constrained_types[StrictStr-expected_schema0]", "tests/test_schema.py::test_str_constrained_types[ConstrainedStr-expected_schema1]", "tests/test_schema.py::test_str_constrained_types[ConstrainedStrValue-expected_schema2]", "tests/test_schema.py::test_special_str_types[AnyUrl-expected_schema0]", "tests/test_schema.py::test_special_str_types[UrlValue-expected_schema1]", "tests/test_schema.py::test_email_str_types[EmailStr-email]", "tests/test_schema.py::test_email_str_types[NameEmail-name-email]", "tests/test_schema.py::test_secret_types[SecretBytes-string]", "tests/test_schema.py::test_secret_types[SecretStr-string]", "tests/test_schema.py::test_special_int_types[ConstrainedInt-expected_schema0]", "tests/test_schema.py::test_special_int_types[ConstrainedIntValue-expected_schema1]", "tests/test_schema.py::test_special_int_types[ConstrainedIntValue-expected_schema2]", "tests/test_schema.py::test_special_int_types[ConstrainedIntValue-expected_schema3]", "tests/test_schema.py::test_special_int_types[PositiveInt-expected_schema4]", "tests/test_schema.py::test_special_int_types[NegativeInt-expected_schema5]", "tests/test_schema.py::test_special_float_types[ConstrainedFloat-expected_schema0]", "tests/test_schema.py::test_special_float_types[ConstrainedFloatValue-expected_schema1]", "tests/test_schema.py::test_special_float_types[ConstrainedFloatValue-expected_schema2]", "tests/test_schema.py::test_special_float_types[ConstrainedFloatValue-expected_schema3]", "tests/test_schema.py::test_special_float_types[PositiveFloat-expected_schema4]", "tests/test_schema.py::test_special_float_types[NegativeFloat-expected_schema5]", "tests/test_schema.py::test_special_float_types[ConstrainedDecimal-expected_schema6]", "tests/test_schema.py::test_special_float_types[ConstrainedDecimalValue-expected_schema7]", "tests/test_schema.py::test_special_float_types[ConstrainedDecimalValue-expected_schema8]", "tests/test_schema.py::test_special_float_types[ConstrainedDecimalValue-expected_schema9]", "tests/test_schema.py::test_uuid_types[UUID-uuid]", "tests/test_schema.py::test_uuid_types[UUID1-uuid1]", "tests/test_schema.py::test_uuid_types[UUID3-uuid3]", "tests/test_schema.py::test_uuid_types[UUID4-uuid4]", "tests/test_schema.py::test_uuid_types[UUID5-uuid5]", "tests/test_schema.py::test_path_types[FilePath-file-path]", "tests/test_schema.py::test_path_types[DirectoryPath-directory-path]", "tests/test_schema.py::test_path_types[Path-path]", "tests/test_schema.py::test_json_type", "tests/test_schema.py::test_ipv4address_type", "tests/test_schema.py::test_ipv6address_type", "tests/test_schema.py::test_ipvanyaddress_type", "tests/test_schema.py::test_ipv4interface_type", "tests/test_schema.py::test_ipv6interface_type", "tests/test_schema.py::test_ipvanyinterface_type", "tests/test_schema.py::test_ipv4network_type", "tests/test_schema.py::test_ipv6network_type", "tests/test_schema.py::test_ipvanynetwork_type", "tests/test_schema.py::test_callable_type[annotation0]", "tests/test_schema.py::test_callable_type[annotation1]", "tests/test_schema.py::test_error_non_supported_types", "tests/test_schema.py::test_flat_models_unique_models", "tests/test_schema.py::test_flat_models_with_submodels", "tests/test_schema.py::test_flat_models_with_submodels_from_sequence", "tests/test_schema.py::test_model_name_maps", "tests/test_schema.py::test_schema_overrides", "tests/test_schema.py::test_schema_from_models", "tests/test_schema.py::test_schema_with_ref_prefix", "tests/test_schema.py::test_schema_no_definitions", "tests/test_schema.py::test_list_default", "tests/test_schema.py::test_dict_default", "tests/test_schema.py::test_constraints_schema[kwargs0-str-expected_extra0]", "tests/test_schema.py::test_constraints_schema[kwargs1-ConstrainedStrValue-expected_extra1]", "tests/test_schema.py::test_constraints_schema[kwargs2-str-expected_extra2]", "tests/test_schema.py::test_constraints_schema[kwargs3-bytes-expected_extra3]", "tests/test_schema.py::test_constraints_schema[kwargs4-str-expected_extra4]", "tests/test_schema.py::test_constraints_schema[kwargs5-int-expected_extra5]", "tests/test_schema.py::test_constraints_schema[kwargs6-int-expected_extra6]", "tests/test_schema.py::test_constraints_schema[kwargs7-int-expected_extra7]", "tests/test_schema.py::test_constraints_schema[kwargs8-int-expected_extra8]", "tests/test_schema.py::test_constraints_schema[kwargs9-int-expected_extra9]", "tests/test_schema.py::test_constraints_schema[kwargs10-float-expected_extra10]", "tests/test_schema.py::test_constraints_schema[kwargs11-float-expected_extra11]", "tests/test_schema.py::test_constraints_schema[kwargs12-float-expected_extra12]", "tests/test_schema.py::test_constraints_schema[kwargs13-float-expected_extra13]", "tests/test_schema.py::test_constraints_schema[kwargs14-float-expected_extra14]", "tests/test_schema.py::test_constraints_schema[kwargs15-Decimal-expected_extra15]", "tests/test_schema.py::test_constraints_schema[kwargs16-Decimal-expected_extra16]", "tests/test_schema.py::test_constraints_schema[kwargs17-Decimal-expected_extra17]", "tests/test_schema.py::test_constraints_schema[kwargs18-Decimal-expected_extra18]", "tests/test_schema.py::test_constraints_schema[kwargs19-Decimal-expected_extra19]", "tests/test_schema.py::test_constraints_schema_validation[kwargs0-str-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs1-str-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs2-bytes-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs3-str-foo]", "tests/test_schema.py::test_constraints_schema_validation[kwargs4-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs5-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs6-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs7-int-2]", "tests/test_schema.py::test_constraints_schema_validation[kwargs8-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs9-int-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs10-int-5]", "tests/test_schema.py::test_constraints_schema_validation[kwargs11-float-3.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs12-float-2.1]", "tests/test_schema.py::test_constraints_schema_validation[kwargs13-float-3.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs14-float-4.9]", "tests/test_schema.py::test_constraints_schema_validation[kwargs15-float-3.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs16-float-2.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs17-float-3.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs18-float-5.0]", "tests/test_schema.py::test_constraints_schema_validation[kwargs19-float-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs20-float-3]", "tests/test_schema.py::test_constraints_schema_validation[kwargs21-Decimal-value21]", "tests/test_schema.py::test_constraints_schema_validation[kwargs22-Decimal-value22]", "tests/test_schema.py::test_constraints_schema_validation[kwargs23-Decimal-value23]", "tests/test_schema.py::test_constraints_schema_validation[kwargs24-Decimal-value24]", "tests/test_schema.py::test_constraints_schema_validation[kwargs25-Decimal-value25]", "tests/test_schema.py::test_constraints_schema_validation[kwargs26-Decimal-value26]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs0-str-foobar]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs1-str-f]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs2-str-bar]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs3-int-2]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs4-int-5]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs5-int-1]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs6-int-6]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs7-float-2.0]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs8-float-5.0]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs9-float-1.9]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs10-float-5.1]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs11-Decimal-value11]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs12-Decimal-value12]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs13-Decimal-value13]", "tests/test_schema.py::test_constraints_schema_validation_raises[kwargs14-Decimal-value14]", "tests/test_schema.py::test_schema_kwargs", "tests/test_schema.py::test_schema_dict_constr", "tests/test_schema.py::test_bytes_constrained_types[ConstrainedBytes-expected_schema0]", "tests/test_schema.py::test_bytes_constrained_types[ConstrainedBytesValue-expected_schema1]", "tests/test_schema.py::test_optional_dict", "tests/test_schema.py::test_optional_validator", "tests/test_schema.py::test_field_with_validator", "tests/test_schema.py::test_known_model_optimization", "tests/test_schema.py::test_root", "tests/test_schema.py::test_root_list", "tests/test_schema.py::test_root_nested_model", "tests/test_schema.py::test_new_type_schema", "tests/test_schema.py::test_literal_schema", "tests/test_schema.py::test_color_type", "tests/test_schema.py::test_model_with_schema_extra", "tests/test_schema.py::test_model_with_extra_forbidden", "tests/test_schema.py::test_enforced_constraints[int-kwargs0-field_schema0]", "tests/test_schema.py::test_enforced_constraints[annotation1-kwargs1-field_schema1]", "tests/test_schema.py::test_real_vs_phony_constraints" ]
{ "failed_lite_validators": [ "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-10-17 11:08:39+00:00
mit
4,918
pydantic__pydantic-915
diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -231,6 +231,7 @@ def __new__(mcs, name, bases, namespace, **kwargs): # noqa C901 new_namespace = { '__config__': config, '__fields__': fields, + '__field_defaults__': {n: f.default for n, f in fields.items() if not f.required}, '__validators__': vg.validators, '__pre_root_validators__': pre_root_validators + pre_rv_new, '__post_root_validators__': post_root_validators + post_rv_new, @@ -252,6 +253,7 @@ class BaseModel(metaclass=ModelMetaclass): if TYPE_CHECKING: # populated by the metaclass, defined here to help IDEs only __fields__: Dict[str, ModelField] = {} + __field_defaults__: Dict[str, Any] = {} __validators__: Dict[str, AnyCallable] = {} __pre_root_validators__: List[AnyCallable] __post_root_validators__: List[AnyCallable] @@ -303,15 +305,23 @@ def dict( include: Union['SetIntStr', 'DictIntStrAny'] = None, exclude: Union['SetIntStr', 'DictIntStrAny'] = None, by_alias: bool = False, - skip_defaults: bool = False, + skip_defaults: bool = None, + exclude_unset: bool = False, + exclude_defaults: bool = False, ) -> 'DictStrAny': """ Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. """ + if skip_defaults is not None: + warnings.warn( + f'{self.__class__.__name__}.dict(): "skip_defaults" is deprecated and replaced by "exclude_unset"', + DeprecationWarning, + ) + exclude_unset = skip_defaults get_key = self._get_key_factory(by_alias) get_key = partial(get_key, self.__fields__) - allowed_keys = self._calculate_keys(include=include, exclude=exclude, skip_defaults=skip_defaults) + allowed_keys = self._calculate_keys(include=include, exclude=exclude, exclude_unset=exclude_unset) return { get_key(k): v for k, v in self._iter( @@ -320,7 +330,8 @@ def dict( allowed_keys=allowed_keys, include=include, exclude=exclude, - skip_defaults=skip_defaults, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, ) } @@ -336,7 +347,9 @@ def json( include: Union['SetIntStr', 'DictIntStrAny'] = None, exclude: Union['SetIntStr', 'DictIntStrAny'] = None, by_alias: bool = False, - skip_defaults: bool = False, + skip_defaults: bool = None, + exclude_unset: bool = False, + exclude_defaults: bool = False, encoder: Optional[Callable[[Any], Any]] = None, **dumps_kwargs: Any, ) -> str: @@ -345,8 +358,20 @@ def json( `encoder` is an optional function to supply as `default` to json.dumps(), other arguments as per `json.dumps()`. """ + if skip_defaults is not None: + warnings.warn( + f'{self.__class__.__name__}.json(): "skip_defaults" is deprecated and replaced by "exclude_unset"', + DeprecationWarning, + ) + exclude_unset = skip_defaults encoder = cast(Callable[[Any], Any], encoder or self.__json_encoder__) - data = self.dict(include=include, exclude=exclude, by_alias=by_alias, skip_defaults=skip_defaults) + data = self.dict( + include=include, + exclude=exclude, + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + ) if self.__custom_root_type__: data = data[ROOT_KEY] return self.__config__.json_dumps(data, default=encoder, **dumps_kwargs) @@ -446,7 +471,7 @@ def copy( # skip constructing values if no arguments are passed v = self.__dict__ else: - allowed_keys = self._calculate_keys(include=include, exclude=exclude, skip_defaults=False, update=update) + allowed_keys = self._calculate_keys(include=include, exclude=exclude, exclude_unset=False, update=update) if allowed_keys is None: v = {**self.__dict__, **(update or {})} else: @@ -457,7 +482,7 @@ def copy( by_alias=False, include=include, exclude=exclude, - skip_defaults=False, + exclude_unset=False, allowed_keys=allowed_keys, ) ), @@ -516,12 +541,19 @@ def _get_value( by_alias: bool, include: Optional[Union['SetIntStr', 'DictIntStrAny']], exclude: Optional[Union['SetIntStr', 'DictIntStrAny']], - skip_defaults: bool, + exclude_unset: bool, + exclude_defaults: bool, ) -> Any: if isinstance(v, BaseModel): if to_dict: - return v.dict(by_alias=by_alias, skip_defaults=skip_defaults, include=include, exclude=exclude) + return v.dict( + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + include=include, + exclude=exclude, + ) else: return v.copy(include=include, exclude=exclude) @@ -534,7 +566,8 @@ def _get_value( v_, to_dict=to_dict, by_alias=by_alias, - skip_defaults=skip_defaults, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, include=value_include and value_include.for_element(k_), exclude=value_exclude and value_exclude.for_element(k_), ) @@ -549,7 +582,8 @@ def _get_value( v_, to_dict=to_dict, by_alias=by_alias, - skip_defaults=skip_defaults, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, include=value_include and value_include.for_element(i), exclude=value_exclude and value_exclude.for_element(i), ) @@ -584,12 +618,20 @@ def _iter( allowed_keys: Optional['SetStr'] = None, include: Union['SetIntStr', 'DictIntStrAny'] = None, exclude: Union['SetIntStr', 'DictIntStrAny'] = None, - skip_defaults: bool = False, + exclude_unset: bool = False, + exclude_defaults: bool = False, ) -> 'TupleGenerator': value_exclude = ValueItems(self, exclude) if exclude else None value_include = ValueItems(self, include) if include else None + if exclude_defaults: + if allowed_keys is None: + allowed_keys = set(self.__fields__) + for k, v in self.__field_defaults__.items(): + if self.__dict__[k] == v: + allowed_keys.discard(k) + for k, v in self.__dict__.items(): if allowed_keys is None or k in allowed_keys: yield k, self._get_value( @@ -598,20 +640,21 @@ def _iter( by_alias=by_alias, include=value_include and value_include.for_element(k), exclude=value_exclude and value_exclude.for_element(k), - skip_defaults=skip_defaults, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, ) def _calculate_keys( self, include: Optional[Union['SetIntStr', 'DictIntStrAny']], exclude: Optional[Union['SetIntStr', 'DictIntStrAny']], - skip_defaults: bool, + exclude_unset: bool, update: Optional['DictStrAny'] = None, ) -> Optional['SetStr']: - if include is None and exclude is None and skip_defaults is False: + if include is None and exclude is None and exclude_unset is False: return None - if skip_defaults: + if exclude_unset: keys = self.__fields_set__.copy() else: keys = set(self.__dict__.keys())
pydantic/pydantic
f5cde39e7550871e6ca1aceb70891a4bf9f01608
I agree that it should, PR welcome @skewty in this case you are explicitly passing a value to `PanelData.validate` with `'gios_type': DIGITAL_INPUT`. You are passing the same value as the one that would be used by default, but you are passing it explicitly. If you don't pass an explicit value, and let the model take the default one (the same value, but using the default), then Pydantic respects the `skip_defaults`: ```Python from typing import List from pydantic import BaseModel, Schema DIGITAL_INPUT = 'digital_input' class Payload(BaseModel): """Base class for all Combox payloads""" class PointData(Payload): name: str = Schema(..., title='Name', min_length=1, max_length=32) gios_type: str = Schema(DIGITAL_INPUT, title='GIOS Type') class PanelData(Payload): name: str = Schema(..., title='Name', min_length=1, max_length=32) points: List[PointData] = Schema(..., title='Points', min_length=1) pd = PanelData.validate({'name': 'Dummy Panel', 'points': [{'name': 'Dummy Point'}]}) assert 'gios_type' not in pd.dict(skip_defaults=True)['points'][0] print(pd.dict(skip_defaults=True)) ``` --- I consider this behavior (the current behavior) a feature (useful), for example in this example: Let's say you have this model: ```Python class Person(BaseModel): name: str pet: str = None ``` You have an item in your DB that contains: ```Python {"name": "alice", "pet": "orion"} ``` Now let's say you receive an update to that item with: ```Python {"name": "bob"} ``` As `pet` is not set, you can keep the current value of `"orion"`, but you can update the name to `"bob"`. Using `skip_defaults` skips the non-existing `"pet"` that would be set to `None` by default. Now in your DB: ```Python {"name": "bob", "pet": "orion"} ``` Then, if you receive an update to the same item with: ```Python {"pet": None} ``` You could update your item in the DB, marking the pet as dead (`None`). Now in your DB: ```Python {"name": "bob", "pet": None} ``` In this case, Pydantic would be smart enough to know that `pet` was intentionally and explicitly set to `None`, even when that was the default value. It's able to distinguish between values taken by default and values set, even if the value is the same. @tiangolo thank you for taking the time to make such a complete reply and sorry for taking so long to get back to this. > I consider this behavior (the current behavior) a feature (useful), for example in this example: > ... > In this case, Pydantic would be smart enough to know that `pet` was intentionally and explicitly set to `None`, even when that was the default value. > > It's able to distinguish between values taken by default and values set, even if the value is the same. To me anyway, it is surprising that " It's able to distinguish between values taken by default and values set, even if the value is the same." To me, I see the feature more as a `skip_unset_defaults=True` rather than a `skip_defaults=True` because you are not really skipping default values as the parameter name suggests (to me). That said, would an alternate parameter name be acceptable to accomplish my version be acceptable? Or perhaps some sort of additional parameter like `strict=True` which I would set to `False` to accomplish what I was looking for when I created this issue? I realize changing how `skip_defaults` parameter works would be a breaking change and such a change would be best done before v1.0. So this issue / discussion is coming up at a good time :) I'm not entirely clear what change/new feature you would like? @samuelcolvin I think the request is to change the `skip_defaults` argument of `BaseModel.dict` to exclude values if they are equal to the default value (whether or not it was set), and to have a new keyword argument (called `skip_unset_defaults`; I would propose just `skip_unset`) that implements the existing functionality. For what it's worth, I also found the `skip_defaults` behavior surprising at first; `skip_unset` might have been a clearer name, especially considering most other libraries wouldn't even be *capable* of supporting the `skip_defaults` feature, so I think most people wouldn't guess that's how it works. Separately, I feel like skipping defaults (whether or not they were set) is a relatively common feature request. (For example, it would make it a lot easier to skip nulls in many cases). At this point I'm familiar and comfortable with the existing implementation, so I'm fine either way, but I can see some merits. `skip_defaults` and `skip_unset` sounds reasonable to me. One advantage is that there's no more logic required on parsing so performance (of raw parsing) would be unchanged. My only concern is that `skip_defaults` has new behaviour but has a name that shadows a different old keyword argument which now has a new name. This will cause a lot of headaches when migrating to v1 since tests and setup won't fail immediately. One solution would be to completely change the names to: `exclude_defaults` and `exclude_unset`. That way there can be no confusion with the names and it's more consistent with the `exclude` argument at the expensive for 3 more characters and one more syllable. What do you think? I like the consistency with `exclude`. do we still want this before v1 is released? If so it needs someone to start it in the next week or so. I think it's worthwhile. I'll try to get to this this weekend if no one else wants to handle it sooner. might require logic shared to #898 to get the default values.
diff --git a/tests/test_construction.py b/tests/test_construction.py --- a/tests/test_construction.py +++ b/tests/test_construction.py @@ -181,8 +181,8 @@ def test_copy_set_fields(): m = ModelTwo(a=24, d=Model(a='12')) m2 = m.copy() - assert m.dict(skip_defaults=True) == {'a': 24.0, 'd': {'a': 12}} - assert m.dict(skip_defaults=True) == m2.dict(skip_defaults=True) + assert m.dict(exclude_unset=True) == {'a': 24.0, 'd': {'a': 12}} + assert m.dict(exclude_unset=True) == m2.dict(exclude_unset=True) def test_simple_pickle(): @@ -227,9 +227,9 @@ class Config: def test_pickle_fields_set(): m = Model(a=24) - assert m.dict(skip_defaults=True) == {'a': 24} + assert m.dict(exclude_unset=True) == {'a': 24} m2 = pickle.loads(pickle.dumps(m)) - assert m2.dict(skip_defaults=True) == {'a': 24} + assert m2.dict(exclude_unset=True) == {'a': 24} def test_copy_update_exclude(): @@ -246,5 +246,5 @@ class Model(BaseModel): assert m.copy(exclude={'c'}).dict() == {'d': {'a': 'ax', 'b': 'bx'}} assert m.copy(exclude={'c'}, update={'c': 42}).dict() == {'c': 42, 'd': {'a': 'ax', 'b': 'bx'}} - assert m._calculate_keys(exclude={'x'}, include=None, skip_defaults=False) == {'c', 'd'} - assert m._calculate_keys(exclude={'x'}, include=None, skip_defaults=False, update={'c': 42}) == {'d'} + assert m._calculate_keys(exclude={'x'}, include=None, exclude_unset=False) == {'c', 'd'} + assert m._calculate_keys(exclude={'x'}, include=None, exclude_unset=False, update={'c': 42}) == {'d'} diff --git a/tests/test_edge_cases.py b/tests/test_edge_cases.py --- a/tests/test_edge_cases.py +++ b/tests/test_edge_cases.py @@ -373,26 +373,70 @@ class Model(BaseModel): assert m.dict(include={'a', 'b'}, exclude={'a'}) == {'b': 2} -def test_include_exclude_default(): +def test_include_exclude_unset(): class Model(BaseModel): a: int b: int c: int = 3 d: int = 4 + e: int = 5 + f: int = 6 - m = Model(a=1, b=2) - assert m.dict() == {'a': 1, 'b': 2, 'c': 3, 'd': 4} - assert m.__fields_set__ == {'a', 'b'} - assert m.dict(skip_defaults=True) == {'a': 1, 'b': 2} + m = Model(a=1, b=2, e=5, f=7) + assert m.dict() == {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 7} + assert m.__fields_set__ == {'a', 'b', 'e', 'f'} + assert m.dict(exclude_unset=True) == {'a': 1, 'b': 2, 'e': 5, 'f': 7} + + assert m.dict(include={'a'}, exclude_unset=True) == {'a': 1} + assert m.dict(include={'c'}, exclude_unset=True) == {} + + assert m.dict(exclude={'a'}, exclude_unset=True) == {'b': 2, 'e': 5, 'f': 7} + assert m.dict(exclude={'c'}, exclude_unset=True) == {'a': 1, 'b': 2, 'e': 5, 'f': 7} + + assert m.dict(include={'a', 'b', 'c'}, exclude={'b'}, exclude_unset=True) == {'a': 1} + assert m.dict(include={'a', 'b', 'c'}, exclude={'a', 'c'}, exclude_unset=True) == {'b': 2} - assert m.dict(include={'a'}, skip_defaults=True) == {'a': 1} - assert m.dict(include={'c'}, skip_defaults=True) == {} - assert m.dict(exclude={'a'}, skip_defaults=True) == {'b': 2} - assert m.dict(exclude={'c'}, skip_defaults=True) == {'a': 1, 'b': 2} +def test_include_exclude_defaults(): + class Model(BaseModel): + a: int + b: int + c: int = 3 + d: int = 4 + e: int = 5 + f: int = 6 + + m = Model(a=1, b=2, e=5, f=7) + assert m.dict() == {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 7} + assert m.__fields_set__ == {'a', 'b', 'e', 'f'} + assert m.dict(exclude_defaults=True) == {'a': 1, 'b': 2, 'f': 7} + + assert m.dict(include={'a'}, exclude_defaults=True) == {'a': 1} + assert m.dict(include={'c'}, exclude_defaults=True) == {} + + assert m.dict(exclude={'a'}, exclude_defaults=True) == {'b': 2, 'f': 7} + assert m.dict(exclude={'c'}, exclude_defaults=True) == {'a': 1, 'b': 2, 'f': 7} + + assert m.dict(include={'a', 'b', 'c'}, exclude={'b'}, exclude_defaults=True) == {'a': 1} + assert m.dict(include={'a', 'b', 'c'}, exclude={'a', 'c'}, exclude_defaults=True) == {'b': 2} + + +def test_skip_defaults_deprecated(): + class Model(BaseModel): + x: int + + m = Model(x=1) + match = r'Model.dict\(\): "skip_defaults" is deprecated and replaced by "exclude_unset"' + with pytest.warns(DeprecationWarning, match=match): + assert m.dict(skip_defaults=True) + with pytest.warns(DeprecationWarning, match=match): + assert m.dict(skip_defaults=False) - assert m.dict(include={'a', 'b', 'c'}, exclude={'b'}, skip_defaults=True) == {'a': 1} - assert m.dict(include={'a', 'b', 'c'}, exclude={'a', 'c'}, skip_defaults=True) == {'b': 2} + match = r'Model.json\(\): "skip_defaults" is deprecated and replaced by "exclude_unset"' + with pytest.warns(DeprecationWarning, match=match): + assert m.json(skip_defaults=True) + with pytest.warns(DeprecationWarning, match=match): + assert m.json(skip_defaults=False) def test_advanced_exclude(): @@ -474,12 +518,12 @@ class Config: m = Model(a=1, b=2) assert m.dict() == {'a': 1, 'b': 2, 'c': 3} assert m.__fields_set__ == {'a', 'b'} - assert m.dict(skip_defaults=True) == {'a': 1, 'b': 2} + assert m.dict(exclude_unset=True) == {'a': 1, 'b': 2} m2 = Model(a=1, b=2, d=4) assert m2.dict() == {'a': 1, 'b': 2, 'c': 3} assert m2.__fields_set__ == {'a', 'b'} - assert m2.dict(skip_defaults=True) == {'a': 1, 'b': 2} + assert m2.dict(exclude_unset=True) == {'a': 1, 'b': 2} def test_field_set_allow_extra(): @@ -494,12 +538,12 @@ class Config: m = Model(a=1, b=2) assert m.dict() == {'a': 1, 'b': 2, 'c': 3} assert m.__fields_set__ == {'a', 'b'} - assert m.dict(skip_defaults=True) == {'a': 1, 'b': 2} + assert m.dict(exclude_unset=True) == {'a': 1, 'b': 2} m2 = Model(a=1, b=2, d=4) assert m2.dict() == {'a': 1, 'b': 2, 'c': 3, 'd': 4} assert m2.__fields_set__ == {'a', 'b', 'd'} - assert m2.dict(skip_defaults=True) == {'a': 1, 'b': 2, 'd': 4} + assert m2.dict(exclude_unset=True) == {'a': 1, 'b': 2, 'd': 4} def test_field_set_field_name(): @@ -509,7 +553,7 @@ class Model(BaseModel): b: int = 3 assert Model(a=1, field_set=2).dict() == {'a': 1, 'field_set': 2, 'b': 3} - assert Model(a=1, field_set=2).dict(skip_defaults=True) == {'a': 1, 'field_set': 2} + assert Model(a=1, field_set=2).dict(exclude_unset=True) == {'a': 1, 'field_set': 2} assert Model.construct(dict(a=1, field_set=3), {'a', 'field_set'}).dict() == {'a': 1, 'field_set': 3} diff --git a/tests/test_main.py b/tests/test_main.py --- a/tests/test_main.py +++ b/tests/test_main.py @@ -729,19 +729,19 @@ class MyModel(BaseModel): assert m.__fields_set__ == {'a', 'b'} -def test_skip_defaults_dict(): +def test_exclude_unset_dict(): class MyModel(BaseModel): a: int b: int = 2 m = MyModel(a=5) - assert m.dict(skip_defaults=True) == {'a': 5} + assert m.dict(exclude_unset=True) == {'a': 5} m = MyModel(a=5, b=3) - assert m.dict(skip_defaults=True) == {'a': 5, 'b': 3} + assert m.dict(exclude_unset=True) == {'a': 5, 'b': 3} -def test_skip_defaults_recursive(): +def test_exclude_unset_recursive(): class ModelA(BaseModel): a: int b: int = 1 @@ -753,11 +753,11 @@ class ModelB(BaseModel): m = ModelB(c=5, e={'a': 0}) assert m.dict() == {'c': 5, 'd': 2, 'e': {'a': 0, 'b': 1}} - assert m.dict(skip_defaults=True) == {'c': 5, 'e': {'a': 0}} + assert m.dict(exclude_unset=True) == {'c': 5, 'e': {'a': 0}} assert dict(m) == {'c': 5, 'd': 2, 'e': {'a': 0, 'b': 1}} -def test_dict_skip_defaults_populated_by_alias(): +def test_dict_exclude_unset_populated_by_alias(): class MyModel(BaseModel): a: str = Field('default', alias='alias_a') b: str = Field('default', alias='alias_b') @@ -767,11 +767,11 @@ class Config: m = MyModel(alias_a='a') - assert m.dict(skip_defaults=True) == {'a': 'a'} - assert m.dict(skip_defaults=True, by_alias=True) == {'alias_a': 'a'} + assert m.dict(exclude_unset=True) == {'a': 'a'} + assert m.dict(exclude_unset=True, by_alias=True) == {'alias_a': 'a'} -def test_dict_skip_defaults_populated_by_alias_with_extra(): +def test_dict_exclude_unset_populated_by_alias_with_extra(): class MyModel(BaseModel): a: str = Field('default', alias='alias_a') b: str = Field('default', alias='alias_b') @@ -781,8 +781,8 @@ class Config: m = MyModel(alias_a='a', c='c') - assert m.dict(skip_defaults=True) == {'a': 'a', 'c': 'c'} - assert m.dict(skip_defaults=True, by_alias=True) == {'alias_a': 'a', 'c': 'c'} + assert m.dict(exclude_unset=True) == {'a': 'a', 'c': 'c'} + assert m.dict(exclude_unset=True, by_alias=True) == {'alias_a': 'a', 'c': 'c'} def test_dir_fields(): diff --git a/tests/test_orm_mode.py b/tests/test_orm_mode.py --- a/tests/test_orm_mode.py +++ b/tests/test_orm_mode.py @@ -122,7 +122,7 @@ class Config: model = Model.from_orm(foo) assert model.foo == 'Foo' assert model.bar == 1 - assert model.dict(skip_defaults=True) == {'foo': 'Foo'} + assert model.dict(exclude_unset=True) == {'foo': 'Foo'} with pytest.raises(ValidationError): ModelInvalid.from_orm(foo)
dict(skip_defaults=True) doesn't apply to nested models ```python from typing import List from pydantic import BaseModel, Schema DIGITAL_INPUT = 'digital_input' class Payload(BaseModel): """Base class for all Combox payloads""" class PointData(Payload): name: str = Schema(..., title='Name', min_length=1, max_length=32) gios_type: str = Schema(DIGITAL_INPUT, title='GIOS Type') class PanelData(Payload): name: str = Schema(..., title='Name', min_length=1, max_length=32) points: List[PointData] = Schema(..., title='Points', min_length=1) pd = PanelData.validate({'name': 'Dummy Panel', 'points': [{'name': 'Dummy Point', 'gios_type': DIGITAL_INPUT}]}) assert pd.dict(skip_defaults=True)['points'][0]['gios_type'] == DIGITAL_INPUT print(pd.dict(skip_defaults=True)) ``` ``` {'name': 'Dummy Panel', 'points': [{'name': 'Dummy Point', 'gios_type': 'digital_input'}]} ``` Notice how the `dict` contains 'gios_type' field.
0.0
f5cde39e7550871e6ca1aceb70891a4bf9f01608
[ "tests/test_construction.py::test_copy_set_fields", "tests/test_construction.py::test_pickle_fields_set", "tests/test_construction.py::test_copy_update_exclude", "tests/test_edge_cases.py::test_include_exclude_unset", "tests/test_edge_cases.py::test_include_exclude_defaults", "tests/test_edge_cases.py::test_skip_defaults_deprecated", "tests/test_edge_cases.py::test_field_set_ignore_extra", "tests/test_edge_cases.py::test_field_set_allow_extra", "tests/test_edge_cases.py::test_field_set_field_name", "tests/test_main.py::test_exclude_unset_dict", "tests/test_main.py::test_exclude_unset_recursive", "tests/test_main.py::test_dict_exclude_unset_populated_by_alias", "tests/test_main.py::test_dict_exclude_unset_populated_by_alias_with_extra", "tests/test_orm_mode.py::test_object_with_getattr" ]
[ "tests/test_construction.py::test_simple_construct", "tests/test_construction.py::test_construct_missing", "tests/test_construction.py::test_large_any_str", "tests/test_construction.py::test_simple_copy", "tests/test_construction.py::test_deep_copy", "tests/test_construction.py::test_copy_exclude", "tests/test_construction.py::test_copy_include", "tests/test_construction.py::test_copy_include_exclude", "tests/test_construction.py::test_copy_advanced_exclude", "tests/test_construction.py::test_copy_advanced_include", "tests/test_construction.py::test_copy_advanced_include_exclude", "tests/test_construction.py::test_copy_update", "tests/test_construction.py::test_simple_pickle", "tests/test_construction.py::test_recursive_pickle", "tests/test_construction.py::test_immutable_copy", "tests/test_edge_cases.py::test_str_bytes", "tests/test_edge_cases.py::test_str_bytes_none", "tests/test_edge_cases.py::test_union_int_str", "tests/test_edge_cases.py::test_union_priority", "tests/test_edge_cases.py::test_typed_list", "tests/test_edge_cases.py::test_typed_set", "tests/test_edge_cases.py::test_dict_dict", "tests/test_edge_cases.py::test_typed_dict[value0-result0]", "tests/test_edge_cases.py::test_typed_dict[value1-result1]", "tests/test_edge_cases.py::test_typed_dict[value2-result2]", "tests/test_edge_cases.py::test_typed_dict_error[1-errors0]", "tests/test_edge_cases.py::test_typed_dict_error[value1-errors1]", "tests/test_edge_cases.py::test_typed_dict_error[value2-errors2]", "tests/test_edge_cases.py::test_dict_key_error", "tests/test_edge_cases.py::test_tuple", "tests/test_edge_cases.py::test_tuple_more", "tests/test_edge_cases.py::test_tuple_length_error", "tests/test_edge_cases.py::test_tuple_invalid", "tests/test_edge_cases.py::test_tuple_value_error", "tests/test_edge_cases.py::test_recursive_list", "tests/test_edge_cases.py::test_recursive_list_error", "tests/test_edge_cases.py::test_list_unions", "tests/test_edge_cases.py::test_recursive_lists", "tests/test_edge_cases.py::test_str_enum", "tests/test_edge_cases.py::test_any_dict", "tests/test_edge_cases.py::test_infer_alias", "tests/test_edge_cases.py::test_alias_error", "tests/test_edge_cases.py::test_annotation_config", "tests/test_edge_cases.py::test_success_values_include", "tests/test_edge_cases.py::test_advanced_exclude", "tests/test_edge_cases.py::test_advanced_value_inclide", "tests/test_edge_cases.py::test_advanced_value_exclude_include", "tests/test_edge_cases.py::test_values_order", "tests/test_edge_cases.py::test_inheritance", "tests/test_edge_cases.py::test_invalid_type", "tests/test_edge_cases.py::test_valid_string_types[a", "tests/test_edge_cases.py::test_valid_string_types[some", "tests/test_edge_cases.py::test_valid_string_types[value2-foobar]", "tests/test_edge_cases.py::test_valid_string_types[123-123]", "tests/test_edge_cases.py::test_valid_string_types[123.45-123.45]", "tests/test_edge_cases.py::test_valid_string_types[value5-12.45]", "tests/test_edge_cases.py::test_valid_string_types[True-True]", "tests/test_edge_cases.py::test_valid_string_types[False-False]", "tests/test_edge_cases.py::test_valid_string_types[a10-a10]", "tests/test_edge_cases.py::test_valid_string_types[whatever-whatever]", "tests/test_edge_cases.py::test_invalid_string_types[value0-errors0]", "tests/test_edge_cases.py::test_invalid_string_types[value1-errors1]", "tests/test_edge_cases.py::test_inheritance_config", "tests/test_edge_cases.py::test_partial_inheritance_config", "tests/test_edge_cases.py::test_annotation_inheritance", "tests/test_edge_cases.py::test_string_none", "tests/test_edge_cases.py::test_alias_camel_case", "tests/test_edge_cases.py::test_get_field_info_inherit", "tests/test_edge_cases.py::test_return_errors_ok", "tests/test_edge_cases.py::test_return_errors_error", "tests/test_edge_cases.py::test_optional_required", "tests/test_edge_cases.py::test_invalid_validator", "tests/test_edge_cases.py::test_unable_to_infer", "tests/test_edge_cases.py::test_multiple_errors", "tests/test_edge_cases.py::test_pop_by_alias", "tests/test_edge_cases.py::test_validate_all", "tests/test_edge_cases.py::test_force_extra", "tests/test_edge_cases.py::test_illegal_extra_value", "tests/test_edge_cases.py::test_multiple_inheritance_config", "tests/test_edge_cases.py::test_submodel_different_type", "tests/test_edge_cases.py::test_self", "tests/test_edge_cases.py::test_self_recursive[BaseModel]", "tests/test_edge_cases.py::test_self_recursive[BaseSettings]", "tests/test_edge_cases.py::test_nested_init[BaseModel]", "tests/test_edge_cases.py::test_nested_init[BaseSettings]", "tests/test_edge_cases.py::test_values_attr_deprecation", "tests/test_edge_cases.py::test_init_inspection", "tests/test_edge_cases.py::test_type_on_annotation", "tests/test_edge_cases.py::test_assign_type", "tests/test_edge_cases.py::test_optional_subfields", "tests/test_edge_cases.py::test_not_optional_subfields", "tests/test_edge_cases.py::test_scheme_deprecated", "tests/test_edge_cases.py::test_population_by_alias", "tests/test_edge_cases.py::test_fields_deprecated", "tests/test_edge_cases.py::test_alias_child_precedence", "tests/test_edge_cases.py::test_alias_generator_parent", "tests/test_edge_cases.py::test_optional_field_constraints", "tests/test_edge_cases.py::test_field_str_shape", "tests/test_edge_cases.py::test_field_type_display[int-int]", "tests/test_edge_cases.py::test_field_type_display[type_1-Optional[int]]", "tests/test_edge_cases.py::test_field_type_display[type_2-Union[NoneType,", "tests/test_edge_cases.py::test_field_type_display[type_3-Union[int,", "tests/test_edge_cases.py::test_field_type_display[type_4-List[int]]", "tests/test_edge_cases.py::test_field_type_display[type_5-Tuple[int,", "tests/test_edge_cases.py::test_field_type_display[type_6-Union[List[int],", "tests/test_edge_cases.py::test_field_type_display[type_7-List[Tuple[int,", "tests/test_edge_cases.py::test_field_type_display[type_8-Mapping[int,", "tests/test_edge_cases.py::test_field_type_display[type_9-Tuple[int,", "tests/test_edge_cases.py::test_field_type_display[type_10-Optional[List[int]]]", "tests/test_main.py::test_success", "tests/test_main.py::test_ultra_simple_missing", "tests/test_main.py::test_ultra_simple_failed", "tests/test_main.py::test_comparing", "tests/test_main.py::test_nullable_strings_success", "tests/test_main.py::test_nullable_strings_fails", "tests/test_main.py::test_recursion", "tests/test_main.py::test_recursion_fails", "tests/test_main.py::test_not_required", "tests/test_main.py::test_infer_type", "tests/test_main.py::test_allow_extra", "tests/test_main.py::test_forbidden_extra_success", "tests/test_main.py::test_forbidden_extra_fails", "tests/test_main.py::test_disallow_mutation", "tests/test_main.py::test_extra_allowed", "tests/test_main.py::test_extra_ignored", "tests/test_main.py::test_set_attr", "tests/test_main.py::test_set_attr_invalid", "tests/test_main.py::test_any", "tests/test_main.py::test_alias", "tests/test_main.py::test_population_by_field_name", "tests/test_main.py::test_field_order", "tests/test_main.py::test_required", "tests/test_main.py::test_not_immutability", "tests/test_main.py::test_immutability", "tests/test_main.py::test_const_validates", "tests/test_main.py::test_const_uses_default", "tests/test_main.py::test_const_with_wrong_value", "tests/test_main.py::test_const_list", "tests/test_main.py::test_const_list_with_wrong_value", "tests/test_main.py::test_const_validation_json_serializable", "tests/test_main.py::test_validating_assignment_pass", "tests/test_main.py::test_validating_assignment_fail", "tests/test_main.py::test_enum_values", "tests/test_main.py::test_enum_raw", "tests/test_main.py::test_set_tuple_values", "tests/test_main.py::test_default_copy", "tests/test_main.py::test_arbitrary_type_allowed_validation_success", "tests/test_main.py::test_arbitrary_type_allowed_validation_fails", "tests/test_main.py::test_arbitrary_types_not_allowed", "tests/test_main.py::test_type_type_validation_success", "tests/test_main.py::test_type_type_subclass_validation_success", "tests/test_main.py::test_type_type_validation_fails_for_instance", "tests/test_main.py::test_type_type_validation_fails_for_basic_type", "tests/test_main.py::test_annotation_field_name_shadows_attribute", "tests/test_main.py::test_value_field_name_shadows_attribute", "tests/test_main.py::test_class_var", "tests/test_main.py::test_fields_set", "tests/test_main.py::test_dir_fields", "tests/test_main.py::test_dict_with_extra_keys", "tests/test_main.py::test_alias_generator", "tests/test_main.py::test_alias_generator_with_field_schema", "tests/test_main.py::test_alias_generator_wrong_type_error", "tests/test_main.py::test_root", "tests/test_main.py::test_root_list", "tests/test_main.py::test_root_failed", "tests/test_main.py::test_root_undefined_failed", "tests/test_main.py::test_parse_root_as_mapping", "tests/test_main.py::test_untouched_types", "tests/test_main.py::test_custom_types_fail_without_keep_untouched", "tests/test_main.py::test_model_iteration", "tests/test_main.py::test_custom_init_subclass_params", "tests/test_orm_mode.py::test_getdict", "tests/test_orm_mode.py::test_orm_mode", "tests/test_orm_mode.py::test_not_orm_mode", "tests/test_orm_mode.py::test_properties", "tests/test_orm_mode.py::test_extra_allow", "tests/test_orm_mode.py::test_extra_forbid", "tests/test_orm_mode.py::test_root_validator", "tests/test_orm_mode.py::test_custom_getter_dict", "tests/test_orm_mode.py::test_custom_getter_dict_derived_model_class" ]
{ "failed_lite_validators": [ "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2019-10-21 00:34:26+00:00
mit
4,919
pydantic__pydantic-926
diff --git a/pydantic/validators.py b/pydantic/validators.py --- a/pydantic/validators.py +++ b/pydantic/validators.py @@ -568,9 +568,7 @@ def find_validators( # noqa: C901 (ignore complexity) if config.arbitrary_types_allowed: yield make_arbitrary_type_validator(type_) else: - raise RuntimeError( - f'no validator found for {type_} see `keep_untouched` or `arbitrary_types_allowed` in Config' - ) + raise RuntimeError(f'no validator found for {type_}, see `arbitrary_types_allowed` in Config') def _find_supertype(type_: AnyType) -> Optional[AnyType]:
pydantic/pydantic
f5cde39e7550871e6ca1aceb70891a4bf9f01608
I agree the name isn't that clear, but I think it's too late to change. Happy to accept a PR to update the documentation, or even update the error message if we can do it asap.
diff --git a/tests/test_main.py b/tests/test_main.py --- a/tests/test_main.py +++ b/tests/test_main.py @@ -951,7 +951,7 @@ def class_name(cls) -> str: assert str(e.value) == ( "no validator found for <class 'tests.test_main.test_custom_types_fail_without_keep_untouched.<locals>." - "_ClassPropertyDescriptor'> see `keep_untouched` or `arbitrary_types_allowed` in Config" + "_ClassPropertyDescriptor'>, see `arbitrary_types_allowed` in Config" ) class Model(BaseModel):
Behaviour of keep_untouched is unclear in docs # Bug * Python version `import sys; print(sys.version)`: 3.7.3 * Pydantic version `import pydantic; print(pydantic.VERSION)`: 0.32.2 The `keep_untouched` attribute on a model's Config affects the behaviour for properties' **values**, not their **type annotations**. This is unclear, and is also made particularly misleading by the wording of [this error message](https://github.com/samuelcolvin/pydantic/blob/master/pydantic/validators.py#L572): ``` RuntimeError: no validator found for {type_} see `keep_untouched` or `arbitrary_types_allowed` in Config ``` These should both be improved, and perhaps the config attribute's name should also be changed?
0.0
f5cde39e7550871e6ca1aceb70891a4bf9f01608
[ "tests/test_main.py::test_custom_types_fail_without_keep_untouched" ]
[ "tests/test_main.py::test_success", "tests/test_main.py::test_ultra_simple_missing", "tests/test_main.py::test_ultra_simple_failed", "tests/test_main.py::test_comparing", "tests/test_main.py::test_nullable_strings_success", "tests/test_main.py::test_nullable_strings_fails", "tests/test_main.py::test_recursion", "tests/test_main.py::test_recursion_fails", "tests/test_main.py::test_not_required", "tests/test_main.py::test_infer_type", "tests/test_main.py::test_allow_extra", "tests/test_main.py::test_forbidden_extra_success", "tests/test_main.py::test_forbidden_extra_fails", "tests/test_main.py::test_disallow_mutation", "tests/test_main.py::test_extra_allowed", "tests/test_main.py::test_extra_ignored", "tests/test_main.py::test_set_attr", "tests/test_main.py::test_set_attr_invalid", "tests/test_main.py::test_any", "tests/test_main.py::test_alias", "tests/test_main.py::test_population_by_field_name", "tests/test_main.py::test_field_order", "tests/test_main.py::test_required", "tests/test_main.py::test_not_immutability", "tests/test_main.py::test_immutability", "tests/test_main.py::test_const_validates", "tests/test_main.py::test_const_uses_default", "tests/test_main.py::test_const_with_wrong_value", "tests/test_main.py::test_const_list", "tests/test_main.py::test_const_list_with_wrong_value", "tests/test_main.py::test_const_validation_json_serializable", "tests/test_main.py::test_validating_assignment_pass", "tests/test_main.py::test_validating_assignment_fail", "tests/test_main.py::test_enum_values", "tests/test_main.py::test_enum_raw", "tests/test_main.py::test_set_tuple_values", "tests/test_main.py::test_default_copy", "tests/test_main.py::test_arbitrary_type_allowed_validation_success", "tests/test_main.py::test_arbitrary_type_allowed_validation_fails", "tests/test_main.py::test_arbitrary_types_not_allowed", "tests/test_main.py::test_type_type_validation_success", "tests/test_main.py::test_type_type_subclass_validation_success", "tests/test_main.py::test_type_type_validation_fails_for_instance", "tests/test_main.py::test_type_type_validation_fails_for_basic_type", "tests/test_main.py::test_annotation_field_name_shadows_attribute", "tests/test_main.py::test_value_field_name_shadows_attribute", "tests/test_main.py::test_class_var", "tests/test_main.py::test_fields_set", "tests/test_main.py::test_skip_defaults_dict", "tests/test_main.py::test_skip_defaults_recursive", "tests/test_main.py::test_dict_skip_defaults_populated_by_alias", "tests/test_main.py::test_dict_skip_defaults_populated_by_alias_with_extra", "tests/test_main.py::test_dir_fields", "tests/test_main.py::test_dict_with_extra_keys", "tests/test_main.py::test_alias_generator", "tests/test_main.py::test_alias_generator_with_field_schema", "tests/test_main.py::test_alias_generator_wrong_type_error", "tests/test_main.py::test_root", "tests/test_main.py::test_root_list", "tests/test_main.py::test_root_failed", "tests/test_main.py::test_root_undefined_failed", "tests/test_main.py::test_parse_root_as_mapping", "tests/test_main.py::test_untouched_types", "tests/test_main.py::test_model_iteration", "tests/test_main.py::test_custom_init_subclass_params" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2019-10-23 07:40:23+00:00
mit
4,920
pydantic__pydantic-941
diff --git a/pydantic/class_validators.py b/pydantic/class_validators.py --- a/pydantic/class_validators.py +++ b/pydantic/class_validators.py @@ -51,6 +51,7 @@ def validator( always: bool = False, check_fields: bool = True, whole: bool = None, + allow_reuse: bool = False, ) -> Callable[[AnyCallable], classmethod]: """ Decorate methods on the class indicating that they should be used to validate fields @@ -60,6 +61,7 @@ def validator( whole object :param always: whether this method and other validators should be called even if the value is missing :param check_fields: whether to check that the fields actually exist on the model + :param allow_reuse: whether to track and raise an error if another validator refers to the decorated function """ if not fields: raise ConfigError('validator with no fields specified') @@ -78,12 +80,14 @@ def validator( each_item = not whole def dec(f: AnyCallable) -> classmethod: - _check_validator_name(f) - f_cls = classmethod(f) + f_cls = _prepare_validator(f, allow_reuse) setattr( f_cls, VALIDATOR_CONFIG_KEY, - (fields, Validator(func=f, pre=pre, each_item=each_item, always=always, check_fields=check_fields)), + ( + fields, + Validator(func=f_cls.__func__, pre=pre, each_item=each_item, always=always, check_fields=check_fields), + ), ) return f_cls @@ -91,33 +95,33 @@ def dec(f: AnyCallable) -> classmethod: def root_validator( - _func: Optional[AnyCallable] = None, *, pre: bool = False + _func: Optional[AnyCallable] = None, *, pre: bool = False, allow_reuse: bool = False ) -> Union[classmethod, Callable[[AnyCallable], classmethod]]: if _func: - _check_validator_name(_func) - f_cls = classmethod(_func) - setattr(f_cls, ROOT_VALIDATOR_CONFIG_KEY, Validator(func=_func, pre=pre)) + f_cls = _prepare_validator(_func, allow_reuse) + setattr(f_cls, ROOT_VALIDATOR_CONFIG_KEY, Validator(func=f_cls.__func__, pre=pre)) return f_cls def dec(f: AnyCallable) -> classmethod: - _check_validator_name(f) - f_cls = classmethod(f) - setattr(f_cls, ROOT_VALIDATOR_CONFIG_KEY, Validator(func=f, pre=pre)) + f_cls = _prepare_validator(f, allow_reuse) + setattr(f_cls, ROOT_VALIDATOR_CONFIG_KEY, Validator(func=f_cls.__func__, pre=pre)) return f_cls return dec -def _check_validator_name(f: AnyCallable) -> None: +def _prepare_validator(function: AnyCallable, allow_reuse: bool) -> classmethod: """ - avoid validators with duplicated names since without this, validators can be overwritten silently - which generally isn't the intended behaviour, don't run in ipython - see #312 + Avoid validators with duplicated names since without this, validators can be overwritten silently + which generally isn't the intended behaviour, don't run in ipython (see #312) or if allow_reuse is False. """ - if not in_ipython(): # pragma: no branch - ref = f.__module__ + '.' + f.__qualname__ + f_cls = function if isinstance(function, classmethod) else classmethod(function) + if not in_ipython() and not allow_reuse: + ref = f_cls.__func__.__module__ + '.' + f_cls.__func__.__qualname__ if ref in _FUNCS: - raise ConfigError(f'duplicate validator function "{ref}"') + raise ConfigError(f'duplicate validator function "{ref}"; if this is intended, set `allow_reuse=True`') _FUNCS.add(ref) + return f_cls class ValidatorGroup:
pydantic/pydantic
25f657fd5ff03f661cb84656747b0a90bad02c46
I'm on my mobile, but should be as simple as doing something like: ```py class MyModel(BaseModel): check_foo = validator('foo')(reused_validator) ``` Have a try and let me know if that works or doesn't work or I have the syntax slightly wrong. @samuelcolvin I don't think that works due to this check: ```python if not in_ipython(): # pragma: no branch ref = f.__module__ + '.' + f.__qualname__ if ref in _FUNCS: raise ConfigError(f'duplicate validator function "{ref}"') _FUNCS.add(ref) ``` I think we can probably fix this though. Here's a self contained demonstration that it doesn't currently work. ```python from pydantic import BaseModel, validator def double_validator(cls, value): return value * 2 class A(BaseModel): x: int double = validator('x')(double_validator) class B(BaseModel): x: int double = validator('x')(double_validator) # pydantic.errors.ConfigError: duplicate validator function "__main__.double_validator" ``` Humm, possibly. We could either drop that check or make it optional. Or you could setup a validator which just calls the reused validator. Maybe `allow_name_reuse` as another argument on a validator?
diff --git a/tests/test_validators.py b/tests/test_validators.py --- a/tests/test_validators.py +++ b/tests/test_validators.py @@ -1,4 +1,5 @@ from datetime import datetime +from itertools import product from typing import Dict, List, Optional, Tuple import pytest @@ -235,7 +236,9 @@ def duplicate_name(cls, v): # noqa return v assert str(exc_info.value) == ( - 'duplicate validator function ' '"tests.test_validators.test_duplicates.<locals>.Model.duplicate_name"' + 'duplicate validator function ' + '"tests.test_validators.test_duplicates.<locals>.Model.duplicate_name"; ' + 'if this is intended, set `allow_reuse=True`' ) @@ -756,7 +759,7 @@ def repeat_b(cls, v): return v * 2 @root_validator - def root_validator(cls, values): + def example_root_validator(cls, values): root_val_values.append(values) if 'snap' in values.get('b', ''): raise ValueError('foobar') @@ -906,3 +909,99 @@ def root_validator_child(cls, values): assert len(Child.__pre_root_validators__) == 0 assert Child(a=123).dict() == {'extra2': 2, 'extra1': 1, 'a': 123} assert calls == ["parent validator: {'a': 123}", "child validator: {'extra1': 1, 'a': 123}"] + + +def reusable_validator(num): + return num * 2 + + +def test_reuse_global_validators(): + class Model(BaseModel): + x: int + y: int + + double_x = validator('x', allow_reuse=True)(reusable_validator) + double_y = validator('y', allow_reuse=True)(reusable_validator) + + assert dict(Model(x=1, y=1)) == {'x': 2, 'y': 2} + + +def declare_with_reused_validators(include_root, allow_1, allow_2, allow_3): + class Model(BaseModel): + a: str + b: str + + @validator('a', allow_reuse=allow_1) + def duplicate_name(cls, v): + return v + + @validator('b', allow_reuse=allow_2) # noqa F811 + def duplicate_name(cls, v): # noqa F811 + return v + + if include_root: + + @root_validator(allow_reuse=allow_3) # noqa F811 + def duplicate_name(cls, values): # noqa F811 + return values + + [email protected] +def reset_tracked_validators(): + from pydantic.class_validators import _FUNCS + + original_tracked_validators = set(_FUNCS) + yield + _FUNCS.clear() + _FUNCS.update(original_tracked_validators) + + [email protected]('include_root,allow_1,allow_2,allow_3', product(*[[True, False]] * 4)) +def test_allow_reuse(include_root, allow_1, allow_2, allow_3, reset_tracked_validators): + duplication_count = int(not allow_1) + int(not allow_2) + int(include_root and not allow_3) + if duplication_count > 1: + with pytest.raises(ConfigError) as exc_info: + declare_with_reused_validators(include_root, allow_1, allow_2, allow_3) + assert str(exc_info.value).startswith('duplicate validator function') + else: + declare_with_reused_validators(include_root, allow_1, allow_2, allow_3) + + [email protected]('validator_classmethod,root_validator_classmethod', product(*[[True, False]] * 2)) +def test_root_validator_classmethod(validator_classmethod, root_validator_classmethod, reset_tracked_validators): + root_val_values = [] + + class Model(BaseModel): + a: int = 1 + b: str + + def repeat_b(cls, v): + return v * 2 + + if validator_classmethod: + repeat_b = classmethod(repeat_b) + repeat_b = validator('b')(repeat_b) + + def example_root_validator(cls, values): + root_val_values.append(values) + if 'snap' in values.get('b', ''): + raise ValueError('foobar') + return dict(values, b='changed') + + if root_validator_classmethod: + example_root_validator = classmethod(example_root_validator) + example_root_validator = root_validator(example_root_validator) + + assert Model(a='123', b='bar').dict() == {'a': 123, 'b': 'changed'} + + with pytest.raises(ValidationError) as exc_info: + Model(b='snap dragon') + assert exc_info.value.errors() == [{'loc': ('__root__',), 'msg': 'foobar', 'type': 'value_error'}] + + with pytest.raises(ValidationError) as exc_info: + Model(a='broken', b='bar') + assert exc_info.value.errors() == [ + {'loc': ('a',), 'msg': 'value is not a valid integer', 'type': 'type_error.integer'} + ] + + assert root_val_values == [{'a': 123, 'b': 'barbar'}, {'a': 1, 'b': 'snap dragonsnap dragon'}, {'b': 'barbar'}]
Re-use validators? Is it possible to create a validator and import it everywhere else it's used? I have validators for certain fields that are present in multiple classes that I'd like to call simply without defining them.
0.0
25f657fd5ff03f661cb84656747b0a90bad02c46
[ "tests/test_validators.py::test_duplicates", "tests/test_validators.py::test_reuse_global_validators", "tests/test_validators.py::test_allow_reuse[True-True-True-True]", "tests/test_validators.py::test_allow_reuse[True-True-True-False]", "tests/test_validators.py::test_allow_reuse[True-True-False-True]", "tests/test_validators.py::test_allow_reuse[True-True-False-False]", "tests/test_validators.py::test_allow_reuse[True-False-True-True]", "tests/test_validators.py::test_allow_reuse[True-False-True-False]", "tests/test_validators.py::test_allow_reuse[True-False-False-True]", "tests/test_validators.py::test_allow_reuse[True-False-False-False]", "tests/test_validators.py::test_allow_reuse[False-True-True-True]", "tests/test_validators.py::test_allow_reuse[False-True-True-False]", "tests/test_validators.py::test_allow_reuse[False-True-False-True]", "tests/test_validators.py::test_allow_reuse[False-True-False-False]", "tests/test_validators.py::test_allow_reuse[False-False-True-True]", "tests/test_validators.py::test_allow_reuse[False-False-True-False]", "tests/test_validators.py::test_allow_reuse[False-False-False-True]", "tests/test_validators.py::test_allow_reuse[False-False-False-False]", "tests/test_validators.py::test_root_validator_classmethod[True-True]", "tests/test_validators.py::test_root_validator_classmethod[True-False]", "tests/test_validators.py::test_root_validator_classmethod[False-True]" ]
[ "tests/test_validators.py::test_simple", "tests/test_validators.py::test_int_validation", "tests/test_validators.py::test_frozenset_validation", "tests/test_validators.py::test_validate_whole", "tests/test_validators.py::test_validate_kwargs", "tests/test_validators.py::test_validate_pre_error", "tests/test_validators.py::test_validating_assignment_ok", "tests/test_validators.py::test_validating_assignment_fail", "tests/test_validators.py::test_validating_assignment_value_change", "tests/test_validators.py::test_validating_assignment_extra", "tests/test_validators.py::test_validating_assignment_dict", "tests/test_validators.py::test_validate_multiple", "tests/test_validators.py::test_classmethod", "tests/test_validators.py::test_use_bare", "tests/test_validators.py::test_use_no_fields", "tests/test_validators.py::test_validate_always", "tests/test_validators.py::test_validate_not_always", "tests/test_validators.py::test_wildcard_validators", "tests/test_validators.py::test_wildcard_validator_error", "tests/test_validators.py::test_invalid_field", "tests/test_validators.py::test_validate_child", "tests/test_validators.py::test_validate_child_extra", "tests/test_validators.py::test_validate_child_all", "tests/test_validators.py::test_validate_parent", "tests/test_validators.py::test_validate_parent_all", "tests/test_validators.py::test_inheritance_keep", "tests/test_validators.py::test_inheritance_replace", "tests/test_validators.py::test_inheritance_new", "tests/test_validators.py::test_validation_each_item", "tests/test_validators.py::test_key_validation", "tests/test_validators.py::test_validator_always_optional", "tests/test_validators.py::test_validator_always_pre", "tests/test_validators.py::test_validator_always_post", "tests/test_validators.py::test_validator_always_post_optional", "tests/test_validators.py::test_datetime_validator", "tests/test_validators.py::test_pre_called_once", "tests/test_validators.py::test_make_generic_validator[fields0-_v_]", "tests/test_validators.py::test_make_generic_validator[fields1-_v_]", "tests/test_validators.py::test_make_generic_validator[fields2-_v_,_field_]", "tests/test_validators.py::test_make_generic_validator[fields3-_v_,_config_]", "tests/test_validators.py::test_make_generic_validator[fields4-_v_,_values_]", "tests/test_validators.py::test_make_generic_validator[fields5-_v_,_field_,_config_]", "tests/test_validators.py::test_make_generic_validator[fields6-_v_,_field_,_values_]", "tests/test_validators.py::test_make_generic_validator[fields7-_v_,_config_,_values_]", "tests/test_validators.py::test_make_generic_validator[fields8-_v_,_field_,_values_,_config_]", "tests/test_validators.py::test_make_generic_validator[fields9-_cls_,_v_]", "tests/test_validators.py::test_make_generic_validator[fields10-_cls_,_v_]", "tests/test_validators.py::test_make_generic_validator[fields11-_cls_,_v_,_field_]", "tests/test_validators.py::test_make_generic_validator[fields12-_cls_,_v_,_config_]", "tests/test_validators.py::test_make_generic_validator[fields13-_cls_,_v_,_values_]", "tests/test_validators.py::test_make_generic_validator[fields14-_cls_,_v_,_field_,_config_]", "tests/test_validators.py::test_make_generic_validator[fields15-_cls_,_v_,_field_,_values_]", "tests/test_validators.py::test_make_generic_validator[fields16-_cls_,_v_,_config_,_values_]", "tests/test_validators.py::test_make_generic_validator[fields17-_cls_,_v_,_field_,_values_,_config_]", "tests/test_validators.py::test_make_generic_validator_kwargs", "tests/test_validators.py::test_make_generic_validator_invalid", "tests/test_validators.py::test_make_generic_validator_cls_kwargs", "tests/test_validators.py::test_make_generic_validator_cls_invalid", "tests/test_validators.py::test_make_generic_validator_self", "tests/test_validators.py::test_assert_raises_validation_error", "tests/test_validators.py::test_optional_validator", "tests/test_validators.py::test_whole", "tests/test_validators.py::test_root_validator", "tests/test_validators.py::test_root_validator_pre", "tests/test_validators.py::test_root_validator_repeat", "tests/test_validators.py::test_root_validator_repeat2", "tests/test_validators.py::test_root_validator_self", "tests/test_validators.py::test_root_validator_extra", "tests/test_validators.py::test_root_validator_types", "tests/test_validators.py::test_root_validator_inheritance", "tests/test_validators.py::test_root_validator_classmethod[False-False]" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-10-25 19:24:53+00:00
mit
4,921
pydantic__pydantic-958
diff --git a/docs/examples/models_custom_root_field_parse_obj.py b/docs/examples/models_custom_root_field_parse_obj.py new file mode 100644 --- /dev/null +++ b/docs/examples/models_custom_root_field_parse_obj.py @@ -0,0 +1,17 @@ +from typing import List, Dict +from pydantic import BaseModel, ValidationError + +class Pets(BaseModel): + __root__: List[str] + +print(Pets.parse_obj(['dog', 'cat'])) +print(Pets.parse_obj({'__root__': ['dog', 'cat']})) # not recommended + +class PetsByName(BaseModel): + __root__: Dict[str, str] + +print(PetsByName.parse_obj({'Otis': 'dog', 'Milo': 'cat'})) +try: + PetsByName.parse_obj({'__root__': {'Otis': 'dog', 'Milo': 'cat'}}) +except ValidationError as e: + print(e) diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -136,8 +136,6 @@ def is_valid_field(name: str) -> bool: def validate_custom_root_type(fields: Dict[str, ModelField]) -> None: if len(fields) > 1: raise ValueError('__root__ cannot be mixed with other fields') - if fields[ROOT_KEY].shape == SHAPE_MAPPING: - raise TypeError('custom root type cannot allow mapping') UNTOUCHED_TYPES = FunctionType, property, type, classmethod, staticmethod @@ -382,15 +380,16 @@ def json( @classmethod def parse_obj(cls: Type['Model'], obj: Any) -> 'Model': - if not isinstance(obj, dict): - if cls.__custom_root_type__: - obj = {ROOT_KEY: obj} - else: - try: - obj = dict(obj) - except (TypeError, ValueError) as e: - exc = TypeError(f'{cls.__name__} expected dict not {type(obj).__name__}') - raise ValidationError([ErrorWrapper(exc, loc=ROOT_KEY)], cls) from e + if cls.__custom_root_type__ and ( + not (isinstance(obj, dict) and obj.keys() == {ROOT_KEY}) or cls.__fields__[ROOT_KEY].shape == SHAPE_MAPPING + ): + obj = {ROOT_KEY: obj} + elif not isinstance(obj, dict): + try: + obj = dict(obj) + except (TypeError, ValueError) as e: + exc = TypeError(f'{cls.__name__} expected dict not {type(obj).__name__}') + raise ValidationError([ErrorWrapper(exc, loc=ROOT_KEY)], cls) from e return cls(**obj) @classmethod
pydantic/pydantic
043186cfcd2d3f6223753f38b2140e3a94194e38
If you want change the input data to confirm to a more conventional shape, you'd be best of with something like: ```py class ChildModel(BaseModel): thumbnail: str video: str class MainModel(BaseModel): __root__: Dict[str, ChildModel] ``` Then you'll need a validator to check the format of the keys. You'll then need to manually [customise the schema](https://pydantic-docs.helpmanual.io/usage/schema/#schema-customization) Hi @samuelcolvin, thank you for reverting back so quick. I tried to follow the link and the example shared you above. but wasn't able to achieve the use case as mentioned above. Can you please help me with this? A code example will be a great help. I get the following error using your code snippet `TypeError: custom root type cannot allow mapping` Thanks in advance! Bump! Sorry, I forgot dictionaries can't be used as the root type. You need to use a key for the dictionaries of video formats, in your above example that's fine since you have `{"preview: {...}}`. With that you might want something like: ```py from typing import Dict from pydantic import BaseModel, validator from devtools import debug class ChildModel(BaseModel): thumbnail: str video: str class MainModel(BaseModel): preview: Dict[str, ChildModel] @validator('preview') def check_keys(cls, v): for i, k in enumerate(v): if ':' not in k: raise ValueError(f'{i} key {k!r} does not contain a colon (:)') return v data = { 'preview': { '9:16': {'thumbnail': '', 'video': ''}, '16:9': {'thumbnail': '', 'video': ''}, '1:1': {'thumbnail': '', 'video': ''}, 'bad': {'thumbnail': '', 'video': ''}, } } m = MainModel(**data) debug(m) ``` Will raise an error as one of the keys doesn't contain a colon. If you're data is just a dictionary of the form `{"9:16": {}, "16:9": {}, ...}`, you would need to initialise with something like `MainModel(preview=data)`. @samuelcolvin Is there a fundamental reason we don't support root mappings, or is it just because this way was easier to implement for now? I recognize it may require adding an unacceptable amount of added complexity to support a mapping type in the root; I'm just trying to understand whether this restriction is more purposeful or accidental. I think the problem is `parse_obj`: https://github.com/samuelcolvin/pydantic/blob/f5cde39e7550871e6ca1aceb70891a4bf9f01608/pydantic/main.py#L356 Might be possible to fix, but that was why we did it. Yeah, I think it could make sense to replace that with a root model check; it feels kind of arbitrarily limiting to not support mappings as the root model. On the other hand, I don't love adding all of these runtime checks when in most cases they aren't relevant; maybe there is a way to essentially decorate/replace this method inside the metaclass to get different behavior (if the model is a custom root model with a mapping type)? (I guess maybe this is starting to get outside the scope of this issue though.)
diff --git a/tests/test_main.py b/tests/test_main.py --- a/tests/test_main.py +++ b/tests/test_main.py @@ -900,10 +900,34 @@ class MyModel(BaseModel): def test_parse_root_as_mapping(): - with pytest.raises(TypeError, match='custom root type cannot allow mapping'): + class MyModel(BaseModel): + __root__: Mapping[str, str] - class MyModel(BaseModel): - __root__: Mapping[str, str] + assert MyModel.parse_obj({1: 2}).__root__ == {'1': '2'} + + with pytest.raises(ValidationError) as exc_info: + MyModel.parse_obj({'__root__': {'1': '2'}}) + assert exc_info.value.errors() == [ + {'loc': ('__root__', '__root__'), 'msg': 'str type expected', 'type': 'type_error.str'} + ] + + +def test_parse_obj_non_mapping_root(): + class MyModel(BaseModel): + __root__: List[str] + + assert MyModel.parse_obj(['a']).__root__ == ['a'] + assert MyModel.parse_obj({'__root__': ['a']}).__root__ == ['a'] + with pytest.raises(ValidationError) as exc_info: + MyModel.parse_obj({'__not_root__': ['a']}) + assert exc_info.value.errors() == [ + {'loc': ('__root__',), 'msg': 'value is not a valid list', 'type': 'type_error.list'} + ] + with pytest.raises(ValidationError): + MyModel.parse_obj({'__root__': ['a'], 'other': 1}) + assert exc_info.value.errors() == [ + {'loc': ('__root__',), 'msg': 'value is not a valid list', 'type': 'type_error.list'} + ] def test_untouched_types():
Allow dict like types to __root__ Hi @samuelcolvin , Thank you for this amazing library. I am using it with fastapi for defining input models. ``` "preview": { "9:16": { "thumbnail": "", "video": "" }, "16:9": { "thumbnail": "", "video": "" }, "1:1": { "thumbnail": "", "video": "" } } ``` I have the above data coming in the request for which I want to create a model. I tried implementing wildcard fields but didn't get any success. In the above case, the aspect ratio is dynamic and can be anything but will always be in *:* format. In case that is coming, thumbnail and video are in nested model. I have implemented this in JSON schema like the following: ``` template_schema = { "type": "object", "properties": { "preview": { "minProperties": 1, "type": "object", "patternProperties": { "^[0-9]{1,2}:\d{1,2}$": { "type": "object", "properties": { "thumbnail": {"type": "string"}, "video": {"type": "string"} }, "required": ["thumbnail", "video"], } }, }, } }``` Please guide me on how to get it to work? Any leads would be appreciated. Thanks in advance!
0.0
043186cfcd2d3f6223753f38b2140e3a94194e38
[ "tests/test_main.py::test_parse_root_as_mapping", "tests/test_main.py::test_parse_obj_non_mapping_root" ]
[ "tests/test_main.py::test_success", "tests/test_main.py::test_ultra_simple_missing", "tests/test_main.py::test_ultra_simple_failed", "tests/test_main.py::test_comparing", "tests/test_main.py::test_nullable_strings_success", "tests/test_main.py::test_nullable_strings_fails", "tests/test_main.py::test_recursion", "tests/test_main.py::test_recursion_fails", "tests/test_main.py::test_not_required", "tests/test_main.py::test_infer_type", "tests/test_main.py::test_allow_extra", "tests/test_main.py::test_forbidden_extra_success", "tests/test_main.py::test_forbidden_extra_fails", "tests/test_main.py::test_disallow_mutation", "tests/test_main.py::test_extra_allowed", "tests/test_main.py::test_extra_ignored", "tests/test_main.py::test_set_attr", "tests/test_main.py::test_set_attr_invalid", "tests/test_main.py::test_any", "tests/test_main.py::test_alias", "tests/test_main.py::test_population_by_field_name", "tests/test_main.py::test_field_order", "tests/test_main.py::test_required", "tests/test_main.py::test_not_immutability", "tests/test_main.py::test_immutability", "tests/test_main.py::test_const_validates", "tests/test_main.py::test_const_uses_default", "tests/test_main.py::test_const_with_wrong_value", "tests/test_main.py::test_const_list", "tests/test_main.py::test_const_list_with_wrong_value", "tests/test_main.py::test_const_validation_json_serializable", "tests/test_main.py::test_validating_assignment_pass", "tests/test_main.py::test_validating_assignment_fail", "tests/test_main.py::test_enum_values", "tests/test_main.py::test_enum_raw", "tests/test_main.py::test_set_tuple_values", "tests/test_main.py::test_default_copy", "tests/test_main.py::test_arbitrary_type_allowed_validation_success", "tests/test_main.py::test_arbitrary_type_allowed_validation_fails", "tests/test_main.py::test_arbitrary_types_not_allowed", "tests/test_main.py::test_type_type_validation_success", "tests/test_main.py::test_type_type_subclass_validation_success", "tests/test_main.py::test_type_type_validation_fails_for_instance", "tests/test_main.py::test_type_type_validation_fails_for_basic_type", "tests/test_main.py::test_annotation_field_name_shadows_attribute", "tests/test_main.py::test_value_field_name_shadows_attribute", "tests/test_main.py::test_class_var", "tests/test_main.py::test_fields_set", "tests/test_main.py::test_exclude_unset_dict", "tests/test_main.py::test_exclude_unset_recursive", "tests/test_main.py::test_dict_exclude_unset_populated_by_alias", "tests/test_main.py::test_dict_exclude_unset_populated_by_alias_with_extra", "tests/test_main.py::test_dir_fields", "tests/test_main.py::test_dict_with_extra_keys", "tests/test_main.py::test_alias_generator", "tests/test_main.py::test_alias_generator_with_field_schema", "tests/test_main.py::test_alias_generator_wrong_type_error", "tests/test_main.py::test_root", "tests/test_main.py::test_root_list", "tests/test_main.py::test_root_failed", "tests/test_main.py::test_root_undefined_failed", "tests/test_main.py::test_untouched_types", "tests/test_main.py::test_custom_types_fail_without_keep_untouched", "tests/test_main.py::test_model_iteration", "tests/test_main.py::test_custom_init_subclass_params" ]
{ "failed_lite_validators": [ "has_added_files", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2019-11-02 23:31:50+00:00
mit
4,922
pydantic__pydantic-980
diff --git a/docs/examples/dataclasses_default_schema.py b/docs/examples/dataclasses_default_schema.py new file mode 100644 --- /dev/null +++ b/docs/examples/dataclasses_default_schema.py @@ -0,0 +1,12 @@ +import dataclasses +from typing import List +from pydantic.dataclasses import dataclass + +@dataclass +class User: + id: int + name: str = 'John Doe' + friends: List[int] = dataclasses.field(default_factory=lambda: [0]) + +user = User(id='42') +print(user.__pydantic_model__.schema()) diff --git a/pydantic/dataclasses.py b/pydantic/dataclasses.py --- a/pydantic/dataclasses.py +++ b/pydantic/dataclasses.py @@ -83,10 +83,18 @@ def _pydantic_post_init(self: 'DataclassType', *initvars: Any) -> None: _cls.__post_init__ = _pydantic_post_init cls = dataclasses._process_class(_cls, init, repr, eq, order, unsafe_hash, frozen) # type: ignore - fields: Dict[str, Any] = { - field.name: (field.type, field.default if field.default != dataclasses.MISSING else Required) - for field in dataclasses.fields(cls) - } + fields: Dict[str, Any] = {} + for field in dataclasses.fields(cls): + + if field.default != dataclasses.MISSING: + field_value = field.default + # mypy issue 7020 and 708 + elif field.default_factory != dataclasses.MISSING: # type: ignore + field_value = field.default_factory() # type: ignore + else: + field_value = Required + + fields[field.name] = (field.type, field_value) validators = gather_all_validators(cls) cls.__pydantic_model__ = create_model(
pydantic/pydantic
093474ae27d9e1737d6aa76bd6b75f3918acd2e2
This isn't a bug, but a feature request. ```py class Config: fields = {"b": { "required": False}} ``` Wouldn't work on a normal model. I think what you want is better support for the `field()` function from dataclasses. If so, please describe exactly what parts of `field()` usage you'd like to support in pydantic. Is it just the default in schema? Thanks for clarifying! Only handling `default*` in schema is what we need to support. However, it would be nice to have a stable interface for `.__pydantic_model__`. I'm not sure if this might change. `__pydantic_model__` won't change, we should document it. It would be wonderful if you could create a PR for that. :smile: i'm going for it
diff --git a/tests/test_dataclasses.py b/tests/test_dataclasses.py --- a/tests/test_dataclasses.py +++ b/tests/test_dataclasses.py @@ -1,7 +1,7 @@ import dataclasses from datetime import datetime from pathlib import Path -from typing import ClassVar, FrozenSet, Optional +from typing import ClassVar, Dict, FrozenSet, Optional import pytest @@ -403,11 +403,28 @@ class User: assert fields['signup_ts'].default is None +def test_default_factory_field(): + @pydantic.dataclasses.dataclass + class User: + id: int + aliases: Dict[str, str] = dataclasses.field(default_factory=lambda: {'John': 'Joey'}) + + user = User(id=123) + fields = user.__pydantic_model__.__fields__ + + assert fields['id'].required is True + assert fields['id'].default is None + + assert fields['aliases'].required is False + assert fields['aliases'].default == {'John': 'Joey'} + + def test_schema(): @pydantic.dataclasses.dataclass class User: id: int name: str = 'John Doe' + aliases: Dict[str, str] = dataclasses.field(default_factory=lambda: {'John': 'Joey'}) signup_ts: datetime = None user = User(id=123) @@ -417,6 +434,12 @@ class User: 'properties': { 'id': {'title': 'Id', 'type': 'integer'}, 'name': {'title': 'Name', 'default': 'John Doe', 'type': 'string'}, + 'aliases': { + 'title': 'Aliases', + 'default': {'John': 'Joey'}, + 'type': 'object', + 'additionalProperties': {'type': 'string'}, + }, 'signup_ts': {'title': 'Signup Ts', 'type': 'string', 'format': 'date-time'}, }, 'required': ['id'],
dataclass field doesn't change required schema # Bug Please complete: * OS: Mac OS * Python version `import sys; print(sys.version)`: **3.6.7** with dataclasses backport * Pydantic version `import pydantic; print(pydantic.VERSION)`: **1.0** It is known that `@pydantic.dataclasses.dataclass` doesn't fully mimic the `BaseModel`. However, we'd like use `.schema()` representation faithfully. I'm wondering what's the best workaround. Adding a `Config` for `b` with `required=False` doesn't carry over to `.schema()` either. ```py from typing import Dict from dataclasses import field from pydantic import Field, ValidationError from pydantic.dataclasses import dataclass @dataclass class D1: a: int # b: Dict[str, int] = {"x":10} # mutable default, not allowed @dataclass class D2: a: int b: Dict[str, int] = Field({"x":10}) # pydantic.Field, unsafe and invalid default @dataclass class D3: a: int b: Dict[str, int] = field(default_factory=lambda: {"x":10}) # std lib, safe and invalid default class C: fields = {"b": { "required": False}} # doesn't carry over!! @dataclass(config=C) class D4: a: int b: Dict[str, int] = field(default_factory=lambda: {"x":10}) print(D1(10)) try: print(D2(10)) except ValidationError as e: print(e) # pydantic/dataclasses.py:77 print(D3(10)) req = D3.__pydantic_model__.schema()["required"] if req != ["a"]: print('only ["a"] should be required, is:', req) print() print(D4.__pydantic_model__.schema()["required"]) # same as D3 ``` Output ``` D1(a=10) 1 validation error for D2 b value is not a valid dict (type=type_error.dict) D3(a=10, b={'x': 10}) only ["a"] should be required, is: ['a', 'b'] ['a', 'b'] ```
0.0
093474ae27d9e1737d6aa76bd6b75f3918acd2e2
[ "tests/test_dataclasses.py::test_default_factory_field", "tests/test_dataclasses.py::test_schema" ]
[ "tests/test_dataclasses.py::test_simple", "tests/test_dataclasses.py::test_value_error", "tests/test_dataclasses.py::test_frozen", "tests/test_dataclasses.py::test_validate_assignment", "tests/test_dataclasses.py::test_validate_assignment_error", "tests/test_dataclasses.py::test_not_validate_assignment", "tests/test_dataclasses.py::test_validate_assignment_value_change", "tests/test_dataclasses.py::test_validate_assignment_extra", "tests/test_dataclasses.py::test_post_init", "tests/test_dataclasses.py::test_post_init_inheritance_chain", "tests/test_dataclasses.py::test_post_init_post_parse", "tests/test_dataclasses.py::test_post_init_post_parse_types", "tests/test_dataclasses.py::test_post_init_assignment", "tests/test_dataclasses.py::test_inheritance", "tests/test_dataclasses.py::test_validate_long_string_error", "tests/test_dataclasses.py::test_validate_assigment_long_string_error", "tests/test_dataclasses.py::test_no_validate_assigment_long_string_error", "tests/test_dataclasses.py::test_nested_dataclass", "tests/test_dataclasses.py::test_arbitrary_types_allowed", "tests/test_dataclasses.py::test_nested_dataclass_model", "tests/test_dataclasses.py::test_fields", "tests/test_dataclasses.py::test_nested_schema", "tests/test_dataclasses.py::test_initvar", "tests/test_dataclasses.py::test_derived_field_from_initvar", "tests/test_dataclasses.py::test_initvars_post_init", "tests/test_dataclasses.py::test_initvars_post_init_post_parse", "tests/test_dataclasses.py::test_classvar", "tests/test_dataclasses.py::test_frozenset_field", "tests/test_dataclasses.py::test_inheritance_post_init" ]
{ "failed_lite_validators": [ "has_added_files" ], "has_test_patch": true, "is_lite": false }
2019-11-08 08:06:56+00:00
mit
4,923
pydata__pydata-google-auth-17
diff --git a/docs/source/changelog.rst b/docs/source/changelog.rst index 49a0433..0e07cd3 100644 --- a/docs/source/changelog.rst +++ b/docs/source/changelog.rst @@ -1,6 +1,19 @@ Changelog ========= +.. _changelog-0.1.3: + +0.1.3 / TBD +----------- + +Bug Fixes +^^^^^^^^^ + +- Respect the ``dirname`` and ``filename`` arguments to the + :class:`~pydata_google_auth.cache.ReadWriteCredentialsCache` and + :class:`~pydata_google_auth.cache.WriteOnlyCredentialsCache` constructors. + (:issue:`16`, :issue:`17`) + .. _changelog-0.1.2: 0.1.2 / (2019-02-01) diff --git a/pydata_google_auth/cache.py b/pydata_google_auth/cache.py index a5d7aa6..cd2ff61 100644 --- a/pydata_google_auth/cache.py +++ b/pydata_google_auth/cache.py @@ -169,7 +169,7 @@ class ReadWriteCredentialsCache(CredentialsCache): def __init__(self, dirname=_DIRNAME, filename=_FILENAME): super(ReadWriteCredentialsCache, self).__init__() - self._path = _get_default_credentials_path(_DIRNAME, _FILENAME) + self._path = _get_default_credentials_path(dirname, filename) def load(self): """ @@ -215,7 +215,7 @@ class WriteOnlyCredentialsCache(CredentialsCache): def __init__(self, dirname=_DIRNAME, filename=_FILENAME): super(WriteOnlyCredentialsCache, self).__init__() - self._path = _get_default_credentials_path(_DIRNAME, _FILENAME) + self._path = _get_default_credentials_path(dirname, filename) def save(self, credentials): """
pydata/pydata-google-auth
574eb5204cf43bc5832cfe26b4fff239adf96aa8
diff --git a/tests/unit/test_cache.py b/tests/unit/test_cache.py index 672f72f..cc0ff34 100644 --- a/tests/unit/test_cache.py +++ b/tests/unit/test_cache.py @@ -54,3 +54,31 @@ def test__save_user_account_credentials_wo_directory(module_under_test, fs): with open(path) as fp: serialized_data = json.load(fp) assert serialized_data["refresh_token"] == "refresh_token" + + +def test_ReadWriteCredentialsCache_sets_path(module_under_test): + """ReadWriteCredentialsCache ctor should respect dirname and filename. + + See: https://github.com/pydata/pydata-google-auth/issues/16 + """ + cache = module_under_test.ReadWriteCredentialsCache( + dirname="dirtest", filename="filetest.json" + ) + path = os.path.normpath(cache._path) + parts = path.split(os.sep) + assert parts[-2] == "dirtest" + assert parts[-1] == "filetest.json" + + +def test_WriteOnlyCredentialsCache_sets_path(module_under_test): + """ReadWriteCredentialsCache ctor should respect dirname and filename. + + See: https://github.com/pydata/pydata-google-auth/issues/16 + """ + cache = module_under_test.WriteOnlyCredentialsCache( + dirname="dirtest", filename="filetest.json" + ) + path = os.path.normpath(cache._path) + parts = path.split(os.sep) + assert parts[-2] == "dirtest" + assert parts[-1] == "filetest.json"
"dirname" and "filename" not used in ReadWriteCredentialsCache The arguments "dirname" and "filename" are never used. Instead "_DIRNAME" and "_FILENAME" are used. → `self._path = _get_default_credentials_path(_DIRNAME, _FILENAME)` I think it should be: → `self._path = _get_default_credentials_path(dirname, filename)`
0.0
574eb5204cf43bc5832cfe26b4fff239adf96aa8
[ "tests/unit/test_cache.py::test_ReadWriteCredentialsCache_sets_path", "tests/unit/test_cache.py::test_WriteOnlyCredentialsCache_sets_path" ]
[ "tests/unit/test_cache.py::test_import_unwriteable_fs" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2019-02-26 16:00:57+00:00
bsd-3-clause
4,924
pydata__pydata-google-auth-31
diff --git a/pydata_google_auth/cache.py b/pydata_google_auth/cache.py index 13b9457..cad9097 100644 --- a/pydata_google_auth/cache.py +++ b/pydata_google_auth/cache.py @@ -25,9 +25,11 @@ def _get_default_credentials_path(credentials_dirname, credentials_filename): str Path to the Google user credentials """ + config_path = None + if os.name == "nt": - config_path = os.environ["APPDATA"] - else: + config_path = os.getenv("APPDATA") + if not config_path: config_path = os.path.join(os.path.expanduser("~"), ".config") config_path = os.path.join(config_path, credentials_dirname)
pydata/pydata-google-auth
510f49696fb3d3aa1a77a29a0ee2125ca14ddde4
diff --git a/tests/unit/test_cache.py b/tests/unit/test_cache.py index d2fdea2..1e513c3 100644 --- a/tests/unit/test_cache.py +++ b/tests/unit/test_cache.py @@ -34,6 +34,19 @@ def test_import_unwriteable_fs(module_under_test, monkeypatch): assert module_under_test.NOOP is not None +def test__get_default_credentials_path_windows_wo_appdata( + module_under_test, monkeypatch +): + # Ensure default path returns something sensible on Windows, even if + # APPDATA is not set. See: + # https://github.com/pydata/pydata-google-auth/issues/29 + monkeypatch.setattr(os, "name", "nt") + monkeypatch.delenv("APPDATA", raising=False) + + creds_path = module_under_test._get_default_credentials_path("dirname", "filename") + assert creds_path is not None + + def test__save_user_account_credentials_wo_directory(module_under_test, fs): """Directories should be created if they don't exist."""
APPDATA environment variable must exist when running on windows The os.environ['APPDATA'] lookup in Cache.py line 29 always gets run, even if credentials are passed. `%APPDATA%` is not guaranteed to be set, as it is not on the windows 2012R2 server service accounts that I have been attempting to use. The resulting error message when APPDATA is not set is quite opaque. Especially as the call which triggers the error, like my pandas.to_gbq() call, could have explicitly passed credentials. This problem can be worked-around with `IF "%APPDATA%"=="" set APPDATA="PYDATA-GOOGLE-AUTH needs this to be set"`
0.0
510f49696fb3d3aa1a77a29a0ee2125ca14ddde4
[ "tests/unit/test_cache.py::test_import_unwriteable_fs", "tests/unit/test_cache.py::test__get_default_credentials_path_windows_wo_appdata", "tests/unit/test_cache.py::test_ReadWriteCredentialsCache_sets_path", "tests/unit/test_cache.py::test_WriteOnlyCredentialsCache_sets_path" ]
[]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2019-12-12 21:22:33+00:00
bsd-3-clause
4,925
pydata__pydata-google-auth-40
diff --git a/docs/source/api.rst b/docs/source/api.rst index 24e03ed..f480e1a 100644 --- a/docs/source/api.rst +++ b/docs/source/api.rst @@ -11,6 +11,7 @@ API Reference get_user_credentials load_user_credentials save_user_credentials + load_service_account_credentials cache.CredentialsCache cache.READ_WRITE cache.REAUTH diff --git a/docs/source/changelog.rst b/docs/source/changelog.rst index 71747be..aa1a9a6 100644 --- a/docs/source/changelog.rst +++ b/docs/source/changelog.rst @@ -1,6 +1,12 @@ Changelog ========= +Unreleased / TBD +---------------- + +- Adds :func:`pydata_google_auth.load_service_account_credentials` function to + get service account credentials from the specified JSON path. (:issue:`39`) + .. _changelog-1.1.0: 1.1.0 / (2020-04-23) diff --git a/pydata_google_auth/__init__.py b/pydata_google_auth/__init__.py index dafec61..9ea95f5 100644 --- a/pydata_google_auth/__init__.py +++ b/pydata_google_auth/__init__.py @@ -2,6 +2,7 @@ from .auth import default from .auth import get_user_credentials from .auth import load_user_credentials from .auth import save_user_credentials +from .auth import load_service_account_credentials from ._version import get_versions versions = get_versions() @@ -20,4 +21,5 @@ __all__ = [ "get_user_credentials", "load_user_credentials", "save_user_credentials", + "load_service_account_credentials", ] diff --git a/pydata_google_auth/auth.py b/pydata_google_auth/auth.py index 6c9a7ba..7ac86ce 100644 --- a/pydata_google_auth/auth.py +++ b/pydata_google_auth/auth.py @@ -402,3 +402,51 @@ def load_user_credentials(path): if not credentials: raise exceptions.PyDataCredentialsError("Could not load credentials.") return credentials + + +def load_service_account_credentials(path, scopes=None): + """ + Gets service account credentials from JSON file at ``path``. + + Parameters + ---------- + path : str + Path to credentials JSON file. + scopes : list[str], optional + A list of scopes to use when authenticating to Google APIs. See the + `list of OAuth 2.0 scopes for Google APIs + <https://developers.google.com/identity/protocols/googlescopes>`_. + + Returns + ------- + + google.oauth2.service_account.Credentials + + Raises + ------ + pydata_google_auth.exceptions.PyDataCredentialsError + If unable to load service credentials. + + Examples + -------- + + Load credentials and use them to construct a BigQuery client. + + .. code-block:: python + + import pydata_google_auth + import google.cloud.bigquery + + credentials = pydata_google_auth.load_service_account_credentials( + "/home/username/keys/google-service-account-credentials.json", + ) + client = google.cloud.bigquery.BigQueryClient( + credentials=credentials, + project=credentials.project_id + ) + """ + + credentials = cache._load_service_account_credentials_from_file(path, scopes=scopes) + if not credentials: + raise exceptions.PyDataCredentialsError("Could not load credentials.") + return credentials diff --git a/pydata_google_auth/cache.py b/pydata_google_auth/cache.py index cad9097..16051a3 100644 --- a/pydata_google_auth/cache.py +++ b/pydata_google_auth/cache.py @@ -7,6 +7,7 @@ import os import os.path import google.oauth2.credentials +from google.oauth2 import service_account logger = logging.getLogger(__name__) @@ -123,6 +124,34 @@ def _save_user_account_credentials(credentials, credentials_path): logger.warning("Unable to save credentials.") +def _load_service_account_credentials_from_file(credentials_path, **kwargs): + try: + with open(credentials_path) as credentials_file: + credentials_json = json.load(credentials_file) + except (IOError, ValueError) as exc: + logger.debug( + "Error loading credentials from {}: {}".format(credentials_path, str(exc)) + ) + return None + + return _load_service_account_credentials_from_info(credentials_json, **kwargs) + + +def _load_service_account_credentials_from_info(credentials_json, **kwargs): + credentials = service_account.Credentials.from_service_account_info( + credentials_json, **kwargs + ) + if not credentials.valid: + request = google.auth.transport.requests.Request() + try: + credentials.refresh(request) + except google.auth.exceptions.RefreshError: + # Credentials could be expired or revoked. + return None + + return credentials + + class CredentialsCache(object): """ Shared base class for crentials classes.
pydata/pydata-google-auth
c7f74594a8d2283d0685b7a427b4eba2ea6c75d1
diff --git a/tests/unit/test_auth.py b/tests/unit/test_auth.py index 7eadd2c..993d02b 100644 --- a/tests/unit/test_auth.py +++ b/tests/unit/test_auth.py @@ -10,6 +10,7 @@ import google.auth.credentials import google.oauth2.credentials import pytest +from google.oauth2 import service_account from pydata_google_auth import exceptions @@ -56,6 +57,33 @@ def test_default_loads_user_credentials(monkeypatch, module_under_test): assert credentials is mock_user_credentials +class FakeCredentials(object): + @property + def valid(self): + return True + + +def test_load_service_account_credentials(monkeypatch, tmp_path, module_under_test): + creds_path = str(tmp_path / "creds.json") + with open(creds_path, "w") as stream: + stream.write("{}") + + fake_creds = FakeCredentials() + mock_service = mock.create_autospec(service_account.Credentials) + mock_service.from_service_account_info.return_value = fake_creds + monkeypatch.setattr(service_account, "Credentials", mock_service) + + creds = module_under_test.load_service_account_credentials(creds_path) + assert creds is fake_creds + + def test_load_user_credentials_raises_when_file_doesnt_exist(module_under_test): with pytest.raises(exceptions.PyDataCredentialsError): module_under_test.load_user_credentials("path/not/found.json") + + +def test_load_service_account_credentials_raises_when_file_doesnt_exist( + module_under_test, +): + with pytest.raises(exceptions.PyDataCredentialsError): + module_under_test.load_service_account_credentials("path/not/found.json")
ENH: Support authentication with service accounts Service accounts use a different credentials class (`google.oauth2.service_account.Credentials`) and mostly used within a file that is expored from GCP console. It would be nice to have a `pydata_google_auth.load_service_account_credentials(path: os.PathLike) -> Credentials` method which does the initalization.
0.0
c7f74594a8d2283d0685b7a427b4eba2ea6c75d1
[ "tests/unit/test_auth.py::test_load_service_account_credentials", "tests/unit/test_auth.py::test_load_service_account_credentials_raises_when_file_doesnt_exist" ]
[ "tests/unit/test_auth.py::test_default_returns_google_auth_credentials", "tests/unit/test_auth.py::test_default_loads_user_credentials", "tests/unit/test_auth.py::test_load_user_credentials_raises_when_file_doesnt_exist" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-02-12 09:17:52+00:00
bsd-3-clause
4,926
pydata__sparse-226
diff --git a/sparse/coo/core.py b/sparse/coo/core.py index 71fe0d5..727df16 100644 --- a/sparse/coo/core.py +++ b/sparse/coo/core.py @@ -479,11 +479,9 @@ class COO(SparseArray, NDArrayOperatorsMixin): ndim = 0 if shape is None else len(shape) coords = np.empty((ndim, 0), dtype=np.uint8) data = np.empty((0,)) + shape = () if shape is None else shape - return COO(coords, data, shape=() if shape is None else shape, - sorted=True, has_duplicates=False) - - if not isinstance(x[0][0], Iterable): + elif not isinstance(x[0][0], Iterable): coords = np.stack(x[1], axis=0) data = np.asarray(x[0]) else: diff --git a/sparse/dok.py b/sparse/dok.py index b4f1233..1351cbd 100644 --- a/sparse/dok.py +++ b/sparse/dok.py @@ -125,7 +125,7 @@ class DOK(SparseArray): def _make_shallow_copy_of(self, other): self.dtype = other.dtype self.data = other.data - super(DOK, self).__init__(other.shape) + super(DOK, self).__init__(other.shape, fill_value=other.fill_value) @classmethod def from_coo(cls, x):
pydata/sparse
b7381b4298878ae1642d679e4b129cadb43302f4
diff --git a/sparse/tests/test_dok.py b/sparse/tests/test_dok.py index 2443f33..e9d3d4a 100644 --- a/sparse/tests/test_dok.py +++ b/sparse/tests/test_dok.py @@ -169,3 +169,11 @@ def test_asformat(format): s2 = s.asformat(format) assert_eq(s, s2) + + +def test_coo_fv_interface(): + s1 = sparse.full((5, 5), fill_value=1+np.random.rand()) + s2 = sparse.DOK(s1) + assert_eq(s1, s2) + s3 = sparse.COO(s2) + assert_eq(s1, s3)
Bug in converting from DOK to COO I originally noticed this bug when I tried the following, `sparse.DOK.from_coo(sparse.ones((2,2), dtype=bool)).to_coo().todense()`. It yields ``` array([[0., 0.], [0., 0.]]) ``` However, the issue is even more basic for example the following: `sparse.DOK.from_coo(sparse.ones((2,2))).to_coo().todense()`, yields the same result, ``` array([[0., 0.], [0., 0.]]) ``` The correct results ought to be ``` array([[True, True], [True, True]]) ``` and ``` array([[1., 1.], [1., 1.]]) ```
0.0
b7381b4298878ae1642d679e4b129cadb43302f4
[ "sparse/tests/test_dok.py::test_setitem[shape0-index0-0.24378411847456782]", "sparse/tests/test_dok.py::test_setitem[shape1-index1-0.4655835128747583]", "sparse/tests/test_dok.py::test_setitem[shape3-1-0.6611644715879794]", "sparse/tests/test_dok.py::test_setitem[shape4-index4-0.44921796957042237]", "sparse/tests/test_dok.py::test_setitem[shape5-index5-0.6755965596371413]", "sparse/tests/test_dok.py::test_setitem[shape9-index9-0.9169802728671987]", "sparse/tests/test_dok.py::test_setitem[shape11-index11-0.1490395247941586]", "sparse/tests/test_dok.py::test_setitem[shape13-index13-0.0810663815477296]", "sparse/tests/test_dok.py::test_coo_fv_interface" ]
[ "sparse/tests/test_dok.py::flake-8::FLAKE8", "sparse/tests/test_dok.py::test_random_shape_nnz[0.1-shape0]", "sparse/tests/test_dok.py::test_random_shape_nnz[0.1-shape1]", "sparse/tests/test_dok.py::test_random_shape_nnz[0.1-shape2]", "sparse/tests/test_dok.py::test_random_shape_nnz[0.3-shape0]", "sparse/tests/test_dok.py::test_random_shape_nnz[0.3-shape1]", "sparse/tests/test_dok.py::test_random_shape_nnz[0.3-shape2]", "sparse/tests/test_dok.py::test_random_shape_nnz[0.5-shape0]", "sparse/tests/test_dok.py::test_random_shape_nnz[0.5-shape1]", "sparse/tests/test_dok.py::test_random_shape_nnz[0.5-shape2]", "sparse/tests/test_dok.py::test_random_shape_nnz[0.7-shape0]", "sparse/tests/test_dok.py::test_random_shape_nnz[0.7-shape1]", "sparse/tests/test_dok.py::test_random_shape_nnz[0.7-shape2]", "sparse/tests/test_dok.py::test_convert_to_coo", "sparse/tests/test_dok.py::test_convert_from_coo", "sparse/tests/test_dok.py::test_convert_from_numpy", "sparse/tests/test_dok.py::test_convert_to_numpy", "sparse/tests/test_dok.py::test_construct[2-data0]", "sparse/tests/test_dok.py::test_construct[shape1-data1]", "sparse/tests/test_dok.py::test_construct[shape2-data2]", "sparse/tests/test_dok.py::test_getitem[0.1-shape0]", "sparse/tests/test_dok.py::test_getitem[0.1-shape1]", "sparse/tests/test_dok.py::test_getitem[0.1-shape2]", "sparse/tests/test_dok.py::test_getitem[0.3-shape0]", "sparse/tests/test_dok.py::test_getitem[0.3-shape1]", "sparse/tests/test_dok.py::test_getitem[0.3-shape2]", "sparse/tests/test_dok.py::test_getitem[0.5-shape0]", "sparse/tests/test_dok.py::test_getitem[0.5-shape1]", "sparse/tests/test_dok.py::test_getitem[0.5-shape2]", "sparse/tests/test_dok.py::test_getitem[0.7-shape0]", "sparse/tests/test_dok.py::test_getitem[0.7-shape1]", "sparse/tests/test_dok.py::test_getitem[0.7-shape2]", "sparse/tests/test_dok.py::test_setitem[shape2-index2-value2]", "sparse/tests/test_dok.py::test_setitem[shape6-index6-value6]", "sparse/tests/test_dok.py::test_setitem[shape7-index7-value7]", "sparse/tests/test_dok.py::test_setitem[shape8-index8-value8]", "sparse/tests/test_dok.py::test_setitem[shape10-index10-value10]", "sparse/tests/test_dok.py::test_setitem[shape12-index12-value12]", "sparse/tests/test_dok.py::test_default_dtype", "sparse/tests/test_dok.py::test_int_dtype", "sparse/tests/test_dok.py::test_float_dtype", "sparse/tests/test_dok.py::test_set_zero", "sparse/tests/test_dok.py::test_asformat[coo]", "sparse/tests/test_dok.py::test_asformat[dok]" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2018-12-27 16:43:07+00:00
bsd-3-clause
4,927
pydata__sparse-94
diff --git a/sparse/dok.py b/sparse/dok.py index 65ede6f..9beaada 100644 --- a/sparse/dok.py +++ b/sparse/dok.py @@ -339,8 +339,11 @@ class DOK(object): raise IndexError('All indices must be slices or integers' ' when setting an item.') + key = tuple(key_list) if value != _zero_of_dtype(self.dtype): - self.data[tuple(key_list)] = value[()] + self.data[key] = value[()] + elif key in self.data: + del self.data[key] def __str__(self): return "<DOK: shape=%s, dtype=%s, nnz=%d>" % (self.shape, self.dtype, self.nnz)
pydata/sparse
80e9abc41c0e6238eafe20a7696ccfa9a32eec5d
diff --git a/sparse/tests/test_dok.py b/sparse/tests/test_dok.py index 568c1d0..45c9899 100644 --- a/sparse/tests/test_dok.py +++ b/sparse/tests/test_dok.py @@ -149,3 +149,12 @@ def test_float_dtype(): s = DOK((5,), data) assert s.dtype == np.float32 + + +def test_set_zero(): + s = DOK((1,), dtype=np.uint8) + s[0] = 1 + s[0] = 0 + + assert s[0] == 0 + assert s.nnz == 0
Setting DOK elements to zero doesn't work. Trivial example: ``` >>> import sparse >>> import numpy as np >>> s = sparse.DOK((1,)) >>> s[0] = 1 >>> s[0] 1.0 >>> s[0] = 0 >>> s[0] 1.0 ```
0.0
80e9abc41c0e6238eafe20a7696ccfa9a32eec5d
[ "sparse/tests/test_dok.py::test_setitem[shape0-index0-0.8955187055746776]", "sparse/tests/test_dok.py::test_setitem[shape1-index1-0.3518569369389797]", "sparse/tests/test_dok.py::test_setitem[shape3-1-0.23848692220254797]", "sparse/tests/test_dok.py::test_setitem[shape4-index4-0.22260470500706064]", "sparse/tests/test_dok.py::test_setitem[shape5-index5-0.7520164007372592]", "sparse/tests/test_dok.py::test_setitem[shape9-index9-0.4678733721507552]", "sparse/tests/test_dok.py::test_setitem[shape11-index11-0.02529711593219741]", "sparse/tests/test_dok.py::test_setitem[shape13-index13-0.5484454606790654]", "sparse/tests/test_dok.py::test_set_zero" ]
[ "sparse/tests/test_dok.py::flake-8::FLAKE8", "sparse/tests/test_dok.py::test_random_shape_nnz[0.1-shape0]", "sparse/tests/test_dok.py::test_random_shape_nnz[0.1-shape1]", "sparse/tests/test_dok.py::test_random_shape_nnz[0.1-shape2]", "sparse/tests/test_dok.py::test_random_shape_nnz[0.3-shape0]", "sparse/tests/test_dok.py::test_random_shape_nnz[0.3-shape1]", "sparse/tests/test_dok.py::test_random_shape_nnz[0.3-shape2]", "sparse/tests/test_dok.py::test_random_shape_nnz[0.5-shape0]", "sparse/tests/test_dok.py::test_random_shape_nnz[0.5-shape1]", "sparse/tests/test_dok.py::test_random_shape_nnz[0.5-shape2]", "sparse/tests/test_dok.py::test_random_shape_nnz[0.7-shape0]", "sparse/tests/test_dok.py::test_random_shape_nnz[0.7-shape1]", "sparse/tests/test_dok.py::test_random_shape_nnz[0.7-shape2]", "sparse/tests/test_dok.py::test_convert_to_coo", "sparse/tests/test_dok.py::test_convert_from_coo", "sparse/tests/test_dok.py::test_convert_from_numpy", "sparse/tests/test_dok.py::test_convert_to_numpy", "sparse/tests/test_dok.py::test_construct[2-data0]", "sparse/tests/test_dok.py::test_construct[shape1-data1]", "sparse/tests/test_dok.py::test_construct[shape2-data2]", "sparse/tests/test_dok.py::test_getitem[0.1-shape0]", "sparse/tests/test_dok.py::test_getitem[0.1-shape1]", "sparse/tests/test_dok.py::test_getitem[0.1-shape2]", "sparse/tests/test_dok.py::test_getitem[0.3-shape0]", "sparse/tests/test_dok.py::test_getitem[0.3-shape1]", "sparse/tests/test_dok.py::test_getitem[0.3-shape2]", "sparse/tests/test_dok.py::test_getitem[0.5-shape0]", "sparse/tests/test_dok.py::test_getitem[0.5-shape1]", "sparse/tests/test_dok.py::test_getitem[0.5-shape2]", "sparse/tests/test_dok.py::test_getitem[0.7-shape0]", "sparse/tests/test_dok.py::test_getitem[0.7-shape1]", "sparse/tests/test_dok.py::test_getitem[0.7-shape2]", "sparse/tests/test_dok.py::test_setitem[shape2-index2-value2]", "sparse/tests/test_dok.py::test_setitem[shape6-index6-value6]", "sparse/tests/test_dok.py::test_setitem[shape7-index7-value7]", "sparse/tests/test_dok.py::test_setitem[shape8-index8-value8]", "sparse/tests/test_dok.py::test_setitem[shape10-index10-value10]", "sparse/tests/test_dok.py::test_setitem[shape12-index12-value12]", "sparse/tests/test_dok.py::test_default_dtype", "sparse/tests/test_dok.py::test_int_dtype", "sparse/tests/test_dok.py::test_float_dtype" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2018-01-27 09:16:07+00:00
bsd-3-clause
4,928
pydicom__pynetdicom-332
diff --git a/docs/changelog/v1.3.0.rst b/docs/changelog/v1.3.0.rst index 5304f72c6..a99244f42 100644 --- a/docs/changelog/v1.3.0.rst +++ b/docs/changelog/v1.3.0.rst @@ -17,7 +17,9 @@ Fixes of just re-using 1. (:issue:`315`) * The default ``logging`` configuration no longer uses a non-NullHandler (:issue:`321`) -* Fix Unified Procedure Step's SOP Class UID variable names +* Fixed Unified Procedure Step's SOP Class UID variable names +* Fixed memory leak caused by keeping old ``Association`` threads around after + they died (:issue:`328`) Enhancements diff --git a/pynetdicom/association.py b/pynetdicom/association.py index 94d08f7c5..68ad63067 100644 --- a/pynetdicom/association.py +++ b/pynetdicom/association.py @@ -1,6 +1,7 @@ """ Defines the Association class which handles associating with peers. """ +import gc from io import BytesIO import logging import threading @@ -130,6 +131,10 @@ class Association(threading.Thread): self._ae = ae self.mode = mode + # If acceptor this is the parent AssociationServer, used to identify + # the thread when updating bound event-handlers + self._server = None + # Represents the association requestor and acceptor users self.requestor = ServiceUser(self, MODE_REQUESTOR) self.acceptor = ServiceUser(self, MODE_ACCEPTOR) diff --git a/pynetdicom/pdu_items.py b/pynetdicom/pdu_items.py index 5f65a2064..4570836a8 100644 --- a/pynetdicom/pdu_items.py +++ b/pynetdicom/pdu_items.py @@ -125,7 +125,8 @@ class PDUItem(object): if other is self: return True - if isinstance(other, self.__class__): + if isinstance(other, type(self)): + # Use the values of the class attributes that get encoded self_dict = { en[0]: getattr(self, en[0]) for en in self._encoders if en[0] } @@ -216,11 +217,7 @@ class PDUItem(object): @property def item_type(self): """Return the item's *Item Type* field value as an int.""" - key_val = PDU_ITEM_TYPES.items() - keys = [key for (key, val) in key_val] - vals = [val for (key, val) in key_val] - - return keys[vals.index(self.__class__)] + return {vv: kk for kk, vv in PDU_ITEM_TYPES.items()}[type(self)] def __len__(self): """Return the total length of the encoded item as an int.""" diff --git a/pynetdicom/transport.py b/pynetdicom/transport.py index 7b517efd3..fd7a80420 100644 --- a/pynetdicom/transport.py +++ b/pynetdicom/transport.py @@ -342,6 +342,7 @@ class RequestHandler(BaseRequestHandler): from pynetdicom.association import Association assoc = Association(self.ae, MODE_ACCEPTOR) + assoc._server = self.server # Set the thread name timestamp = datetime.strftime(datetime.now(), "%Y%m%d%H%M%S") @@ -385,9 +386,6 @@ class RequestHandler(BaseRequestHandler): assoc.start() - # Track the server's associations - self.server._children.append(assoc) - @property def local(self): """Return a 2-tuple of the local server's ``(host, port)`` address.""" @@ -448,10 +446,8 @@ class AssociationServer(TCPServer): self.timeout = 60 - # Tracks child Association acceptors - self._children = [] # Stores all currently bound event handlers so future - # children can be bound + # Associations can be bound self._handlers = {} self._bind_defaults() @@ -506,9 +502,11 @@ class AssociationServer(TCPServer): @property def active_associations(self): """Return the server's running ``Association`` acceptor instances""" - self._children = [ - child for child in self._children if child.is_alive()] - return self._children + # Find all AcceptorThreads with `_server` as self + threads = [ + tt for tt in threading.enumerate() if 'AcceptorThread' in tt.name + ] + return [tt for tt in threads if tt._server is self] def get_events(self): """Return a list of currently bound events."""
pydicom/pynetdicom
ff79e00f054d7d40bd6493cd5735f1087ce52fbb
diff --git a/pynetdicom/tests/test_pdu_items.py b/pynetdicom/tests/test_pdu_items.py index a2de773e0..1c84825a7 100644 --- a/pynetdicom/tests/test_pdu_items.py +++ b/pynetdicom/tests/test_pdu_items.py @@ -178,9 +178,9 @@ class TestPDU(object): item.item_length def test_item_type_raises(self): - """Test PDU.pdu_type raises ValueError.""" + """Test PDUItem.item_type raises ValueError.""" item = PDUItem() - with pytest.raises(ValueError): + with pytest.raises(KeyError): item.item_type def test_wrap_bytes(self): diff --git a/pynetdicom/tests/test_transport.py b/pynetdicom/tests/test_transport.py index 2650093de..7752eb5ac 100644 --- a/pynetdicom/tests/test_transport.py +++ b/pynetdicom/tests/test_transport.py @@ -169,9 +169,16 @@ def client_context(request): class TestTLS(object): """Test using TLS to wrap the association.""" + def setup(self): + self.ae = None + + def teardown(self): + if self.ae: + self.ae.shutdown() + def test_tls_not_server_not_client(self): """Test associating with no TLS on either end.""" - ae = AE() + self.ae = ae = AE() ae.add_supported_context('1.2.840.10008.1.1') server = ae.start_server(('', 11112), block=False) @@ -183,10 +190,16 @@ class TestTLS(object): server.shutdown() + assert len(server.active_associations) == 0 + def test_tls_not_server_yes_client(self, client_context): """Test wrapping the requestor socket with TLS (but not server).""" - ae = AE() + self.ae = ae = AE() + ae.acse_timeout = 0.5 + ae.dimse_timeout = 0.5 + ae.network_timeout = 0.5 ae.add_supported_context('1.2.840.10008.1.1') + server = ae.start_server(('', 11112), block=False) ae.add_requested_context('1.2.840.10008.1.1') @@ -195,9 +208,13 @@ class TestTLS(object): server.shutdown() + time.sleep(0.5) + + assert len(server.active_associations) == 0 + def test_tls_yes_server_not_client(self, server_context): """Test wrapping the requestor socket with TLS (and server).""" - ae = AE() + self.ae = ae = AE() ae.add_supported_context('1.2.840.10008.1.1') server = ae.start_server( ('', 11112), @@ -211,9 +228,11 @@ class TestTLS(object): server.shutdown() + assert len(server.active_associations) == 0 + def test_tls_yes_server_yes_client(self, server_context, client_context): """Test associating with no TLS on either end.""" - ae = AE() + self.ae = ae = AE() ae.add_supported_context('1.2.840.10008.1.1') server = ae.start_server( ('', 11112), @@ -229,6 +248,8 @@ class TestTLS(object): server.shutdown() + assert len(server.active_associations) == 0 + class TestAssociationServer(object): def setup(self):
Association related memory leak ### Description There seems to be an association-related memory-leak somewhere. ### Expected behaviour The memory usage when acting as an SCP should remain constant over time. ### Actual behaviour Memory usage increases with the total number of associations. Storage SCP starts around 27.3 MB and increases by about 30 MB per 1000 associations. * Looks like `AssociationServer._children` isn't being cleaned up (when commented out memory usage starts at 20.8 and stabilises around 28.8) ### Steps to reproduce Start a storage SCP and associate with it a few thousand times
0.0
ff79e00f054d7d40bd6493cd5735f1087ce52fbb
[ "pynetdicom/tests/test_pdu_items.py::TestPDU::test_item_type_raises" ]
[ "pynetdicom/tests/test_pdu_items.py::TestPDU::test_decode_raises", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_decoders_raises", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_equality", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_encode_raises", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_encoders_raises", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_generate_items", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_generate_items_raises", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_hash_raises", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_inequality", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_item_length_raises", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_wrap_bytes", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_wrap_encode_items", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_wrap_generate_items", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_wrap_pack", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_wrap_uid_bytes", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_wrap_unpack", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_wrap_encode_uid", "pynetdicom/tests/test_pdu_items.py::TestApplicationContext::test_init", "pynetdicom/tests/test_pdu_items.py::TestApplicationContext::test_uid_conformance", "pynetdicom/tests/test_pdu_items.py::TestApplicationContext::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestApplicationContext::test_rq_decode", "pynetdicom/tests/test_pdu_items.py::TestApplicationContext::test_ac_decode", "pynetdicom/tests/test_pdu_items.py::TestApplicationContext::test_encode_cycle", "pynetdicom/tests/test_pdu_items.py::TestApplicationContext::test_update", "pynetdicom/tests/test_pdu_items.py::TestApplicationContext::test_properties", "pynetdicom/tests/test_pdu_items.py::TestApplicationContext::test_encode_odd", "pynetdicom/tests/test_pdu_items.py::TestApplicationContext::test_encode_even", "pynetdicom/tests/test_pdu_items.py::TestApplicationContext::test_decode_odd", "pynetdicom/tests/test_pdu_items.py::TestApplicationContext::test_decode_even", "pynetdicom/tests/test_pdu_items.py::TestApplicationContext::test_decode_padded_odd", "pynetdicom/tests/test_pdu_items.py::TestPresentationContextRQ::test_init", "pynetdicom/tests/test_pdu_items.py::TestPresentationContextRQ::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestPresentationContextRQ::test_decode", "pynetdicom/tests/test_pdu_items.py::TestPresentationContextRQ::test_encode", "pynetdicom/tests/test_pdu_items.py::TestPresentationContextRQ::test_to_primitive", "pynetdicom/tests/test_pdu_items.py::TestPresentationContextRQ::test_from_primitive", "pynetdicom/tests/test_pdu_items.py::TestPresentationContextAC::test_init", "pynetdicom/tests/test_pdu_items.py::TestPresentationContextAC::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestPresentationContextAC::test_decode", "pynetdicom/tests/test_pdu_items.py::TestPresentationContextAC::test_encode", "pynetdicom/tests/test_pdu_items.py::TestPresentationContextAC::test_to_primitive", "pynetdicom/tests/test_pdu_items.py::TestPresentationContextAC::test_from_primitive", "pynetdicom/tests/test_pdu_items.py::TestPresentationContextAC::test_result_str", "pynetdicom/tests/test_pdu_items.py::TestAbstractSyntax::test_init", "pynetdicom/tests/test_pdu_items.py::TestAbstractSyntax::test_uid_conformance", "pynetdicom/tests/test_pdu_items.py::TestAbstractSyntax::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestAbstractSyntax::test_decode", "pynetdicom/tests/test_pdu_items.py::TestAbstractSyntax::test_encode_cycle", "pynetdicom/tests/test_pdu_items.py::TestAbstractSyntax::test_properies", "pynetdicom/tests/test_pdu_items.py::TestAbstractSyntax::test_encode_odd", "pynetdicom/tests/test_pdu_items.py::TestAbstractSyntax::test_encode_even", "pynetdicom/tests/test_pdu_items.py::TestAbstractSyntax::test_decode_odd", "pynetdicom/tests/test_pdu_items.py::TestAbstractSyntax::test_decode_even", "pynetdicom/tests/test_pdu_items.py::TestAbstractSyntax::test_decode_padded_odd", "pynetdicom/tests/test_pdu_items.py::TestTransferSyntax::test_init", "pynetdicom/tests/test_pdu_items.py::TestTransferSyntax::test_uid_conformance", "pynetdicom/tests/test_pdu_items.py::TestTransferSyntax::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestTransferSyntax::test_decode", "pynetdicom/tests/test_pdu_items.py::TestTransferSyntax::test_encode_cycle", "pynetdicom/tests/test_pdu_items.py::TestTransferSyntax::test_properies", "pynetdicom/tests/test_pdu_items.py::TestTransferSyntax::test_encode_odd", "pynetdicom/tests/test_pdu_items.py::TestTransferSyntax::test_encode_even", "pynetdicom/tests/test_pdu_items.py::TestTransferSyntax::test_decode_odd", "pynetdicom/tests/test_pdu_items.py::TestTransferSyntax::test_decode_even", "pynetdicom/tests/test_pdu_items.py::TestTransferSyntax::test_decode_padded_odd", "pynetdicom/tests/test_pdu_items.py::TestPresentationDataValue::test_init", "pynetdicom/tests/test_pdu_items.py::TestPresentationDataValue::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestPresentationDataValue::test_decode", "pynetdicom/tests/test_pdu_items.py::TestPresentationDataValue::test_encode", "pynetdicom/tests/test_pdu_items.py::TestPresentationDataValue::test_properies", "pynetdicom/tests/test_pdu_items.py::TestPresentationDataValue::test_message_control_header_byte", "pynetdicom/tests/test_pdu_items.py::TestUserInformation::test_init", "pynetdicom/tests/test_pdu_items.py::TestUserInformation::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestUserInformation::test_decode", "pynetdicom/tests/test_pdu_items.py::TestUserInformation::test_encode", "pynetdicom/tests/test_pdu_items.py::TestUserInformation::test_to_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserInformation::test_from_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserInformation::test_properties_usr_id", "pynetdicom/tests/test_pdu_items.py::TestUserInformation::test_properties_ext_neg", "pynetdicom/tests/test_pdu_items.py::TestUserInformation::test_properties_role", "pynetdicom/tests/test_pdu_items.py::TestUserInformation::test_properties_async", "pynetdicom/tests/test_pdu_items.py::TestUserInformation::test_properties_max_pdu", "pynetdicom/tests/test_pdu_items.py::TestUserInformation::test_properties_implementation", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_MaximumLength::test_init", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_MaximumLength::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_MaximumLength::test_decode", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_MaximumLength::test_encode", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_MaximumLength::test_to_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_MaximumLength::test_from_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationUID::test_uid_conformance", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationUID::test_init", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationUID::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationUID::test_decode", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationUID::test_encode", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationUID::test_to_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationUID::test_from_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationUID::test_properies", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationUID::test_encode_odd", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationUID::test_encode_even", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationUID::test_decode_odd", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationUID::test_decode_even", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationUID::test_decode_padded_odd", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationUID::test_no_log_padded", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationVersion::test_init", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationVersion::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationVersion::test_decode", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationVersion::test_encode", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationVersion::test_to_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationVersion::test_from_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationVersion::test_properies", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_Asynchronous::test_init", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_Asynchronous::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_Asynchronous::test_decode", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_Asynchronous::test_encode", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_Asynchronous::test_to_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_Asynchronous::test_from_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_Asynchronous::test_properies", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_RoleSelection::test_uid_conformance", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_RoleSelection::test_init", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_RoleSelection::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_RoleSelection::test_decode", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_RoleSelection::test_encode", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_RoleSelection::test_to_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_RoleSelection::test_from_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_RoleSelection::test_from_primitive_no_scu", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_RoleSelection::test_properties", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_RoleSelection::test_encode_odd", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_RoleSelection::test_encode_even", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_RoleSelection::test_decode_odd", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_RoleSelection::test_decode_even", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_RoleSelection::test_decode_padded_odd", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityRQ_UserNoPass::test_init", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityRQ_UserNoPass::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityRQ_UserNoPass::test_decode", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityRQ_UserNoPass::test_encode", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityRQ_UserNoPass::test_to_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityRQ_UserNoPass::test_from_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityRQ_UserNoPass::test_properies", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityRQ_UserPass::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityRQ_UserPass::test_decode", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityRQ_UserPass::test_encode", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityRQ_UserPass::test_to_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityRQ_UserPass::test_from_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityRQ_UserPass::test_properties", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityAC_UserResponse::test_init", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityAC_UserResponse::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityAC_UserResponse::test_decode", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityAC_UserResponse::test_encode", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityAC_UserResponse::test_to_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityAC_UserResponse::test_from_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityAC_UserResponse::test_properies", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ExtendedNegotiation::test_uid_conformance", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ExtendedNegotiation::test_init", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ExtendedNegotiation::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ExtendedNegotiation::test_decode", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ExtendedNegotiation::test_encode", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ExtendedNegotiation::test_to_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ExtendedNegotiation::test_from_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ExtendedNegotiation::test_properties", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ExtendedNegotiation::test_encode_odd", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ExtendedNegotiation::test_encode_even", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ExtendedNegotiation::test_decode_odd", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ExtendedNegotiation::test_decode_even", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ExtendedNegotiation::test_decode_padded_odd", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_CommonExtendedNegotiation::test_uid_conformance", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_CommonExtendedNegotiation::test_init", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_CommonExtendedNegotiation::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_CommonExtendedNegotiation::test_decode", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_CommonExtendedNegotiation::test_encode", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_CommonExtendedNegotiation::test_to_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_CommonExtendedNegotiation::test_from_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_CommonExtendedNegotiation::test_properties", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_CommonExtendedNegotiation::test_generate_items", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_CommonExtendedNegotiation::test_generate_items_raises", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_CommonExtendedNegotiation::test_wrap_generate_items", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_CommonExtendedNegotiation::test_wrap_list", "pynetdicom/tests/test_transport.py::TestTLS::test_tls_not_server_not_client", "pynetdicom/tests/test_transport.py::TestTLS::test_tls_not_server_yes_client", "pynetdicom/tests/test_transport.py::TestTLS::test_tls_yes_server_not_client" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-04-09 00:52:41+00:00
mit
4,929
pydicom__pynetdicom-343
diff --git a/docs/changelog/v1.4.0.rst b/docs/changelog/v1.4.0.rst index e3a4fa84b..4be63b2f8 100644 --- a/docs/changelog/v1.4.0.rst +++ b/docs/changelog/v1.4.0.rst @@ -9,6 +9,8 @@ Fixes * Fixed Query Retrieve service class not responded with ``0x0000`` (Success) if no matches were yielded by the C-FIND request handler. +* Fixed association being aborted due to failure to decode a rejected + presentation context when the transfer syntax value is empty (:issue:`342`) Enhancements diff --git a/pynetdicom/pdu_items.py b/pynetdicom/pdu_items.py index 4570836a8..73cffcd47 100644 --- a/pynetdicom/pdu_items.py +++ b/pynetdicom/pdu_items.py @@ -961,8 +961,9 @@ class PresentationContextItemAC(PDUItem): s += " Context ID: {0:d}\n".format(self.presentation_context_id) s += " Result/Reason: {0!s}\n".format(self.result_str) - item_str = '{0!s}'.format(self.transfer_syntax.name) - s += ' + {0!s}\n'.format(item_str) + if self.transfer_syntax: + item_str = '{0!s}'.format(self.transfer_syntax.name) + s += ' + {0!s}\n'.format(item_str) return s @@ -979,6 +980,20 @@ class PresentationContextItemAC(PDUItem): return None + def _wrap_generate_items(self, bytestream): + """Return a list of decoded PDU items generated from `bytestream`.""" + item_list = [] + for item_type, item_bytes in self._generate_items(bytestream): + item = PDU_ITEM_TYPES[item_type]() + # Transfer Syntax items shall not have their value tested if + # not accepted + if item_type == 0x40 and self.result != 0x00: + item._skip_validation = True + item.decode(item_bytes) + item_list.append(item) + + return item_list + class UserInformationItem(PDUItem): """A User Information Item. @@ -1492,6 +1507,8 @@ class TransferSyntaxSubItem(PDUItem): def __init__(self): """Initialise a new Abstract Syntax Item.""" + # Should not be validated if Presentation Context was rejected + self._skip_validation = False self.transfer_syntax_name = None @property @@ -1547,8 +1564,10 @@ class TransferSyntaxSubItem(PDUItem): s = "Transfer syntax sub item\n" s += " Item type: 0x{0:02x}\n".format(self.item_type) s += " Item length: {0:d} bytes\n".format(self.item_length) - s += ' Transfer syntax name: ={0!s}\n'.format( - self.transfer_syntax_name.name) + if self.transfer_syntax_name: + s += ' Transfer syntax name: ={0!s}\n'.format( + self.transfer_syntax_name.name + ) return s @@ -1584,6 +1603,10 @@ class TransferSyntaxSubItem(PDUItem): raise TypeError('Transfer syntax must be a pydicom.uid.UID, ' 'bytes or str') + if self._skip_validation: + self._transfer_syntax_name = value or None + return + if value is not None and not validate_uid(value): LOGGER.error("Transfer Syntax Name is an invalid UID") raise ValueError("Transfer Syntax Name is an invalid UID")
pydicom/pynetdicom
12555184529a10ac76064e84be0922fbad0b6d4b
diff --git a/pynetdicom/tests/encoded_pdu_items.py b/pynetdicom/tests/encoded_pdu_items.py index 05c20deaf..0d9148291 100644 --- a/pynetdicom/tests/encoded_pdu_items.py +++ b/pynetdicom/tests/encoded_pdu_items.py @@ -282,6 +282,46 @@ a_associate_ac_user = b'\x02\x00\x00\x00\x00\xb8\x00\x01\x00\x00' \ b'\x59\x00\x00\x0a\x00\x08\x41\x63\x63\x65' \ b'\x70\x74\x65\x64' + +# Issue 342 +# Called AET: ANY-SCP +# Calling AET: PYNETDICOM +# Application Context Name: 1.2.840.10008.3.1.1.1 +# Presentation Context Items: +# Presentation Context ID: 1 +# Abstract Syntax: Verification SOP Class +# SCP/SCU Role: Default +# Result: Accepted +# Transfer Syntax: 1.2.840.10008.1.2.1 Explicit VR Little Endian +# Presentation Context ID: 3 +# Abstract Syntax: Basic Grayscale Print Management Meta SOP Class +# SCP/SCU Role: Default +# Result: Abstract Syntax Not Supported +# Transfer Syntax: None +# User Information +# Max Length Received: 28672 +# Implementation Class UID: 2.16.840.1 +# Implementation Version Name: MergeCOM3_390IB2 +# Extended Negotiation +# SOP Extended: None +# Async Ops: None +# User ID: None +a_associate_ac_zero_ts = ( + b'\x02\x00\x00\x00\x00\xb6\x00\x01\x00\x00\x41\x4e\x59\x2d\x53\x43' + b'\x50\x20\x20\x20\x20\x20\x20\x20\x20\x20\x50\x59\x4e\x45\x54\x44' + b'\x49\x43\x4f\x4d\x20\x20\x20\x20\x20\x20\x00\x00\x00\x00\x00\x00' + b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' + b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x10\x00\x00\x15\x31\x2e' + b'\x32\x2e\x38\x34\x30\x2e\x31\x30\x30\x30\x38\x2e\x33\x2e\x31\x2e' + b'\x31\x2e\x31\x21\x00\x00\x1b\x01\x00\x00\x00\x40\x00\x00\x13\x31' + b'\x2e\x32\x2e\x38\x34\x30\x2e\x31\x30\x30\x30\x38\x2e\x31\x2e\x32' + b'\x2e\x31\x21\x00\x00\x08\x03\x00\x03\x00\x40\x00\x00\x00\x50\x00' + b'\x00\x2a\x51\x00\x00\x04\x00\x00\x70\x00\x52\x00\x00\x0a\x32\x2e' + b'\x31\x36\x2e\x38\x34\x30\x2e\x31\x55\x00\x00\x10\x4d\x65\x72\x67' + b'\x65\x43\x4f\x4d\x33\x5f\x33\x39\x30\x49\x42\x32' +) + + ############################# A-ASSOCIATE-RJ PDU ############################### # Result: Rejected (Permanent) # Source: DUL service-user diff --git a/pynetdicom/tests/test_pdu_items.py b/pynetdicom/tests/test_pdu_items.py index 1c84825a7..48cdb77ef 100644 --- a/pynetdicom/tests/test_pdu_items.py +++ b/pynetdicom/tests/test_pdu_items.py @@ -45,7 +45,7 @@ from .encoded_pdu_items import ( maximum_length_received, implementation_class_uid, implementation_version_name, role_selection, role_selection_odd, user_information, extended_negotiation, common_extended_negotiation, - p_data_tf + p_data_tf, a_associate_ac_zero_ts ) LOGGER = logging.getLogger('pynetdicom') @@ -612,6 +612,28 @@ class TestPresentationContextAC(object): item.result_reason = result assert item.result_str == _result[result] + def test_decode_empty(self): + """Regression test for #342 (decoding an empty Transfer Syntax Item.""" + # When result is not accepted, transfer syntax value must not be tested + item = PresentationContextItemAC() + item.decode( + b'\x21\x00\x00\x08\x01\x00\x01\x00' + b'\x40\x00\x00\x00' + ) + + assert item.item_type == 0x21 + assert item.item_length == 8 + assert item.result == 1 + assert len(item) == 12 + assert item.transfer_syntax is None + + assert "Item length: 8 bytes" in item.__str__() + + item = item.transfer_syntax_sub_item[0] + assert item.item_length == 0 + assert item._skip_validation is True + assert item.transfer_syntax_name is None + class TestAbstractSyntax(object): def setup(self): @@ -880,6 +902,35 @@ class TestTransferSyntax(object): assert len(item) == 9 assert item.encode() == b'\x40\x00\x00\x05\x31\x2e\x32\x2e\x33' + def test_decode_empty(self): + """Regression test for #342 (decoding an empty Transfer Syntax Item.""" + pdu = A_ASSOCIATE_AC() + pdu.decode(a_associate_ac_zero_ts) + + item = pdu.presentation_context[0] + assert item.item_type == 0x21 + assert item.item_length == 27 + assert item.result == 0 + assert len(item) == 31 + assert item.transfer_syntax == UID('1.2.840.10008.1.2.1') + + item = pdu.presentation_context[1] + assert item.item_type == 0x21 + assert item.item_length == 8 + assert item.result == 3 + assert len(item) == 12 + assert item.transfer_syntax is None + + item = TransferSyntaxSubItem() + item._skip_validation = True + item.decode(b'\x40\x00\x00\x00') + assert item.item_type == 0x40 + assert item.item_length == 0 + assert len(item) == 4 + assert item.transfer_syntax is None + assert 'Item length: 0 bytes' in item.__str__() + assert 'Transfer syntax name' not in item.__str__() + class TestPresentationDataValue(object): def test_init(self):
Failure to decode A-ASSOCIATE-AC when transfer syntax length is zero ### Description When an A-ASSOCIATE-AC response is received that includes a rejected context containing a transfer syntax item of zero length then decoding the PDU fails and the association is aborted. ### Expected behaviour The PDU should decode successfully. ### Actual behaviour Decode fails, association is aborted
0.0
12555184529a10ac76064e84be0922fbad0b6d4b
[ "pynetdicom/tests/test_pdu_items.py::TestPresentationContextAC::test_decode_empty", "pynetdicom/tests/test_pdu_items.py::TestTransferSyntax::test_decode_empty" ]
[ "pynetdicom/tests/test_pdu_items.py::TestPDU::test_decode_raises", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_decoders_raises", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_equality", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_encode_raises", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_encoders_raises", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_generate_items", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_generate_items_raises", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_hash_raises", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_inequality", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_item_length_raises", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_item_type_raises", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_wrap_bytes", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_wrap_encode_items", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_wrap_generate_items", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_wrap_pack", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_wrap_uid_bytes", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_wrap_unpack", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_wrap_encode_uid", "pynetdicom/tests/test_pdu_items.py::TestApplicationContext::test_init", "pynetdicom/tests/test_pdu_items.py::TestApplicationContext::test_uid_conformance", "pynetdicom/tests/test_pdu_items.py::TestApplicationContext::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestApplicationContext::test_rq_decode", "pynetdicom/tests/test_pdu_items.py::TestApplicationContext::test_ac_decode", "pynetdicom/tests/test_pdu_items.py::TestApplicationContext::test_encode_cycle", "pynetdicom/tests/test_pdu_items.py::TestApplicationContext::test_update", "pynetdicom/tests/test_pdu_items.py::TestApplicationContext::test_properties", "pynetdicom/tests/test_pdu_items.py::TestApplicationContext::test_encode_odd", "pynetdicom/tests/test_pdu_items.py::TestApplicationContext::test_encode_even", "pynetdicom/tests/test_pdu_items.py::TestApplicationContext::test_decode_odd", "pynetdicom/tests/test_pdu_items.py::TestApplicationContext::test_decode_even", "pynetdicom/tests/test_pdu_items.py::TestApplicationContext::test_decode_padded_odd", "pynetdicom/tests/test_pdu_items.py::TestPresentationContextRQ::test_init", "pynetdicom/tests/test_pdu_items.py::TestPresentationContextRQ::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestPresentationContextRQ::test_decode", "pynetdicom/tests/test_pdu_items.py::TestPresentationContextRQ::test_encode", "pynetdicom/tests/test_pdu_items.py::TestPresentationContextRQ::test_to_primitive", "pynetdicom/tests/test_pdu_items.py::TestPresentationContextRQ::test_from_primitive", "pynetdicom/tests/test_pdu_items.py::TestPresentationContextAC::test_init", "pynetdicom/tests/test_pdu_items.py::TestPresentationContextAC::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestPresentationContextAC::test_decode", "pynetdicom/tests/test_pdu_items.py::TestPresentationContextAC::test_encode", "pynetdicom/tests/test_pdu_items.py::TestPresentationContextAC::test_to_primitive", "pynetdicom/tests/test_pdu_items.py::TestPresentationContextAC::test_from_primitive", "pynetdicom/tests/test_pdu_items.py::TestPresentationContextAC::test_result_str", "pynetdicom/tests/test_pdu_items.py::TestAbstractSyntax::test_init", "pynetdicom/tests/test_pdu_items.py::TestAbstractSyntax::test_uid_conformance", "pynetdicom/tests/test_pdu_items.py::TestAbstractSyntax::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestAbstractSyntax::test_decode", "pynetdicom/tests/test_pdu_items.py::TestAbstractSyntax::test_encode_cycle", "pynetdicom/tests/test_pdu_items.py::TestAbstractSyntax::test_properies", "pynetdicom/tests/test_pdu_items.py::TestAbstractSyntax::test_encode_odd", "pynetdicom/tests/test_pdu_items.py::TestAbstractSyntax::test_encode_even", "pynetdicom/tests/test_pdu_items.py::TestAbstractSyntax::test_decode_odd", "pynetdicom/tests/test_pdu_items.py::TestAbstractSyntax::test_decode_even", "pynetdicom/tests/test_pdu_items.py::TestAbstractSyntax::test_decode_padded_odd", "pynetdicom/tests/test_pdu_items.py::TestTransferSyntax::test_init", "pynetdicom/tests/test_pdu_items.py::TestTransferSyntax::test_uid_conformance", "pynetdicom/tests/test_pdu_items.py::TestTransferSyntax::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestTransferSyntax::test_decode", "pynetdicom/tests/test_pdu_items.py::TestTransferSyntax::test_encode_cycle", "pynetdicom/tests/test_pdu_items.py::TestTransferSyntax::test_properies", "pynetdicom/tests/test_pdu_items.py::TestTransferSyntax::test_encode_odd", "pynetdicom/tests/test_pdu_items.py::TestTransferSyntax::test_encode_even", "pynetdicom/tests/test_pdu_items.py::TestTransferSyntax::test_decode_odd", "pynetdicom/tests/test_pdu_items.py::TestTransferSyntax::test_decode_even", "pynetdicom/tests/test_pdu_items.py::TestTransferSyntax::test_decode_padded_odd", "pynetdicom/tests/test_pdu_items.py::TestPresentationDataValue::test_init", "pynetdicom/tests/test_pdu_items.py::TestPresentationDataValue::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestPresentationDataValue::test_decode", "pynetdicom/tests/test_pdu_items.py::TestPresentationDataValue::test_encode", "pynetdicom/tests/test_pdu_items.py::TestPresentationDataValue::test_properies", "pynetdicom/tests/test_pdu_items.py::TestPresentationDataValue::test_message_control_header_byte", "pynetdicom/tests/test_pdu_items.py::TestUserInformation::test_init", "pynetdicom/tests/test_pdu_items.py::TestUserInformation::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestUserInformation::test_decode", "pynetdicom/tests/test_pdu_items.py::TestUserInformation::test_encode", "pynetdicom/tests/test_pdu_items.py::TestUserInformation::test_to_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserInformation::test_from_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserInformation::test_properties_usr_id", "pynetdicom/tests/test_pdu_items.py::TestUserInformation::test_properties_ext_neg", "pynetdicom/tests/test_pdu_items.py::TestUserInformation::test_properties_role", "pynetdicom/tests/test_pdu_items.py::TestUserInformation::test_properties_async", "pynetdicom/tests/test_pdu_items.py::TestUserInformation::test_properties_max_pdu", "pynetdicom/tests/test_pdu_items.py::TestUserInformation::test_properties_implementation", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_MaximumLength::test_init", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_MaximumLength::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_MaximumLength::test_decode", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_MaximumLength::test_encode", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_MaximumLength::test_to_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_MaximumLength::test_from_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationUID::test_uid_conformance", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationUID::test_init", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationUID::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationUID::test_decode", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationUID::test_encode", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationUID::test_to_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationUID::test_from_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationUID::test_properies", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationUID::test_encode_odd", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationUID::test_encode_even", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationUID::test_decode_odd", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationUID::test_decode_even", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationUID::test_decode_padded_odd", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationUID::test_no_log_padded", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationVersion::test_init", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationVersion::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationVersion::test_decode", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationVersion::test_encode", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationVersion::test_to_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationVersion::test_from_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationVersion::test_properies", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_Asynchronous::test_init", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_Asynchronous::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_Asynchronous::test_decode", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_Asynchronous::test_encode", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_Asynchronous::test_to_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_Asynchronous::test_from_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_Asynchronous::test_properies", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_RoleSelection::test_uid_conformance", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_RoleSelection::test_init", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_RoleSelection::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_RoleSelection::test_decode", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_RoleSelection::test_encode", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_RoleSelection::test_to_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_RoleSelection::test_from_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_RoleSelection::test_from_primitive_no_scu", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_RoleSelection::test_properties", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_RoleSelection::test_encode_odd", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_RoleSelection::test_encode_even", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_RoleSelection::test_decode_odd", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_RoleSelection::test_decode_even", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_RoleSelection::test_decode_padded_odd", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityRQ_UserNoPass::test_init", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityRQ_UserNoPass::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityRQ_UserNoPass::test_decode", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityRQ_UserNoPass::test_encode", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityRQ_UserNoPass::test_to_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityRQ_UserNoPass::test_from_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityRQ_UserNoPass::test_properies", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityRQ_UserPass::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityRQ_UserPass::test_decode", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityRQ_UserPass::test_encode", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityRQ_UserPass::test_to_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityRQ_UserPass::test_from_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityRQ_UserPass::test_properties", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityAC_UserResponse::test_init", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityAC_UserResponse::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityAC_UserResponse::test_decode", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityAC_UserResponse::test_encode", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityAC_UserResponse::test_to_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityAC_UserResponse::test_from_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityAC_UserResponse::test_properies", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ExtendedNegotiation::test_uid_conformance", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ExtendedNegotiation::test_init", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ExtendedNegotiation::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ExtendedNegotiation::test_decode", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ExtendedNegotiation::test_encode", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ExtendedNegotiation::test_to_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ExtendedNegotiation::test_from_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ExtendedNegotiation::test_properties", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ExtendedNegotiation::test_encode_odd", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ExtendedNegotiation::test_encode_even", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ExtendedNegotiation::test_decode_odd", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ExtendedNegotiation::test_decode_even", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ExtendedNegotiation::test_decode_padded_odd", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_CommonExtendedNegotiation::test_uid_conformance", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_CommonExtendedNegotiation::test_init", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_CommonExtendedNegotiation::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_CommonExtendedNegotiation::test_decode", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_CommonExtendedNegotiation::test_encode", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_CommonExtendedNegotiation::test_to_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_CommonExtendedNegotiation::test_from_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_CommonExtendedNegotiation::test_properties", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_CommonExtendedNegotiation::test_generate_items", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_CommonExtendedNegotiation::test_generate_items_raises", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_CommonExtendedNegotiation::test_wrap_generate_items", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_CommonExtendedNegotiation::test_wrap_list" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-04-22 06:45:44+00:00
mit
4,930
pydicom__pynetdicom-362
diff --git a/docs/_static/css/pynetdicom.css b/docs/_static/css/pynetdicom.css index 14216e0d3..39132a277 100644 --- a/docs/_static/css/pynetdicom.css +++ b/docs/_static/css/pynetdicom.css @@ -83,3 +83,7 @@ code.xref { color: #2980B9 !important; font-size: 80%; } + +p.first { + margin-bottom: 0px !important; +} diff --git a/docs/changelog/v1.0.0.rst b/docs/changelog/v1.0.0.rst index a19f88431..a50d617fb 100644 --- a/docs/changelog/v1.0.0.rst +++ b/docs/changelog/v1.0.0.rst @@ -33,7 +33,6 @@ Changes - Added ``AE.add_requested_context()``, ``AE.requested_contexts``, ``AE.remove_requested_context()`` for adding and removing the presentation contexts requested as an SCU. - * Removed ``VerificationSOPClass``, ``StorageSOPClassList`` and ``QueryRetrieveSOPClassList``. * Added ``VerificationPresentationContexts``, ``StoragePresentationContexts``, diff --git a/docs/changelog/v1.4.0.rst b/docs/changelog/v1.4.0.rst index 750f64bcb..76b6eb864 100644 --- a/docs/changelog/v1.4.0.rst +++ b/docs/changelog/v1.4.0.rst @@ -19,8 +19,6 @@ Fixes Enhancements ............ -* Added support for Protocol Approval Query Retrieve service class - (:issue:`327`) * Added ``Event.move_destination`` and ``Event.event`` properties (:issue:`353`) * Added ``meta_uid`` keyword parameters to the ``Association.send_n_*()`` @@ -28,6 +26,20 @@ Enhancements Print Management service class) * Added *Basic Grayscale Print Management Meta SOP Class* and *Basic Color Print Management Meta SOP Class* to ``sop_class``. +* Added full support for the following service classes: + + * Protocol Approval Query Retrieve (:issue:`327`) + * Application Event Logging + * Instance Availability Notification + * Media Creation Management +* Added partial support for the following service classes: + + * Print Management + * Unified Procedure Step + * RT Machine Verification + * Storage Commitment +* Added handling of non-conformant Presentation Context AC (reject) PDUs which + contain no Transfer Syntax Sub-item (:issue:`361`) Changes diff --git a/docs/conf.py b/docs/conf.py index 734f1b465..f30abcd56 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -65,7 +65,7 @@ extensions = [ 'sphinx.ext.todo', 'sphinx.ext.imgmath', 'sphinx.ext.ifconfig', - 'sphinx.ext.viewcode', + #'sphinx.ext.viewcode', #'sphinx_gallery.gen_gallery', 'sphinx.ext.autosummary', 'sphinx.ext.napoleon', @@ -228,7 +228,7 @@ html_static_path = ['_static'] # html_split_index = False # If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True +html_show_sourcelink = False # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the diff --git a/pynetdicom/pdu_items.py b/pynetdicom/pdu_items.py index 698e24b6c..05ba527ec 100644 --- a/pynetdicom/pdu_items.py +++ b/pynetdicom/pdu_items.py @@ -856,11 +856,8 @@ class PresentationContextItemAC(PDUItem): primitive = PresentationContext() primitive.context_id = self.presentation_context_id primitive.result = self.result_reason - # May be `None` if context is rejected - if self.transfer_syntax_sub_item[0].transfer_syntax_name: - primitive.add_transfer_syntax( - self.transfer_syntax_sub_item[0].transfer_syntax_name - ) + if self.transfer_syntax: + primitive.add_transfer_syntax(self.transfer_syntax) return primitive @@ -976,6 +973,9 @@ class PresentationContextItemAC(PDUItem): Returns ------- pydicom.uid.UID or None + If no Transfer Syntax Sub-item or an empty Transfer Syntax Sub-item + has been sent by the Acceptor then returns None, otherwise returns + the Transfer Syntax Sub-item's transfer syntax UID. """ if self.transfer_syntax_sub_item: return self.transfer_syntax_sub_item[0].transfer_syntax_name diff --git a/pynetdicom/presentation.py b/pynetdicom/presentation.py index 8b31ca3fe..575ef121c 100644 --- a/pynetdicom/presentation.py +++ b/pynetdicom/presentation.py @@ -283,7 +283,9 @@ class PresentationContext(object): elif isinstance(syntax, bytes): syntax = UID(syntax.decode('ascii')) else: - LOGGER.error("Attempted to add an invalid transfer syntax") + if syntax is not None: + LOGGER.error("Attempted to add an invalid transfer syntax") + return if syntax is not None and not validate_uid(syntax):
pydicom/pynetdicom
853b2cfe3b14cf5e8a7b554334a4c6c4d65febfb
diff --git a/pynetdicom/tests/encoded_pdu_items.py b/pynetdicom/tests/encoded_pdu_items.py index 0d9148291..d509c4070 100644 --- a/pynetdicom/tests/encoded_pdu_items.py +++ b/pynetdicom/tests/encoded_pdu_items.py @@ -282,7 +282,6 @@ a_associate_ac_user = b'\x02\x00\x00\x00\x00\xb8\x00\x01\x00\x00' \ b'\x59\x00\x00\x0a\x00\x08\x41\x63\x63\x65' \ b'\x70\x74\x65\x64' - # Issue 342 # Called AET: ANY-SCP # Calling AET: PYNETDICOM @@ -321,6 +320,39 @@ a_associate_ac_zero_ts = ( b'\x65\x43\x4f\x4d\x33\x5f\x33\x39\x30\x49\x42\x32' ) +# Issue 361 +# Called AET: ANY-SCP +# Calling AET: PYNETDICOM +# Application Context Name: 1.2.840.10008.3.1.1.1 +# Presentation Context Items: +# Presentation Context ID: 1 +# Abstract Syntax: Verification SOP Class +# SCP/SCU Role: Default +# Result: Reject +# Transfer Syntax: (no Transfer Syntax Sub-Item) +# User Information +# Max Length Received: 16382 +# Implementation Class UID: 1.2.826.0.1.3680043.9.3811.1.4.0 +# Implementation Version Name: PYNETDICOM_140 +# Extended Negotiation +# SOP Extended: None +# Async Ops: None +# User ID: None +a_associate_ac_no_ts = ( + b'\x02\x00\x00\x00\x00\xa7\x00\x01\x00\x00\x41\x4e\x59\x2d\x53\x43' + b'\x50\x20\x20\x20\x20\x20\x20\x20\x20\x20\x50\x59\x4e\x45\x54\x44' + b'\x49\x43\x4f\x4d\x20\x20\x20\x20\x20\x20\x00\x00\x00\x00\x00\x00' + b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' + b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x10\x00\x00\x15\x31\x2e' + b'\x32\x2e\x38\x34\x30\x2e\x31\x30\x30\x30\x38\x2e\x33\x2e\x31\x2e' + b'\x31\x2e\x31\x21\x00\x00\x04\x01\x00\x03\x00' + b'\x50\x00\x00\x3e\x51\x00\x00\x04\x00\x00\x3f\xfe\x52\x00\x00\x20' + b'\x31\x2e\x32\x2e\x38\x32\x36\x2e\x30\x2e\x31\x2e\x33\x36\x38\x30' + b'\x30\x34\x33\x2e\x39\x2e\x33\x38\x31\x31\x2e\x31\x2e\x34\x2e\x30' + b'\x55\x00\x00\x0e\x50\x59\x4e\x45\x54\x44\x49\x43\x4f\x4d\x5f\x31' + b'\x34\x30' +) + ############################# A-ASSOCIATE-RJ PDU ############################### # Result: Rejected (Permanent) diff --git a/pynetdicom/tests/test_pdu.py b/pynetdicom/tests/test_pdu.py index d35a31669..1154923ff 100644 --- a/pynetdicom/tests/test_pdu.py +++ b/pynetdicom/tests/test_pdu.py @@ -37,7 +37,7 @@ from pynetdicom.pdu_primitives import ( from .encoded_pdu_items import ( a_associate_rq, a_associate_ac, a_associate_rj, a_release_rq, a_release_rq, a_release_rp, a_abort, a_p_abort, p_data_tf, - a_associate_rq_user_id_ext_neg + a_associate_rq_user_id_ext_neg, a_associate_ac_no_ts ) from pynetdicom.sop_class import VerificationSOPClass from pynetdicom.utils import pretty_bytes @@ -660,6 +660,24 @@ class TestASSOC_AC(object): assert new == orig + def test_no_transfer_syntax(self): + """Regression test for #361 - ASSOC-AC has no transfer syntax""" + pdu = A_ASSOCIATE_AC() + pdu.decode(a_associate_ac_no_ts) + + assert pdu.pdu_type == 0x02 + assert pdu.pdu_length == 167 + assert pdu.protocol_version == 0x0001 + assert isinstance(pdu.pdu_type, int) + assert isinstance(pdu.pdu_length, int) + assert isinstance(pdu.protocol_version, int) + + item = pdu.variable_items[1] + cx = item.to_primitive() + assert cx.transfer_syntax == [] + assert cx.result == 3 + assert cx.context_id == 1 + class TestASSOC_AC_ApplicationContext(object): def test_decode(self): diff --git a/pynetdicom/tests/test_pdu_items.py b/pynetdicom/tests/test_pdu_items.py index 48cdb77ef..a54c95283 100644 --- a/pynetdicom/tests/test_pdu_items.py +++ b/pynetdicom/tests/test_pdu_items.py @@ -627,6 +627,12 @@ class TestPresentationContextAC(object): assert len(item) == 12 assert item.transfer_syntax is None + # Confirm we can still convert the PDU into a PresentationContext + primitive = item.to_primitive() + assert primitive.context_id == 1 + assert primitive.transfer_syntax == [] + assert primitive.result == 1 + assert "Item length: 8 bytes" in item.__str__() item = item.transfer_syntax_sub_item[0]
Exception raised converting A-ASSOCIATE-AC PDU to A-ASSOCIATE primitive Hi, I know an issue similar to this has been discussed but it did not help. For test purposes, I want to make a C-MOVE request to ONIS Dicom Server to store ct and mammography images. I added my AE-Title, ip and port to ONIS so it recognizes me. I propose PatientRootQueryRetrieveInformationModelMove context and support CTImageStorage and DigitalMammographyXRayImagePresentationStorage within my AE. However I get the following debug logs that says PatientRootQueryRetrieveInformationModelMove is rejected. In its dicom conformance statement, it is written that ONIS supports PatientRootQueryRetrieveInformationModelMove. If I don't request PatientRootQueryRetrieveInformationModelMove but VerificationPresentationContexts, association establishes successfully but I can't make a C-MOVE obviously. Logs: > INFO:root:Server started. > INFO:pynetdicom.assoc:Requesting Association > DEBUG:pynetdicom.events:Request Parameters: > DEBUG:pynetdicom.events:========================= BEGIN A-ASSOCIATE-RQ PDU ========================= > DEBUG:pynetdicom.events:Our Implementation Class UID: 1.2.826.0.1.3680043.9.3811.1.3.1 > DEBUG:pynetdicom.events:Our Implementation Version Name: PYNETDICOM_131 > DEBUG:pynetdicom.events:Application Context Name: 1.2.840.10008.3.1.1.1 > DEBUG:pynetdicom.events:Calling Application Name: EGE-AI > DEBUG:pynetdicom.events:Called Application Name: ONIS25 > DEBUG:pynetdicom.events:Our Max PDU Receive Size: 16382 > DEBUG:pynetdicom.events:Presentation Context: > DEBUG:pynetdicom.events: Context ID: 1 (Proposed) > DEBUG:pynetdicom.events: Abstract Syntax: =Patient Root Query/Retrieve Information Model - MOVE > DEBUG:pynetdicom.events: Proposed SCP/SCU Role: Default > DEBUG:pynetdicom.events: Proposed Transfer Syntaxes: > DEBUG:pynetdicom.events: =Implicit VR Little Endian > DEBUG:pynetdicom.events: =Explicit VR Little Endian > DEBUG:pynetdicom.events: =Explicit VR Big Endian > DEBUG:pynetdicom.events:Requested Extended Negotiation: None > DEBUG:pynetdicom.events:Requested Common Extended Negotiation: None > DEBUG:pynetdicom.events:Requested Asynchronous Operations Window Negotiation: None > DEBUG:pynetdicom.events:Requested User Identity Negotiation: None > DEBUG:pynetdicom.events:========================== END A-ASSOCIATE-RQ PDU ========================== > DEBUG:pynetdicom.events:Accept Parameters: > DEBUG:pynetdicom.events:========================= BEGIN A-ASSOCIATE-AC PDU ========================= > DEBUG:pynetdicom.events:Their Implementation Class UID: 1.2.392.200193 > DEBUG:pynetdicom.events:Their Implementation Version Name: ONIS_Server 2.5 > DEBUG:pynetdicom.events:Application Context Name: 1.2.840.10008.3.1.1.1 > DEBUG:pynetdicom.events:Calling Application Name: EGE-AI > DEBUG:pynetdicom.events:Called Application Name: ONIS25 > DEBUG:pynetdicom.events:Their Max PDU Receive Size: 16382 > DEBUG:pynetdicom.events:Presentation Contexts: > DEBUG:pynetdicom.events: Context ID: 1 (Rejected - Abstract Syntax Not Supported) > DEBUG:pynetdicom.events: Abstract Syntax: =Patient Root Query/Retrieve Information Model - MOVE > DEBUG:pynetdicom.events:Accepted Extended Negotiation: None > DEBUG:pynetdicom.events:Accepted Asynchronous Operations Window Negotiation: None > DEBUG:pynetdicom.events:User Identity Negotiation Response: None > DEBUG:pynetdicom.events:========================== END A-ASSOCIATE-AC PDU ========================== > ERROR:pynetdicom.dul:Exception in DUL.run(), aborting association > ERROR:pynetdicom.dul:list index out of range > Traceback (most recent call last): > File "D:\Ege\DicomServer\venv\lib\site-packages\pynetdicom\dul.py", line 400, in run > elif self._is_transport_event(): > File "D:\Ege\DicomServer\venv\lib\site-packages\pynetdicom\dul.py", line 188, in _is_transport_event > self._read_pdu_data() > File "D:\Ege\DicomServer\venv\lib\site-packages\pynetdicom\dul.py", line 324, in _read_pdu_data > self.primitive = self.pdu.to_primitive() > File "D:\Ege\DicomServer\venv\lib\site-packages\pynetdicom\pdu.py", line 892, in to_primitive > item.to_primitive() > File "D:\Ege\DicomServer\venv\lib\site-packages\pynetdicom\pdu_items.py", line 860, in to_primitive > self.transfer_syntax_sub_item[0].transfer_syntax_name > IndexError: list index out of range > ERROR:root:Association rejected, aborted or never connected Code: ``` import logging from pydicom.dataset import Dataset from pynetdicom import AE, StoragePresentationContexts, evt from pynetdicom.sop_class import ( CTImageStorage, DigitalMammographyXRayImagePresentationStorage, PatientRootQueryRetrieveInformationModelMove) from config import AE_TITLE, PEER_AE_TITLE, PEER_IP, PEER_PORT, PORT from EventHandlers import handle_store logging.basicConfig(level=logging.DEBUG) def moveDataset(aeTitle, port, peerAeTitle, peerIP, peerPort, ds): ae = _initAE(aeTitle) # Start our Storage SCP in non-blocking mode, listening on port 11120 handlers = [(evt.EVT_C_STORE, handle_store)] scp = ae.start_server(('', port), block=False, evt_handlers=handlers) logging.info("Server started.") try: # Associate with peer AE assoc = ae.associate(peerIP, peerPort, ae_title=peerAeTitle) if assoc.is_established: logging.info("Association established") _moveDatasetOverAssociation(assoc, ds) # Release the association assoc.release() else: logging.error('Association rejected, aborted or never connected') finally: # Stop Storage SCP scp.shutdown() def _initAE(aeTitle): # Initialise the Application Entity ae = AE(ae_title=aeTitle) ae.add_requested_context(PatientRootQueryRetrieveInformationModelMove) # Add the Storage SCP's supported presentation contexts ae.add_supported_context(CTImageStorage) ae.add_supported_context(DigitalMammographyXRayImagePresentationStorage) return ae def _moveDatasetOverAssociation(assoc, dataset): responses = assoc.send_c_move(dataset, assoc.ae.ae_title, query_model='P') for (status, identifier) in responses: if status: logging.debug('C-MOVE query status: 0x{0:04x}'.format(status.Status)) # If the status is 'Pending' then `identifier` is the C-MOVE response if status.Status in (0xFF00, 0xFF01): logging.debug(identifier) else: logging.error('Connection timed out, was aborted or received invalid response') if __name__ == "__main__": # Create out identifier (query) dataset ds = Dataset() ds.AccessionNumber = 'EU0000688977' # Balkan, Esma moveDataset(AE_TITLE, PORT, PEER_AE_TITLE, PEER_IP, PEER_PORT,ds) ``` config.py ``` AE_TITLE = b'EGE-AI' PORT = 106 PEER_AE_TITLE = b'ONIS25' PEER_IP = "127.0.0.1" PEER_PORT = 104 ```
0.0
853b2cfe3b14cf5e8a7b554334a4c6c4d65febfb
[ "pynetdicom/tests/test_pdu.py::TestASSOC_AC::test_no_transfer_syntax" ]
[ "pynetdicom/tests/test_pdu.py::TestPDU::test_decode_raises", "pynetdicom/tests/test_pdu.py::TestPDU::test_decoders_raises", "pynetdicom/tests/test_pdu.py::TestPDU::test_equality", "pynetdicom/tests/test_pdu.py::TestPDU::test_encode_raises", "pynetdicom/tests/test_pdu.py::TestPDU::test_encoders_raises", "pynetdicom/tests/test_pdu.py::TestPDU::test_generate_items", "pynetdicom/tests/test_pdu.py::TestPDU::test_generate_items_raises", "pynetdicom/tests/test_pdu.py::TestPDU::test_hash_raises", "pynetdicom/tests/test_pdu.py::TestPDU::test_inequality", "pynetdicom/tests/test_pdu.py::TestPDU::test_pdu_length_raises", "pynetdicom/tests/test_pdu.py::TestPDU::test_pdu_type_raises", "pynetdicom/tests/test_pdu.py::TestPDU::test_wrap_bytes", "pynetdicom/tests/test_pdu.py::TestPDU::test_wrap_encode_items", "pynetdicom/tests/test_pdu.py::TestPDU::test_wrap_encode_uid", "pynetdicom/tests/test_pdu.py::TestPDU::test_wrap_generate_items", "pynetdicom/tests/test_pdu.py::TestPDU::test_wrap_pack", "pynetdicom/tests/test_pdu.py::TestPDU::test_wrap_unpack", "pynetdicom/tests/test_pdu.py::TestASSOC_RQ::test_init", "pynetdicom/tests/test_pdu.py::TestASSOC_RQ::test_property_setters", "pynetdicom/tests/test_pdu.py::TestASSOC_RQ::test_string_output", "pynetdicom/tests/test_pdu.py::TestASSOC_RQ::test_decode", "pynetdicom/tests/test_pdu.py::TestASSOC_RQ::test_decode_properties", "pynetdicom/tests/test_pdu.py::TestASSOC_RQ::test_encode", "pynetdicom/tests/test_pdu.py::TestASSOC_RQ::test_to_primitive", "pynetdicom/tests/test_pdu.py::TestASSOC_RQ::test_from_primitive", "pynetdicom/tests/test_pdu.py::TestASSOC_RQ_ApplicationContext::test_decode", "pynetdicom/tests/test_pdu.py::TestASSOC_RQ_PresentationContext::test_decode", "pynetdicom/tests/test_pdu.py::TestASSOC_RQ_PresentationContext::test_decode_properties", "pynetdicom/tests/test_pdu.py::TestASSOC_RQ_PresentationContext_AbstractSyntax::test_decode", "pynetdicom/tests/test_pdu.py::TestASSOC_RQ_PresentationContext_TransferSyntax::test_decode", "pynetdicom/tests/test_pdu.py::TestASSOC_RQ_UserInformation::test_decode", "pynetdicom/tests/test_pdu.py::TestASSOC_RQ_UserInformation::test_decode_properties", "pynetdicom/tests/test_pdu.py::TestASSOC_AC::test_init", "pynetdicom/tests/test_pdu.py::TestASSOC_AC::test_string_output", "pynetdicom/tests/test_pdu.py::TestASSOC_AC::test_decode", "pynetdicom/tests/test_pdu.py::TestASSOC_AC::test_decode_properties", "pynetdicom/tests/test_pdu.py::TestASSOC_AC::test_stream_encode", "pynetdicom/tests/test_pdu.py::TestASSOC_AC::test_to_primitive", "pynetdicom/tests/test_pdu.py::TestASSOC_AC::test_from_primitive", "pynetdicom/tests/test_pdu.py::TestASSOC_AC_ApplicationContext::test_decode", "pynetdicom/tests/test_pdu.py::TestASSOC_AC_PresentationContext::test_decode", "pynetdicom/tests/test_pdu.py::TestASSOC_AC_PresentationContext::test_decode_properties", "pynetdicom/tests/test_pdu.py::TestASSOC_AC_PresentationContext_TransferSyntax::test_decode", "pynetdicom/tests/test_pdu.py::TestASSOC_AC_UserInformation::test_decode", "pynetdicom/tests/test_pdu.py::TestASSOC_AC_UserInformation::test_decode_properties", "pynetdicom/tests/test_pdu.py::TestASSOC_RJ::test_init", "pynetdicom/tests/test_pdu.py::TestASSOC_RJ::test_string_output", "pynetdicom/tests/test_pdu.py::TestASSOC_RJ::test_decod", "pynetdicom/tests/test_pdu.py::TestASSOC_RJ::test_decode_properties", "pynetdicom/tests/test_pdu.py::TestASSOC_RJ::test_encode", "pynetdicom/tests/test_pdu.py::TestASSOC_RJ::test_to_primitive", "pynetdicom/tests/test_pdu.py::TestASSOC_RJ::test_from_primitive", "pynetdicom/tests/test_pdu.py::TestASSOC_RJ::test_result_str", "pynetdicom/tests/test_pdu.py::TestASSOC_RJ::test_source_str", "pynetdicom/tests/test_pdu.py::TestASSOC_RJ::test_reason_str", "pynetdicom/tests/test_pdu.py::TestP_DATA_TF::test_init", "pynetdicom/tests/test_pdu.py::TestP_DATA_TF::test_string_output", "pynetdicom/tests/test_pdu.py::TestP_DATA_TF::test_decode", "pynetdicom/tests/test_pdu.py::TestP_DATA_TF::test_encode", "pynetdicom/tests/test_pdu.py::TestP_DATA_TF::test_to_primitive", "pynetdicom/tests/test_pdu.py::TestP_DATA_TF::test_from_primitive", "pynetdicom/tests/test_pdu.py::TestP_DATA_TF::test_generate_items", "pynetdicom/tests/test_pdu.py::TestP_DATA_TF::test_generate_items_raises", "pynetdicom/tests/test_pdu.py::TestP_DATA_TF::test_wrap_generate_items", "pynetdicom/tests/test_pdu.py::TestRELEASE_RQ::test_init", "pynetdicom/tests/test_pdu.py::TestRELEASE_RQ::test_string_output", "pynetdicom/tests/test_pdu.py::TestRELEASE_RQ::test_decode", "pynetdicom/tests/test_pdu.py::TestRELEASE_RQ::test_encode", "pynetdicom/tests/test_pdu.py::TestRELEASE_RQ::test_to_primitive", "pynetdicom/tests/test_pdu.py::TestRELEASE_RQ::test_from_primitive", "pynetdicom/tests/test_pdu.py::TestRELEASE_RP::test_init", "pynetdicom/tests/test_pdu.py::TestRELEASE_RP::test_string_output", "pynetdicom/tests/test_pdu.py::TestRELEASE_RP::test_decode", "pynetdicom/tests/test_pdu.py::TestRELEASE_RP::test_encode", "pynetdicom/tests/test_pdu.py::TestRELEASE_RP::test_to_primitive", "pynetdicom/tests/test_pdu.py::TestRELEASE_RP::test_from_primitive", "pynetdicom/tests/test_pdu.py::TestABORT::test_init", "pynetdicom/tests/test_pdu.py::TestABORT::test_string_output", "pynetdicom/tests/test_pdu.py::TestABORT::test_a_abort_decode", "pynetdicom/tests/test_pdu.py::TestABORT::test_a_p_abort_decode", "pynetdicom/tests/test_pdu.py::TestABORT::test_a_abort_encode", "pynetdicom/tests/test_pdu.py::TestABORT::test_a_p_abort_encode", "pynetdicom/tests/test_pdu.py::TestABORT::test_to_a_abort_primitive", "pynetdicom/tests/test_pdu.py::TestABORT::test_to_a_p_abort_primitive", "pynetdicom/tests/test_pdu.py::TestABORT::test_a_abort_from_primitive", "pynetdicom/tests/test_pdu.py::TestABORT::test_a_p_abort_from_primitive", "pynetdicom/tests/test_pdu.py::TestABORT::test_source_str", "pynetdicom/tests/test_pdu.py::TestABORT::test_reason_str", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_decode_raises", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_decoders_raises", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_equality", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_encode_raises", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_encoders_raises", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_generate_items", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_generate_items_raises", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_hash_raises", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_inequality", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_item_length_raises", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_item_type_raises", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_wrap_bytes", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_wrap_encode_items", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_wrap_generate_items", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_wrap_pack", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_wrap_uid_bytes", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_wrap_unpack", "pynetdicom/tests/test_pdu_items.py::TestPDU::test_wrap_encode_uid", "pynetdicom/tests/test_pdu_items.py::TestApplicationContext::test_init", "pynetdicom/tests/test_pdu_items.py::TestApplicationContext::test_uid_conformance", "pynetdicom/tests/test_pdu_items.py::TestApplicationContext::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestApplicationContext::test_rq_decode", "pynetdicom/tests/test_pdu_items.py::TestApplicationContext::test_ac_decode", "pynetdicom/tests/test_pdu_items.py::TestApplicationContext::test_encode_cycle", "pynetdicom/tests/test_pdu_items.py::TestApplicationContext::test_update", "pynetdicom/tests/test_pdu_items.py::TestApplicationContext::test_properties", "pynetdicom/tests/test_pdu_items.py::TestApplicationContext::test_encode_odd", "pynetdicom/tests/test_pdu_items.py::TestApplicationContext::test_encode_even", "pynetdicom/tests/test_pdu_items.py::TestApplicationContext::test_decode_odd", "pynetdicom/tests/test_pdu_items.py::TestApplicationContext::test_decode_even", "pynetdicom/tests/test_pdu_items.py::TestApplicationContext::test_decode_padded_odd", "pynetdicom/tests/test_pdu_items.py::TestPresentationContextRQ::test_init", "pynetdicom/tests/test_pdu_items.py::TestPresentationContextRQ::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestPresentationContextRQ::test_decode", "pynetdicom/tests/test_pdu_items.py::TestPresentationContextRQ::test_encode", "pynetdicom/tests/test_pdu_items.py::TestPresentationContextRQ::test_to_primitive", "pynetdicom/tests/test_pdu_items.py::TestPresentationContextRQ::test_from_primitive", "pynetdicom/tests/test_pdu_items.py::TestPresentationContextAC::test_init", "pynetdicom/tests/test_pdu_items.py::TestPresentationContextAC::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestPresentationContextAC::test_decode", "pynetdicom/tests/test_pdu_items.py::TestPresentationContextAC::test_encode", "pynetdicom/tests/test_pdu_items.py::TestPresentationContextAC::test_to_primitive", "pynetdicom/tests/test_pdu_items.py::TestPresentationContextAC::test_from_primitive", "pynetdicom/tests/test_pdu_items.py::TestPresentationContextAC::test_result_str", "pynetdicom/tests/test_pdu_items.py::TestPresentationContextAC::test_decode_empty", "pynetdicom/tests/test_pdu_items.py::TestAbstractSyntax::test_init", "pynetdicom/tests/test_pdu_items.py::TestAbstractSyntax::test_uid_conformance", "pynetdicom/tests/test_pdu_items.py::TestAbstractSyntax::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestAbstractSyntax::test_decode", "pynetdicom/tests/test_pdu_items.py::TestAbstractSyntax::test_encode_cycle", "pynetdicom/tests/test_pdu_items.py::TestAbstractSyntax::test_properies", "pynetdicom/tests/test_pdu_items.py::TestAbstractSyntax::test_encode_odd", "pynetdicom/tests/test_pdu_items.py::TestAbstractSyntax::test_encode_even", "pynetdicom/tests/test_pdu_items.py::TestAbstractSyntax::test_decode_odd", "pynetdicom/tests/test_pdu_items.py::TestAbstractSyntax::test_decode_even", "pynetdicom/tests/test_pdu_items.py::TestAbstractSyntax::test_decode_padded_odd", "pynetdicom/tests/test_pdu_items.py::TestTransferSyntax::test_init", "pynetdicom/tests/test_pdu_items.py::TestTransferSyntax::test_uid_conformance", "pynetdicom/tests/test_pdu_items.py::TestTransferSyntax::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestTransferSyntax::test_decode", "pynetdicom/tests/test_pdu_items.py::TestTransferSyntax::test_encode_cycle", "pynetdicom/tests/test_pdu_items.py::TestTransferSyntax::test_properies", "pynetdicom/tests/test_pdu_items.py::TestTransferSyntax::test_encode_odd", "pynetdicom/tests/test_pdu_items.py::TestTransferSyntax::test_encode_even", "pynetdicom/tests/test_pdu_items.py::TestTransferSyntax::test_decode_odd", "pynetdicom/tests/test_pdu_items.py::TestTransferSyntax::test_decode_even", "pynetdicom/tests/test_pdu_items.py::TestTransferSyntax::test_decode_padded_odd", "pynetdicom/tests/test_pdu_items.py::TestTransferSyntax::test_decode_empty", "pynetdicom/tests/test_pdu_items.py::TestPresentationDataValue::test_init", "pynetdicom/tests/test_pdu_items.py::TestPresentationDataValue::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestPresentationDataValue::test_decode", "pynetdicom/tests/test_pdu_items.py::TestPresentationDataValue::test_encode", "pynetdicom/tests/test_pdu_items.py::TestPresentationDataValue::test_properies", "pynetdicom/tests/test_pdu_items.py::TestPresentationDataValue::test_message_control_header_byte", "pynetdicom/tests/test_pdu_items.py::TestUserInformation::test_init", "pynetdicom/tests/test_pdu_items.py::TestUserInformation::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestUserInformation::test_decode", "pynetdicom/tests/test_pdu_items.py::TestUserInformation::test_encode", "pynetdicom/tests/test_pdu_items.py::TestUserInformation::test_to_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserInformation::test_from_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserInformation::test_properties_usr_id", "pynetdicom/tests/test_pdu_items.py::TestUserInformation::test_properties_ext_neg", "pynetdicom/tests/test_pdu_items.py::TestUserInformation::test_properties_role", "pynetdicom/tests/test_pdu_items.py::TestUserInformation::test_properties_async", "pynetdicom/tests/test_pdu_items.py::TestUserInformation::test_properties_max_pdu", "pynetdicom/tests/test_pdu_items.py::TestUserInformation::test_properties_implementation", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_MaximumLength::test_init", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_MaximumLength::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_MaximumLength::test_decode", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_MaximumLength::test_encode", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_MaximumLength::test_to_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_MaximumLength::test_from_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationUID::test_uid_conformance", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationUID::test_init", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationUID::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationUID::test_decode", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationUID::test_encode", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationUID::test_to_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationUID::test_from_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationUID::test_properies", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationUID::test_encode_odd", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationUID::test_encode_even", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationUID::test_decode_odd", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationUID::test_decode_even", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationUID::test_decode_padded_odd", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationUID::test_no_log_padded", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationVersion::test_init", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationVersion::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationVersion::test_decode", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationVersion::test_encode", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationVersion::test_to_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationVersion::test_from_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ImplementationVersion::test_properies", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_Asynchronous::test_init", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_Asynchronous::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_Asynchronous::test_decode", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_Asynchronous::test_encode", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_Asynchronous::test_to_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_Asynchronous::test_from_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_Asynchronous::test_properies", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_RoleSelection::test_uid_conformance", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_RoleSelection::test_init", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_RoleSelection::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_RoleSelection::test_decode", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_RoleSelection::test_encode", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_RoleSelection::test_to_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_RoleSelection::test_from_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_RoleSelection::test_from_primitive_no_scu", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_RoleSelection::test_properties", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_RoleSelection::test_encode_odd", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_RoleSelection::test_encode_even", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_RoleSelection::test_decode_odd", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_RoleSelection::test_decode_even", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_RoleSelection::test_decode_padded_odd", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityRQ_UserNoPass::test_init", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityRQ_UserNoPass::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityRQ_UserNoPass::test_decode", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityRQ_UserNoPass::test_encode", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityRQ_UserNoPass::test_to_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityRQ_UserNoPass::test_from_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityRQ_UserNoPass::test_properies", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityRQ_UserPass::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityRQ_UserPass::test_decode", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityRQ_UserPass::test_encode", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityRQ_UserPass::test_to_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityRQ_UserPass::test_from_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityRQ_UserPass::test_properties", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityAC_UserResponse::test_init", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityAC_UserResponse::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityAC_UserResponse::test_decode", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityAC_UserResponse::test_encode", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityAC_UserResponse::test_to_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityAC_UserResponse::test_from_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserIdentityAC_UserResponse::test_properies", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ExtendedNegotiation::test_uid_conformance", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ExtendedNegotiation::test_init", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ExtendedNegotiation::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ExtendedNegotiation::test_decode", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ExtendedNegotiation::test_encode", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ExtendedNegotiation::test_to_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ExtendedNegotiation::test_from_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ExtendedNegotiation::test_properties", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ExtendedNegotiation::test_encode_odd", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ExtendedNegotiation::test_encode_even", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ExtendedNegotiation::test_decode_odd", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ExtendedNegotiation::test_decode_even", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_ExtendedNegotiation::test_decode_padded_odd", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_CommonExtendedNegotiation::test_uid_conformance", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_CommonExtendedNegotiation::test_init", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_CommonExtendedNegotiation::test_string_output", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_CommonExtendedNegotiation::test_decode", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_CommonExtendedNegotiation::test_encode", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_CommonExtendedNegotiation::test_to_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_CommonExtendedNegotiation::test_from_primitive", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_CommonExtendedNegotiation::test_properties", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_CommonExtendedNegotiation::test_generate_items", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_CommonExtendedNegotiation::test_generate_items_raises", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_CommonExtendedNegotiation::test_wrap_generate_items", "pynetdicom/tests/test_pdu_items.py::TestUserInformation_CommonExtendedNegotiation::test_wrap_list" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-07-07 02:48:26+00:00
mit
4,931
pydicom__pynetdicom-404
diff --git a/docs/changelog/v1.5.0.rst b/docs/changelog/v1.5.0.rst index 8bd8344df..5c88acc2d 100644 --- a/docs/changelog/v1.5.0.rst +++ b/docs/changelog/v1.5.0.rst @@ -10,6 +10,14 @@ Fixes closing its sockets (:issue:`382`) * Improved the robustness of determining the local IP address (:issue:`394`) +Enhancements +............ + +* Added configuration option :attr:`_config.USE_SHORT_DIMSE_AET + <pynetdicom._config.USE_SHORT_DIMSE_AET>` so elements with a VR of *AE* in + DIMSE messages are only padded to the shortest even length rather than to + the maximum 16 characters. (:issue:`403`) + Changes ....... diff --git a/docs/reference/config.rst b/docs/reference/config.rst index 6cb9323fa..6e43fb58b 100644 --- a/docs/reference/config.rst +++ b/docs/reference/config.rst @@ -10,3 +10,4 @@ Configuration Options (:mod:`pynetdicom._config`) ENFORCE_UID_CONFORMANCE LOG_HANDLER_LEVEL + USE_SHORT_DIMSE_AET diff --git a/pynetdicom/_config.py b/pynetdicom/_config.py index e115d9f9a..53093bc9d 100644 --- a/pynetdicom/_config.py +++ b/pynetdicom/_config.py @@ -31,3 +31,19 @@ Examples >>> from pynetdicom import _config >>> _config.ENFORCE_UID_CONFORMANCE = True """ + + +USE_SHORT_DIMSE_AET = False +"""Use short AE titles in DIMSE messages. + +If ``False`` then elements with a VR of AE in DIMSE messages will be padded +with trailing spaces up to the maximum allowable length (16 bytes), otherwise +they will be padded with zero or one space to the smallest possible even +length (i.e an AE title with 7 characters will be trailing padded to 8). + +Examples +-------- + +>>> from pynetdicom import _config +>>> _config.USE_SHORT_DIMSE_AET = True +""" diff --git a/pynetdicom/dimse_primitives.py b/pynetdicom/dimse_primitives.py index 0b276f203..3d8371844 100644 --- a/pynetdicom/dimse_primitives.py +++ b/pynetdicom/dimse_primitives.py @@ -17,6 +17,7 @@ import logging from pydicom.tag import Tag from pydicom.uid import UID +from pynetdicom import _config from pynetdicom.utils import validate_ae_title, validate_uid @@ -589,7 +590,7 @@ class C_STORE(DIMSEPrimitive): if value: try: self._move_originator_application_entity_title = ( - validate_ae_title(value) + validate_ae_title(value, _config.USE_SHORT_DIMSE_AET) ) except ValueError: LOGGER.error( @@ -1154,7 +1155,9 @@ class C_MOVE(DIMSEPrimitive): value = codecs.encode(value, 'ascii') if value is not None: - self._move_destination = validate_ae_title(value) + self._move_destination = validate_ae_title( + value, _config.USE_SHORT_DIMSE_AET + ) else: self._move_destination = None diff --git a/pynetdicom/utils.py b/pynetdicom/utils.py index fc9bfbc0a..0b5f6f5ae 100644 --- a/pynetdicom/utils.py +++ b/pynetdicom/utils.py @@ -71,7 +71,7 @@ def pretty_bytes(bytestream, prefix=' ', delimiter=' ', items_per_line=16, return lines -def validate_ae_title(ae_title): +def validate_ae_title(ae_title, use_short=False): """Return a valid AE title from `ae_title`, if possible. An AE title: @@ -93,6 +93,10 @@ def validate_ae_title(ae_title): ---------- ae_title : bytes The AE title to check. + use_short : bool, optional + If ``False`` (default) then pad AE titles with trailing spaces up to + the maximum allowable length (16 bytes), otherwise only pad odd length + AE titles with a single trailing space to make it even length. Returns ------- @@ -131,8 +135,12 @@ def validate_ae_title(ae_title): # Truncate if longer than 16 characters ae_title = ae_title[:16] - # Pad out to 16 characters using spaces - ae_title = ae_title.ljust(16) + if not use_short: + # Pad out to 16 characters using spaces + ae_title = ae_title.ljust(16) + elif len(ae_title) % 2: + # Pad to even length + ae_title += ' ' # Unicode category: 'Cc' is control characters invalid = [
pydicom/pynetdicom
68fd980594bcc5a83480710dce5bfae412cd6432
diff --git a/pynetdicom/tests/test_dimse_c.py b/pynetdicom/tests/test_dimse_c.py index 678d7e280..19c622887 100644 --- a/pynetdicom/tests/test_dimse_c.py +++ b/pynetdicom/tests/test_dimse_c.py @@ -50,9 +50,11 @@ class TestPrimitive_C_STORE(object): """Test DIMSE C-STORE operations.""" def setup(self): self.default_conformance = _config.ENFORCE_UID_CONFORMANCE + self.default_aet_length = _config.USE_SHORT_DIMSE_AET def teardown(self): _config.ENFORCE_UID_CONFORMANCE = self.default_conformance + _config.USE_SHORT_DIMSE_AET = self.default_aet_length def test_assignment(self): """ Check assignment works correctly """ @@ -320,6 +322,38 @@ class TestPrimitive_C_STORE(object): primitive.Status = 0x0000 assert primitive.is_valid_response + def test_aet_short_false(self): + """Test using long AE titles.""" + primitive = C_STORE() + + _config.USE_SHORT_DIMSE_AET = False + + primitive.MoveOriginatorApplicationEntityTitle = b'A' + aet = primitive.MoveOriginatorApplicationEntityTitle + assert b'A ' == aet + + def test_aet_short_true(self): + """Test using short AE titles.""" + primitive = C_STORE() + + _config.USE_SHORT_DIMSE_AET = True + + primitive.MoveOriginatorApplicationEntityTitle = b'A' + aet = primitive.MoveOriginatorApplicationEntityTitle + assert b'A ' == aet + + primitive.MoveOriginatorApplicationEntityTitle = b'ABCDEFGHIJKLMNO' + aet = primitive.MoveOriginatorApplicationEntityTitle + assert b'ABCDEFGHIJKLMNO ' == aet + + primitive.MoveOriginatorApplicationEntityTitle = b'ABCDEFGHIJKLMNOP' + aet = primitive.MoveOriginatorApplicationEntityTitle + assert b'ABCDEFGHIJKLMNOP' == aet + + primitive.MoveOriginatorApplicationEntityTitle = b'ABCDEFGHIJKLMNOPQ' + aet = primitive.MoveOriginatorApplicationEntityTitle + assert b'ABCDEFGHIJKLMNOP' == aet + class TestPrimitive_C_FIND(object): """Test DIMSE C-FIND operations.""" @@ -789,9 +823,11 @@ class TestPrimitive_C_MOVE(object): """Test DIMSE C-MOVE operations.""" def setup(self): self.default_conformance = _config.ENFORCE_UID_CONFORMANCE + self.default_aet_length = _config.USE_SHORT_DIMSE_AET def teardown(self): _config.ENFORCE_UID_CONFORMANCE = self.default_conformance + _config.USE_SHORT_DIMSE_AET = self.default_aet_length def test_assignment(self): """ Check assignment works correctly """ @@ -1047,6 +1083,34 @@ class TestPrimitive_C_MOVE(object): primitive.Status = 0x0000 assert primitive.is_valid_response + def test_aet_short_false(self): + """Test using long AE titles.""" + primitive = C_MOVE() + + _config.USE_SHORT_DIMSE_AET = False + + primitive.MoveDestination = b'A' + assert b'A ' == primitive.MoveDestination + + def test_aet_short_true(self): + """Test using short AE titles.""" + primitive = C_MOVE() + + _config.USE_SHORT_DIMSE_AET = True + + primitive.MoveDestination = b'A' + aet = primitive.MoveDestination + assert b'A ' == primitive.MoveDestination + + primitive.MoveDestination = b'ABCDEFGHIJKLMNO' + assert b'ABCDEFGHIJKLMNO ' == primitive.MoveDestination + + primitive.MoveDestination = b'ABCDEFGHIJKLMNOP' + assert b'ABCDEFGHIJKLMNOP' == primitive.MoveDestination + + primitive.MoveDestination = b'ABCDEFGHIJKLMNOPQ' + assert b'ABCDEFGHIJKLMNOP' == primitive.MoveDestination + class TestPrimitive_C_ECHO(object): """Test DIMSE C-ECHO operations."""
Can't send move requests to Siemens network nodes **Is your feature request related to a problem? Please describe.** It appears that many (most? all?) Siemens instruments have some buggy behavior in how they handle the "MoveDestination" inside a move request. If the AE Title provided in this field is padded with more white space than strictly needed to make the length even (e.g. an AE Title that is 9 chars is padded to be 16 chars instead of just 10) then the move request will be denied. This prevents the use of pynetdicom to send move requests to Siemens instruments. Conversely, the actual association request PDU must have the AE Title padded to the full 16 chars in order to be accepted. I guess there may be other situations where an AE Title needs to be passed in as an attribute and similar restrictions apply. **Describe the solution you'd like** The dcmtk library seems to only pad the AE Title out to 16 bytes in the association request, and otherwise just pad to the next even length.
0.0
68fd980594bcc5a83480710dce5bfae412cd6432
[ "pynetdicom/tests/test_dimse_c.py::TestPrimitive_C_STORE::test_aet_short_true", "pynetdicom/tests/test_dimse_c.py::TestPrimitive_C_MOVE::test_aet_short_true" ]
[ "pynetdicom/tests/test_dimse_c.py::TestPrimitive_C_CANCEL::test_assignment", "pynetdicom/tests/test_dimse_c.py::TestPrimitive_C_STORE::test_assignment", "pynetdicom/tests/test_dimse_c.py::TestPrimitive_C_STORE::test_uid_exceptions_false", "pynetdicom/tests/test_dimse_c.py::TestPrimitive_C_STORE::test_uid_exceptions_true", "pynetdicom/tests/test_dimse_c.py::TestPrimitive_C_STORE::test_exceptions", "pynetdicom/tests/test_dimse_c.py::TestPrimitive_C_STORE::test_conversion_rq", "pynetdicom/tests/test_dimse_c.py::TestPrimitive_C_STORE::test_conversion_rsp", "pynetdicom/tests/test_dimse_c.py::TestPrimitive_C_STORE::test_is_valid_request", "pynetdicom/tests/test_dimse_c.py::TestPrimitive_C_STORE::test_is_valid_resposne", "pynetdicom/tests/test_dimse_c.py::TestPrimitive_C_STORE::test_aet_short_false", "pynetdicom/tests/test_dimse_c.py::TestPrimitive_C_FIND::test_assignment", "pynetdicom/tests/test_dimse_c.py::TestPrimitive_C_FIND::test_uid_exceptions_false", "pynetdicom/tests/test_dimse_c.py::TestPrimitive_C_FIND::test_uid_exceptions_true", "pynetdicom/tests/test_dimse_c.py::TestPrimitive_C_FIND::test_exceptions", "pynetdicom/tests/test_dimse_c.py::TestPrimitive_C_FIND::test_conversion_rq", "pynetdicom/tests/test_dimse_c.py::TestPrimitive_C_FIND::test_conversion_rsp", "pynetdicom/tests/test_dimse_c.py::TestPrimitive_C_FIND::test_is_valid_request", "pynetdicom/tests/test_dimse_c.py::TestPrimitive_C_FIND::test_is_valid_resposne", "pynetdicom/tests/test_dimse_c.py::TestPrimitive_C_GET::test_assignment", "pynetdicom/tests/test_dimse_c.py::TestPrimitive_C_GET::test_uid_exceptions_false", "pynetdicom/tests/test_dimse_c.py::TestPrimitive_C_GET::test_uid_exceptions_true", "pynetdicom/tests/test_dimse_c.py::TestPrimitive_C_GET::test_exceptions", "pynetdicom/tests/test_dimse_c.py::TestPrimitive_C_GET::test_conversion_rq", "pynetdicom/tests/test_dimse_c.py::TestPrimitive_C_GET::test_conversion_rsp", "pynetdicom/tests/test_dimse_c.py::TestPrimitive_C_GET::test_is_valid_request", "pynetdicom/tests/test_dimse_c.py::TestPrimitive_C_GET::test_is_valid_resposne", "pynetdicom/tests/test_dimse_c.py::TestPrimitive_C_MOVE::test_uid_exceptions_false", "pynetdicom/tests/test_dimse_c.py::TestPrimitive_C_MOVE::test_uid_exceptions_true", "pynetdicom/tests/test_dimse_c.py::TestPrimitive_C_MOVE::test_exceptions", "pynetdicom/tests/test_dimse_c.py::TestPrimitive_C_MOVE::test_conversion_rsp", "pynetdicom/tests/test_dimse_c.py::TestPrimitive_C_MOVE::test_is_valid_request", "pynetdicom/tests/test_dimse_c.py::TestPrimitive_C_MOVE::test_is_valid_resposne", "pynetdicom/tests/test_dimse_c.py::TestPrimitive_C_MOVE::test_aet_short_false", "pynetdicom/tests/test_dimse_c.py::TestPrimitive_C_ECHO::test_assignment", "pynetdicom/tests/test_dimse_c.py::TestPrimitive_C_ECHO::test_uid_exceptions_false", "pynetdicom/tests/test_dimse_c.py::TestPrimitive_C_ECHO::test_uid_exceptions_true", "pynetdicom/tests/test_dimse_c.py::TestPrimitive_C_ECHO::test_exceptions", "pynetdicom/tests/test_dimse_c.py::TestPrimitive_C_ECHO::test_conversion_rq", "pynetdicom/tests/test_dimse_c.py::TestPrimitive_C_ECHO::test_conversion_rsp", "pynetdicom/tests/test_dimse_c.py::TestPrimitive_C_ECHO::test_is_valid_request", "pynetdicom/tests/test_dimse_c.py::TestPrimitive_C_ECHO::test_is_valid_resposne" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-09-19 04:07:24+00:00
mit
4,932
pydicom__pynetdicom-425
diff --git a/docs/changelog/v1.5.0.rst b/docs/changelog/v1.5.0.rst index 313fcb339..7cef687f0 100644 --- a/docs/changelog/v1.5.0.rst +++ b/docs/changelog/v1.5.0.rst @@ -29,6 +29,7 @@ Enhancements :mod:`~pynetdicom.sop_class`. * Added support for the DIMSE intervention event handlers aborting or releasing the association during service class operation. +* Add new SOP classes up to 2019e version of the standard (:issue:`424`) Changes ....... diff --git a/docs/service_classes/storage_service_class.rst b/docs/service_classes/storage_service_class.rst index ce6389d30..fda7568ce 100644 --- a/docs/service_classes/storage_service_class.rst +++ b/docs/service_classes/storage_service_class.rst @@ -237,6 +237,10 @@ Supported SOP Classes +----------------------------------+-------------------------------------------------------------------+---------+ | 1.2.840.10008.5.1.4.1.1.88.73 | PatientRadiationDoseSRStorage | A.35.18 | +----------------------------------+-------------------------------------------------------------------+---------+ +| 1.2.840.10008.5.1.4.1.1.88.74 | PlannedImagingAgentAdministrationSRStorage | A.35.19 | ++----------------------------------+-------------------------------------------------------------------+---------+ +| 1.2.840.10008.5.1.4.1.1.88.75 | PerformedImagingAgestAdministrationSRStorage | A.35.20 | ++----------------------------------+-------------------------------------------------------------------+---------+ | 1.2.840.10008.5.1.4.1.1.90.1 | ContentAssessmentResultsStorage | A.81 | +----------------------------------+-------------------------------------------------------------------+---------+ | 1.2.840.10008.5.1.4.1.1.104.1 | EncapsulatedPDFStorage | A.45.1 | @@ -273,6 +277,14 @@ Supported SOP Classes +----------------------------------+-------------------------------------------------------------------+---------+ | 1.2.840.10008.5.1.4.1.1.481.9 | RTIonBeamsTreatmentRecordStorage | A.50 | +----------------------------------+-------------------------------------------------------------------+---------+ +| 1.2.840.10008.5.1.4.1.1.481.10 | RTPhysicianIntentStorage | A.86.1 | ++----------------------------------+-------------------------------------------------------------------+---------+ +| 1.2.840.10008.5.1.4.1.1.481.11 | RTSegmentAnnotationStorage | A.86.1 | ++----------------------------------+-------------------------------------------------------------------+---------+ +| 1.2.840.10008.5.1.4.1.1.481.12 | RTRadiationSetStorage | A.86.1 | ++----------------------------------+-------------------------------------------------------------------+---------+ +| 1.2.840.10008.5.1.4.1.1.481.13 | CArmPhotonElectronRadiationStorage | A.86.1 | ++----------------------------------+-------------------------------------------------------------------+---------+ | 1.2.840.10008.5.1.4.34.7 | RTBeamsDeliveryInstructionStorage | A.64 | +----------------------------------+-------------------------------------------------------------------+---------+ | 1.2.840.10008.5.1.4.34.10 | RTBrachyApplicationSetupDeliveryInstructionsStorage | A.79 | diff --git a/docs/service_classes/ups.rst b/docs/service_classes/ups.rst index 1adbb4ef9..f77c0ae37 100644 --- a/docs/service_classes/ups.rst +++ b/docs/service_classes/ups.rst @@ -24,6 +24,8 @@ Supported SOP Classes +----------------------------+------------------------------------------------+ | 1.2.840.10008.5.1.4.34.6.4 | UnifiedProcedureStepEventSOPClass | +----------------------------+------------------------------------------------+ +| 1.2.840.10008.5.1.4.34.6.5 | UnifiedProcedureStepQuerySOPClass | ++----------------------------+------------------------------------------------+ DIMSE Services @@ -64,6 +66,10 @@ DIMSE Services +---------------------------+-------------------------------+ | N-EVENT-REPORT | Mandatory/Mandatory | +---------------------------+-------------------------------+ +| *Unified Procedure Step Query SOP Class* | ++---------------------------+-------------------------------+ +| C-FIND | Mandatory/Mandatory | ++---------------------------+-------------------------------+ .. _ups_statuses: diff --git a/pynetdicom/sop_class.py b/pynetdicom/sop_class.py index 854766f5d..fd209d605 100644 --- a/pynetdicom/sop_class.py +++ b/pynetdicom/sop_class.py @@ -128,6 +128,16 @@ class SOPClass(UID): def _generate_sop_classes(sop_class_dict): """Generate the SOP Classes.""" + + _2019e = ( + '1.2.840.10008.5.1.4.1.1.88.74', + '1.2.840.10008.5.1.4.1.1.88.75', + '1.2.840.10008.5.1.4.1.1.481.10', + '1.2.840.10008.5.1.4.1.1.481.11', + '1.2.840.10008.5.1.4.1.1.481.12', + '1.2.840.10008.5.1.4.1.1.481.13', + ) + for name in sop_class_dict: uid = sop_class_dict[name] sop_class = SOPClass(uid) @@ -135,6 +145,9 @@ def _generate_sop_classes(sop_class_dict): docstring = "``{}``".format(uid) if uid in ('1.2.840.10008.5.1.1.9', '1.2.840.10008.5.1.1.18'): docstring += "\n\n.. versionadded:: 1.4" + elif uid in _2019e: + docstring += "\n\n.. versionadded:: 1.5" + sop_class.__doc__ = docstring globals()[name] = sop_class @@ -361,6 +374,8 @@ _STORAGE_CLASSES = { 'AcquisitionContextSRStorage' : '1.2.840.10008.5.1.4.1.1.88.71', # A.35.16 'SimplifiedAdultEchoSRStorage' : '1.2.840.10008.5.1.4.1.1.88.72', # A.35.17 'PatientRadiationDoseSRStorage' : '1.2.840.10008.5.1.4.1.1.88.73', # A.35.18 + 'PlannedImagingAgentAdministrationSRStorage' : '1.2.840.10008.5.1.4.1.1.88.74', # A.35.19 + 'PerformedImagingAgestAdministrationSRStorage' : '1.2.840.10008.5.1.4.1.1.88.75', # A.35.20 'ContentAssessmentResultsStorage' : '1.2.840.10008.5.1.4.1.1.90.1', # A.81 'EncapsulatedPDFStorage' : '1.2.840.10008.5.1.4.1.1.104.1', # A.45.1 'EncapsulatedCDAStorage' : '1.2.840.10008.5.1.4.1.1.104.2', # A.45.2 @@ -379,6 +394,10 @@ _STORAGE_CLASSES = { 'RTTreatmentSummaryRecordStorage' : '1.2.840.10008.5.1.4.1.1.481.7', # A.31 'RTIonPlanStorage' : '1.2.840.10008.5.1.4.1.1.481.8', # A.49 'RTIonBeamsTreatmentRecordStorage' : '1.2.840.10008.5.1.4.1.1.481.9', # A.50 + 'RTPhysicianIntentStorage' : '1.2.840.10008.5.1.4.1.1.481.10', # A.86.1.2 + 'RTSegmentAnnotationStorage' : '1.2.840.10008.5.1.4.1.1.481.11', # A.86.1.3 + 'RTRadiationSetStorage' : '1.2.840.10008.5.1.4.1.1.481.12', # A.86.1.4 + 'CArmPhotonElectronRadiationStorage' : '1.2.840.10008.5.1.4.1.1.481.13', # A.86.1.5 'RTBeamsDeliveryInstructionStorage' : '1.2.840.10008.5.1.4.34.7', # A.64 'RTBrachyApplicationSetupDeliveryInstructionsStorage' : '1.2.840.10008.5.1.4.34.10', # A.79 } @@ -394,6 +413,7 @@ _UNIFIED_PROCEDURE_STEP_CLASSES = { 'UnifiedProcedureStepWatchSOPClass' : '1.2.840.10008.5.1.4.34.6.2', 'UnifiedProcedureStepPullSOPClass' : '1.2.840.10008.5.1.4.34.6.3', 'UnifiedProcedureStepEventSOPClass' : '1.2.840.10008.5.1.4.34.6.4', + 'UnifiedProcedureStepQuerySOPClass' : '1.2.840.10008.5.1.4.34.6.5', } _VERIFICATION_CLASSES = { 'VerificationSOPClass' : '1.2.840.10008.1.1', diff --git a/setup.py b/setup.py index a98619052..808081c88 100644 --- a/setup.py +++ b/setup.py @@ -24,7 +24,9 @@ setup( author_email = "[email protected]", url = "https://github.com/pydicom/pynetdicom", license = "MIT", - keywords = "dicom python medicalimaging radiotherapy oncology pydicom imaging", + keywords = ( + "dicom python medicalimaging radiotherapy oncology pydicom imaging" + ), project_urls={ 'Documentation' : 'https://pydicom.github.io/pynetdicom/' }, @@ -45,5 +47,5 @@ setup( "Topic :: Scientific/Engineering :: Medical Science Apps.", "Topic :: Software Development :: Libraries", ], - install_requires = ["pydicom>=1.3.0"], + install_requires = ["pydicom>=1.4.0"], )
pydicom/pynetdicom
941cc8d2ea32d1b1b8b6fa4cf87be9077655eeae
diff --git a/pynetdicom/tests/test_presentation.py b/pynetdicom/tests/test_presentation.py index edc76e6f5..8cc303fe4 100644 --- a/pynetdicom/tests/test_presentation.py +++ b/pynetdicom/tests/test_presentation.py @@ -1857,8 +1857,8 @@ class TestServiceContexts(object): assert context.context_id is None assert contexts[0].abstract_syntax == '1.2.840.10008.5.1.4.1.1.1' - assert contexts[80].abstract_syntax == '1.2.840.10008.5.1.4.1.1.77.1.4.1' - assert contexts[-1].abstract_syntax == '1.2.840.10008.5.1.4.1.1.90.1' + assert contexts[80].abstract_syntax == '1.2.840.10008.5.1.4.1.1.77.1.2' + assert contexts[-1].abstract_syntax == '1.2.840.10008.5.1.4.1.1.9.2.1' def test_storage_commitement(self): """Tests with storage commitment presentation contexts""" @@ -1886,7 +1886,7 @@ class TestServiceContexts(object): def test_unified_procedure(self): """Tests with unified procedure presentation contexts""" contexts = UnifiedProcedurePresentationContexts - assert len(contexts) == 4 + assert len(contexts) == 5 for context in contexts: assert context.transfer_syntax == DEFAULT_TRANSFER_SYNTAXES @@ -1896,6 +1896,7 @@ class TestServiceContexts(object): assert contexts[1].abstract_syntax == '1.2.840.10008.5.1.4.34.6.2' assert contexts[2].abstract_syntax == '1.2.840.10008.5.1.4.34.6.3' assert contexts[3].abstract_syntax == '1.2.840.10008.5.1.4.34.6.4' + assert contexts[4].abstract_syntax == '1.2.840.10008.5.1.4.34.6.5' def test_verification(self): """Test the verification service presentation contexts."""
Add new 2019e SOP Classes, changes to UPS Update pynetdicom to match 2019e version of the DICOM Standard
0.0
941cc8d2ea32d1b1b8b6fa4cf87be9077655eeae
[ "pynetdicom/tests/test_presentation.py::TestServiceContexts::test_storage", "pynetdicom/tests/test_presentation.py::TestServiceContexts::test_unified_procedure" ]
[ "pynetdicom/tests/test_presentation.py::TestPresentationContext::test_setter[good_init0]", "pynetdicom/tests/test_presentation.py::TestPresentationContext::test_setter[good_init1]", "pynetdicom/tests/test_presentation.py::TestPresentationContext::test_setter[good_init2]", "pynetdicom/tests/test_presentation.py::TestPresentationContext::test_setter[good_init3]", "pynetdicom/tests/test_presentation.py::TestPresentationContext::test_setter[good_init4]", "pynetdicom/tests/test_presentation.py::TestPresentationContext::test_setter[good_init5]", "pynetdicom/tests/test_presentation.py::TestPresentationContext::test_add_transfer_syntax", "pynetdicom/tests/test_presentation.py::TestPresentationContext::test_add_transfer_syntax_nonconformant", "pynetdicom/tests/test_presentation.py::TestPresentationContext::test_add_private_transfer_syntax", "pynetdicom/tests/test_presentation.py::TestPresentationContext::test_add_transfer_syntax_duplicate", "pynetdicom/tests/test_presentation.py::TestPresentationContext::test_equality", "pynetdicom/tests/test_presentation.py::TestPresentationContext::test_string_output", "pynetdicom/tests/test_presentation.py::TestPresentationContext::test_context_id", "pynetdicom/tests/test_presentation.py::TestPresentationContext::test_abstract_syntax", "pynetdicom/tests/test_presentation.py::TestPresentationContext::test_abstract_syntax_raises", "pynetdicom/tests/test_presentation.py::TestPresentationContext::test_abstract_syntax_nonconformant", "pynetdicom/tests/test_presentation.py::TestPresentationContext::test_transfer_syntax", "pynetdicom/tests/test_presentation.py::TestPresentationContext::test_transfer_syntax_duplicate", "pynetdicom/tests/test_presentation.py::TestPresentationContext::test_transfer_syntax_nonconformant", "pynetdicom/tests/test_presentation.py::TestPresentationContext::test_status", "pynetdicom/tests/test_presentation.py::TestPresentationContext::test_tuple", "pynetdicom/tests/test_presentation.py::TestPresentationContext::test_as_scp", "pynetdicom/tests/test_presentation.py::TestPresentationContext::test_as_scu", "pynetdicom/tests/test_presentation.py::TestPresentationContext::test_scu_role", "pynetdicom/tests/test_presentation.py::TestPresentationContext::test_scp_role", "pynetdicom/tests/test_presentation.py::TestPresentationContext::test_repr", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_scp_scu_role_negotiation[req0-acc0-out0]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_scp_scu_role_negotiation[req1-acc1-out1]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_scp_scu_role_negotiation[req2-acc2-out2]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_scp_scu_role_negotiation[req3-acc3-out3]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_scp_scu_role_negotiation[req4-acc4-out4]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_scp_scu_role_negotiation[req5-acc5-out5]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_scp_scu_role_negotiation[req6-acc6-out6]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_scp_scu_role_negotiation[req7-acc7-out7]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_scp_scu_role_negotiation[req8-acc8-out8]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_scp_scu_role_negotiation[req9-acc9-out9]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_scp_scu_role_negotiation[req10-acc10-out10]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_scp_scu_role_negotiation[req11-acc11-out11]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_scp_scu_role_negotiation[req12-acc12-out12]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_scp_scu_role_negotiation[req13-acc13-out13]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_scp_scu_role_negotiation[req14-acc14-out14]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_scp_scu_role_negotiation[req15-acc15-out15]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_scp_scu_role_negotiation[req16-acc16-out16]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_scp_scu_role_negotiation[req17-acc17-out17]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_scp_scu_role_negotiation[req18-acc18-out18]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_scp_scu_role_negotiation[req19-acc19-out19]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_scp_scu_role_negotiation[req20-acc20-out20]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_scp_scu_role_negotiation[req21-acc21-out21]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_scp_scu_role_negotiation[req22-acc22-out22]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_scp_scu_role_negotiation[req23-acc23-out23]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_scp_scu_role_negotiation[req24-acc24-out24]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_scp_scu_role_negotiation[req25-acc25-out25]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_scp_scu_role_negotiation[req26-acc26-out26]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_scp_scu_role_negotiation[req27-acc27-out27]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_scp_scu_role_negotiation[req28-acc28-out28]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_scp_scu_role_negotiation[req29-acc29-out29]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_scp_scu_role_negotiation[req30-acc30-out30]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_scp_scu_role_negotiation[req31-acc31-out31]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_scp_scu_role_negotiation[req32-acc32-out32]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_scp_scu_role_negotiation[req33-acc33-out33]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_scp_scu_role_negotiation[req34-acc34-out34]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_scp_scu_role_negotiation[req35-acc35-out35]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_scp_scu_role_negotiation[req36-acc36-out36]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_scp_scu_role_negotiation[req37-acc37-out37]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_scp_scu_role_negotiation[req38-acc38-out38]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_scp_scu_role_negotiation[req39-acc39-out39]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_scp_scu_role_negotiation[req40-acc40-out40]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_scp_scu_role_negotiation[req41-acc41-out41]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_scp_scu_role_negotiation[req42-acc42-out42]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_scp_scu_role_negotiation[req43-acc43-out43]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_scp_scu_role_negotiation[req44-acc44-out44]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_multiple_contexts_same_abstract", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_no_invalid_return_scp", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_no_invalid_return_scu", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_combination_role[req0-acc0-out0]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_combination_role[req1-acc1-out1]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_combination_role[req2-acc2-out2]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_combination_role[req3-acc3-out3]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_combination_role[req4-acc4-out4]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_combination_role[req5-acc5-out5]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_combination_role[req6-acc6-out6]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_combination_role[req7-acc7-out7]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_combination_role[req8-acc8-out8]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_combination_role[req9-acc9-out9]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_combination_role[req10-acc10-out10]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_combination_role[req11-acc11-out11]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_combination_role[req12-acc12-out12]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_combination_role[req13-acc13-out13]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_combination_role[req14-acc14-out14]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_combination_role[req15-acc15-out15]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_combination_role[req16-acc16-out16]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_combination_role[req17-acc17-out17]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_combination_role[req18-acc18-out18]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_combination_role[req19-acc19-out19]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_combination_role[req20-acc20-out20]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_combination_role[req21-acc21-out21]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_combination_role[req22-acc22-out22]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_combination_role[req23-acc23-out23]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_combination_role[req24-acc24-out24]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_combination_role[req25-acc25-out25]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_combination_role[req26-acc26-out26]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_combination_role[req27-acc27-out27]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_combination_role[req28-acc28-out28]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_combination_role[req29-acc29-out29]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_combination_role[req30-acc30-out30]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_combination_role[req31-acc31-out31]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_combination_role[req32-acc32-out32]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_combination_role[req33-acc33-out33]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_combination_role[req34-acc34-out34]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_combination_role[req35-acc35-out35]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_combination_role[req36-acc36-out36]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_combination_role[req37-acc37-out37]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_combination_role[req38-acc38-out38]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_combination_role[req39-acc39-out39]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_combination_role[req40-acc40-out40]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_combination_role[req41-acc41-out41]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_combination_role[req42-acc42-out42]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_combination_role[req43-acc43-out43]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsAcceptorWithRoleSelection::test_combination_role[req44-acc44-out44]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_scp_scu_role_negotiation[req0-acc0-out0]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_scp_scu_role_negotiation[req1-acc1-out1]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_scp_scu_role_negotiation[req2-acc2-out2]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_scp_scu_role_negotiation[req3-acc3-out3]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_scp_scu_role_negotiation[req4-acc4-out4]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_scp_scu_role_negotiation[req5-acc5-out5]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_scp_scu_role_negotiation[req6-acc6-out6]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_scp_scu_role_negotiation[req7-acc7-out7]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_scp_scu_role_negotiation[req8-acc8-out8]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_scp_scu_role_negotiation[req9-acc9-out9]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_scp_scu_role_negotiation[req10-acc10-out10]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_scp_scu_role_negotiation[req11-acc11-out11]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_scp_scu_role_negotiation[req12-acc12-out12]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_scp_scu_role_negotiation[req13-acc13-out13]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_scp_scu_role_negotiation[req14-acc14-out14]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_scp_scu_role_negotiation[req15-acc15-out15]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_scp_scu_role_negotiation[req16-acc16-out16]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_scp_scu_role_negotiation[req17-acc17-out17]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_scp_scu_role_negotiation[req18-acc18-out18]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_scp_scu_role_negotiation[req19-acc19-out19]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_scp_scu_role_negotiation[req20-acc20-out20]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_scp_scu_role_negotiation[req21-acc21-out21]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_scp_scu_role_negotiation[req22-acc22-out22]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_scp_scu_role_negotiation[req23-acc23-out23]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_scp_scu_role_negotiation[req24-acc24-out24]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_scp_scu_role_negotiation[req25-acc25-out25]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_scp_scu_role_negotiation[req26-acc26-out26]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_scp_scu_role_negotiation[req27-acc27-out27]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_scp_scu_role_negotiation[req28-acc28-out28]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_scp_scu_role_negotiation[req29-acc29-out29]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_scp_scu_role_negotiation[req30-acc30-out30]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_scp_scu_role_negotiation[req31-acc31-out31]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_scp_scu_role_negotiation[req32-acc32-out32]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_scp_scu_role_negotiation[req33-acc33-out33]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_scp_scu_role_negotiation[req34-acc34-out34]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_scp_scu_role_negotiation[req35-acc35-out35]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_scp_scu_role_negotiation[req36-acc36-out36]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_scp_scu_role_negotiation[req37-acc37-out37]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_scp_scu_role_negotiation[req38-acc38-out38]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_scp_scu_role_negotiation[req39-acc39-out39]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_scp_scu_role_negotiation[req40-acc40-out40]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_scp_scu_role_negotiation[req41-acc41-out41]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_scp_scu_role_negotiation[req42-acc42-out42]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_scp_scu_role_negotiation[req43-acc43-out43]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_scp_scu_role_negotiation[req44-acc44-out44]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_multiple_contexts_same_abstract", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_functional", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_acc_invalid_return_scp", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_acc_invalid_return_scu", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_combination[req0-acc0-out0]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_combination[req1-acc1-out1]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_combination[req2-acc2-out2]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_combination[req3-acc3-out3]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_combination[req4-acc4-out4]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_combination[req5-acc5-out5]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_combination[req6-acc6-out6]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_combination[req7-acc7-out7]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_combination[req8-acc8-out8]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_combination[req9-acc9-out9]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_combination[req10-acc10-out10]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_combination[req11-acc11-out11]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_combination[req12-acc12-out12]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_combination[req13-acc13-out13]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_combination[req14-acc14-out14]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_combination[req15-acc15-out15]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_combination[req16-acc16-out16]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_combination[req17-acc17-out17]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_combination[req18-acc18-out18]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_combination[req19-acc19-out19]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_combination[req20-acc20-out20]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_combination[req21-acc21-out21]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_combination[req22-acc22-out22]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_combination[req23-acc23-out23]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_combination[req24-acc24-out24]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_combination[req25-acc25-out25]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_combination[req26-acc26-out26]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_combination[req27-acc27-out27]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_combination[req28-acc28-out28]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_combination[req29-acc29-out29]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_combination[req30-acc30-out30]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_combination[req31-acc31-out31]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_combination[req32-acc32-out32]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_combination[req33-acc33-out33]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_combination[req34-acc34-out34]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_combination[req35-acc35-out35]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_combination[req36-acc36-out36]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_combination[req37-acc37-out37]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_combination[req38-acc38-out38]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_combination[req39-acc39-out39]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_combination[req40-acc40-out40]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_combination[req41-acc41-out41]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_combination[req42-acc42-out42]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_combination[req43-acc43-out43]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_combination[req44-acc44-out44]", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_one_role_only_scu", "pynetdicom/tests/test_presentation.py::TestNegotiateAsRequestorWithRoleSelection::test_one_role_only_scp", "pynetdicom/tests/test_presentation.py::test_default_transfer_syntaxes", "pynetdicom/tests/test_presentation.py::test_build_context", "pynetdicom/tests/test_presentation.py::TestServiceContexts::test_application_event", "pynetdicom/tests/test_presentation.py::TestServiceContexts::test_basic_worklist", "pynetdicom/tests/test_presentation.py::TestServiceContexts::test_color_palette", "pynetdicom/tests/test_presentation.py::TestServiceContexts::test_defined_procedure", "pynetdicom/tests/test_presentation.py::TestServiceContexts::test_display_system", "pynetdicom/tests/test_presentation.py::TestServiceContexts::test_hanging_protocol", "pynetdicom/tests/test_presentation.py::TestServiceContexts::test_implant_template", "pynetdicom/tests/test_presentation.py::TestServiceContexts::test_instance_availability", "pynetdicom/tests/test_presentation.py::TestServiceContexts::test_media_creation", "pynetdicom/tests/test_presentation.py::TestServiceContexts::test_media_storage", "pynetdicom/tests/test_presentation.py::TestServiceContexts::test_non_patient", "pynetdicom/tests/test_presentation.py::TestServiceContexts::test_print_management", "pynetdicom/tests/test_presentation.py::TestServiceContexts::test_procedure_step", "pynetdicom/tests/test_presentation.py::TestServiceContexts::test_protocol_approval", "pynetdicom/tests/test_presentation.py::TestServiceContexts::test_qr", "pynetdicom/tests/test_presentation.py::TestServiceContexts::test_relevant_patient", "pynetdicom/tests/test_presentation.py::TestServiceContexts::test_rt_machine", "pynetdicom/tests/test_presentation.py::TestServiceContexts::test_storage_commitement", "pynetdicom/tests/test_presentation.py::TestServiceContexts::test_substance_admin", "pynetdicom/tests/test_presentation.py::TestServiceContexts::test_verification", "pynetdicom/tests/test_presentation.py::TestBuildRole::test_default", "pynetdicom/tests/test_presentation.py::TestBuildRole::test_various" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-01-01 03:01:28+00:00
mit
4,933
pydicom__pynetdicom-464
diff --git a/docs/changelog/v1.5.0.rst b/docs/changelog/v1.5.0.rst index e2b19920d..de9d57f1d 100644 --- a/docs/changelog/v1.5.0.rst +++ b/docs/changelog/v1.5.0.rst @@ -23,6 +23,7 @@ Fixes * Fixed the association acceptor selecting the first matching proposed transfer syntax rather than the first matching supported transfer syntax during presentation context negotiation (:issue:`445`) +* Fixed incorrect Pending status value for Modality Worklist (:issue:`462`) Enhancements @@ -54,9 +55,14 @@ Enhancements * Added ability to pass optional extra arguments to event handlers by using ``(evt.EVT_NAME, handler, ['list', 'of', 'args'])``. (:issue:`447`) * Added :meth:`~pynetdicom.ae.AE.make_server` (:issue:`453`). -* Added `request_handler` keyword parameter to :class:`~pynetdicom.transport.AssociationServer` (:issue:`453`) +* Added `request_handler` keyword parameter to + :class:`~pynetdicom.transport.AssociationServer` (:issue:`453`) * Added hook in :class:`~pynetdicom.ae.AE` for creating :class:`~pynetdicom.transport.AssociationSocket` objects (:issue:`455`) +* Python 3 only: Added a customisable :class:`~pynetdicom.status.Status` + convenience class for comparing, returning and yielding status values + (:issue:`454`) + Changes ....... diff --git a/docs/reference/status.rst b/docs/reference/status.rst index 04b76182e..0bbc41d7a 100644 --- a/docs/reference/status.rst +++ b/docs/reference/status.rst @@ -72,3 +72,4 @@ codes are used internally within pynetdicom to help aid in debugging. code_to_category code_to_status + Status diff --git a/docs/user/association.rst b/docs/user/association.rst index 6873f681f..3b67cac9c 100644 --- a/docs/user/association.rst +++ b/docs/user/association.rst @@ -87,28 +87,25 @@ also acting as a Storage SCP), plus a *User Identity Negotiation* item: :: - from pynetdicom import ( - AE, - StoragePresentationContexts, - QueryRetrievePresentationContexts, - build_role - ) + from pynetdicom import AE, StoragePresentationContexts, build_role from pynetdicom.pdu_primitives import UserIdentityNegotiation + from pynetdicom.sop_class import PatientRootQueryRetrieveInformationModelGet ae = AE() - # Contexts proposed as a QR SCU - ae.requested_contexts = QueryRetrievePresentationContexts # Contexts supported as a Storage SCP - requires Role Selection - ae.requested_contexts = StoragePresentationContexts + # Note that we are limited to a maximum of 128 contexts so we + # only include 127 to make room for the QR Get context + ae.requested_contexts = StoragePresentationContexts[:127] + # Contexts proposed as a QR SCU + ae.add_requested_context = PatientRootQueryRetrieveInformationModelGet - # Add role selection items for the storage contexts we will be supporting - # as an SCP + # Add role selection items for the contexts we will be supporting as an SCP negotiation_items = [] - for context in StoragePresentationContexts: + for context in StoragePresentationContexts[:127]: role = build_role(context.abstract_syntax, scp_role=True) negotiation_items.append(role) - # Add user identity negotiation request + # Add user identity negotiation request - passwords are sent in the clear! user_identity = UserIdentityNegotiation() user_identity.user_identity_type = 2 user_identity.primary_field = b'username' diff --git a/pynetdicom/status.py b/pynetdicom/status.py index 74552e2e6..1147737e7 100644 --- a/pynetdicom/status.py +++ b/pynetdicom/status.py @@ -1,5 +1,11 @@ """Implementation of the DIMSE Status values.""" +try: + from enum import IntEnum + HAS_ENUM = True +except ImportError: + HAS_ENUM = False + from pydicom.dataset import Dataset from pynetdicom._globals import ( @@ -180,7 +186,7 @@ MODALITY_WORKLIST_SERVICE_CLASS_STATUS = { "Matches are continuing - current match is supplied and any " "Optional Keys were supported in the same manner as Required " "Keys"), - 0xFE00 : (STATUS_PENDING, + 0xFF01 : (STATUS_PENDING, "Matches are continuing - warning that one or more Optional " "Keys were not supported for existence for this Identifier"), } @@ -469,3 +475,59 @@ def code_to_category(code): return STATUS_UNKNOWN else: raise ValueError("'code' must be a positive integer.") + + +if HAS_ENUM: + class Status(IntEnum): + """Constants for common status codes. + + .. versionadded:: 1.5 + .. warning:: + + Only available with Python 3 + + New constants can be added with the ``Status.add(name, code)`` method but + the documentation for it is missing due to a bug in Sphinx. `name` is + the variable name of the constant to add as a :class:`str` and `code` is + the corresponding status code as an :class:`int`. + + Examples + -------- + + :: + + from pynetdicom.status import Status + + # Customise the class + Status.add('UNABLE_TO_PROCESS', 0xC000) + + def handle_store(event): + try: + event.dataset.save_as('temp.dcm') + except: + return Status.UNABLE_TO_PROCESS + + return Status.SUCCESS + + """ + SUCCESS = 0x0000 + """``0x0000`` - Success""" + CANCEL = 0xFE00 + """``0xFE00`` - Operation terminated""" + PENDING = 0xFF00 + """``0xFF00`` - Matches or sub-operations are continuing""" + MOVE_DESTINATION_UNKNOWN = 0xA801 + """``0xA801`` - Move destination unknown""" + + @classmethod + def add(cls, name, code): + """Add a new constant to `Status`. + + Parameters + ---------- + name : str + The name of the constant to add. + code : int + The status code corresponding to the name. + """ + setattr(cls, name, code) diff --git a/requirements.txt b/requirements.txt index 79e1efb59..c0961707b 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,1 +1,1 @@ -pydicom>=1.2.1 +pydicom>=1.4.2 diff --git a/setup.py b/setup.py index 808081c88..4c1abb0cc 100644 --- a/setup.py +++ b/setup.py @@ -47,5 +47,5 @@ setup( "Topic :: Scientific/Engineering :: Medical Science Apps.", "Topic :: Software Development :: Libraries", ], - install_requires = ["pydicom>=1.4.0"], + install_requires = ["pydicom>=1.4.2"], )
pydicom/pynetdicom
66d92b0a0c9b8ab7cbdcc3e6dcbf25a88c1e2dbf
diff --git a/pynetdicom/tests/test_service_storage.py b/pynetdicom/tests/test_service_storage.py index 95e0aad2c..ec9d68100 100644 --- a/pynetdicom/tests/test_service_storage.py +++ b/pynetdicom/tests/test_service_storage.py @@ -17,6 +17,11 @@ from pynetdicom.service_class import StorageServiceClass from pynetdicom.sop_class import ( VerificationSOPClass, CTImageStorage, RTImageStorage, ) +try: + from pynetdicom.status import Status + HAS_STATUS = True +except ImportError: + HAS_STATUS = False #debug_logger() @@ -37,10 +42,60 @@ class TestStorageServiceClass(object): if self.ae: self.ae.shutdown() + @pytest.mark.skipif(not HAS_STATUS, reason="No Status class available") + def test_status_enum(self): + """Test failure to decode the dataset""" + # Hard to test directly as decode errors won't show up until the + # dataset is actually used + Status.add('UNABLE_TO_DECODE', 0xC210) + + def handle(event): + try: + for elem in event.dataset.iterall(): + pass + except: + status = Dataset() + status.Status = Status.UNABLE_TO_DECODE + status.ErrorComment = "Unable to decode the dataset" + return status + + return Status.SUCCESS + + handlers = [(evt.EVT_C_STORE, handle)] + + self.ae = ae = AE() + ae.add_supported_context(CTImageStorage) + ae.add_requested_context(CTImageStorage, ExplicitVRLittleEndian) + scp = ae.start_server(('', 11112), block=False, evt_handlers=handlers) + + assoc = ae.associate('localhost', 11112) + assert assoc.is_established + + req = C_STORE() + req.MessageID = 1 + req.AffectedSOPClassUID = DATASET.SOPClassUID + req.AffectedSOPInstanceUID = DATASET.SOPInstanceUID + req.Priorty = 0x0002 + req.DataSet = BytesIO(b'\x08\x00\x01\x00\x40\x40\x00\x00\x00\x00\x00\x08\x00\x49') + + # Send C-STORE request to DIMSE and get response + assoc._reactor_checkpoint.clear() + assoc.dimse.send_msg(req, 1) + cx_id, rsp = assoc.dimse.get_msg(True) + assoc._reactor_checkpoint.set() + + assert rsp.Status == 0xC210 + assert rsp.ErrorComment == 'Unable to decode the dataset' + assoc.release() + assert assoc.is_released + + scp.shutdown() + def test_scp_failed_ds_decode(self): """Test failure to decode the dataset""" # Hard to test directly as decode errors won't show up until the # dataset is actually used + def handle(event): try: for elem in event.dataset.iterall(): diff --git a/pynetdicom/tests/test_status.py b/pynetdicom/tests/test_status.py index f00e93d47..650b8073e 100644 --- a/pynetdicom/tests/test_status.py +++ b/pynetdicom/tests/test_status.py @@ -8,6 +8,11 @@ import pytest from pydicom.dataset import Dataset from pynetdicom.status import code_to_category, code_to_status +try: + from pynetdicom.status import Status + HAS_STATUS = True +except ImportError: + HAS_STATUS = False LOGGER = logging.getLogger('pynetdicom') @@ -255,3 +260,24 @@ class TestStatus(object): assert c2c(0x0000) == 'Success' for code in [0xA700, 0xA900, 0xC000]: assert c2c(code) == 'Failure' + + [email protected](not HAS_STATUS, reason="No Status class available") +class TestStatusEnum(object): + """Tests for the Status enum class.""" + def test_default(self): + """Test the default class.""" + assert 0x0000 == Status.SUCCESS + assert 0xFE00 == Status.CANCEL + assert 0xFF00 == Status.PENDING + + def test_adding(self): + """Tests for adding a new constant to the Status enum.""" + with pytest.raises(AttributeError, match=r'PENDING_WITH_WARNING'): + Status.PENDING_WITH_WARNING + + Status.add('PENDING_WITH_WARNING', 0xFF01) + assert 0xFF01 == Status.PENDING_WITH_WARNING + assert 0x0000 == Status.SUCCESS + assert 0xFE00 == Status.CANCEL + assert 0xFF00 == Status.PENDING
Add constants for status values **Is your feature request related to a problem? Please describe.** It would be convenient to have constants for the various status values. **Describe the solution you'd like** Ideally, there would be an `IntEnum` with the valid service statuses. I imagine it'd look similar to the `http.HTTPStatus` from the stdlib. ```python >>> from pynetdicom.status import Status >>> Status.FAILURE >>> <Status.FAILURE: 0xA700> ``` **Describe alternatives you've considered** You could also use an enum of tuples or sets, so you could have e.g. ```python >>> from pynetdicom.status import Status >>> assert Status.PENDING == {0xFF00, 0xFF01} ``` But this isn't clearly better and is less flexible. **Additional context** Might want to add this after Python 2 is dropped so you don't have to conditionally install an `enum` backport.
0.0
66d92b0a0c9b8ab7cbdcc3e6dcbf25a88c1e2dbf
[ "pynetdicom/tests/test_service_storage.py::TestStorageServiceClass::test_status_enum", "pynetdicom/tests/test_status.py::TestStatusEnum::test_default", "pynetdicom/tests/test_status.py::TestStatusEnum::test_adding" ]
[ "pynetdicom/tests/test_service_storage.py::TestStorageServiceClass::test_scp_failed_ds_decode", "pynetdicom/tests/test_service_storage.py::TestStorageServiceClass::test_scp_handler_return_dataset", "pynetdicom/tests/test_service_storage.py::TestStorageServiceClass::test_scp_handler_return_dataset_multi", "pynetdicom/tests/test_service_storage.py::TestStorageServiceClass::test_scp_handler_return_int", "pynetdicom/tests/test_service_storage.py::TestStorageServiceClass::test_scp_handler_return_invalid", "pynetdicom/tests/test_service_storage.py::TestStorageServiceClass::test_scp_handler_no_status", "pynetdicom/tests/test_service_storage.py::TestStorageServiceClass::test_scp_handler_exception_default", "pynetdicom/tests/test_service_storage.py::TestStorageServiceClass::test_scp_handler_exception", "pynetdicom/tests/test_service_storage.py::TestStorageServiceClass::test_scp_handler_context", "pynetdicom/tests/test_service_storage.py::TestStorageServiceClass::test_scp_handler_assoc", "pynetdicom/tests/test_service_storage.py::TestStorageServiceClass::test_scp_handler_request", "pynetdicom/tests/test_service_storage.py::TestStorageServiceClass::test_scp_handler_dataset", "pynetdicom/tests/test_service_storage.py::TestStorageServiceClass::test_scp_handler_move_origin", "pynetdicom/tests/test_service_storage.py::TestStorageServiceClass::test_scp_handler_sop_extended", "pynetdicom/tests/test_service_storage.py::TestStorageServiceClass::test_event_ds_modify", "pynetdicom/tests/test_service_storage.py::TestStorageServiceClass::test_event_ds_change", "pynetdicom/tests/test_service_storage.py::TestStorageServiceClass::test_event_file_meta", "pynetdicom/tests/test_service_storage.py::TestStorageServiceClass::test_event_file_meta_bad", "pynetdicom/tests/test_service_storage.py::TestStorageServiceClass::test_scp_handler_aborts", "pynetdicom/tests/test_status.py::TestStatus::test_code_to_status", "pynetdicom/tests/test_status.py::TestStatus::test_code_to_category_unknown", "pynetdicom/tests/test_status.py::TestStatus::test_code_to_category_general", "pynetdicom/tests/test_status.py::TestStatus::test_code_to_category_negative_raises", "pynetdicom/tests/test_status.py::TestStatus::test_code_to_category_storage", "pynetdicom/tests/test_status.py::TestStatus::test_code_to_category_qr_find", "pynetdicom/tests/test_status.py::TestStatus::test_code_to_category_qr_move", "pynetdicom/tests/test_status.py::TestStatus::test_code_to_category_qr_get", "pynetdicom/tests/test_status.py::TestStatus::test_code_to_category_proc_step", "pynetdicom/tests/test_status.py::TestStatus::test_code_to_category_print_management", "pynetdicom/tests/test_status.py::TestStatus::test_code_to_category_basic_worklist", "pynetdicom/tests/test_status.py::TestStatus::test_code_to_category_application_event", "pynetdicom/tests/test_status.py::TestStatus::test_code_to_category_relevant_patient", "pynetdicom/tests/test_status.py::TestStatus::test_code_to_category_media_creation", "pynetdicom/tests/test_status.py::TestStatus::test_code_to_category_substance_admin", "pynetdicom/tests/test_status.py::TestStatus::test_code_to_category_instance_frame", "pynetdicom/tests/test_status.py::TestStatus::test_code_to_category_composite_instance", "pynetdicom/tests/test_status.py::TestStatus::test_code_to_category_unified_procedure", "pynetdicom/tests/test_status.py::TestStatus::test_code_to_category_rt_machine", "pynetdicom/tests/test_status.py::TestStatus::test_code_to_category_non_patient" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2020-03-06 23:13:48+00:00
mit
4,934