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-1253
diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -546,6 +546,8 @@ def validate(cls: Type['Model'], value: Any) -> 'Model': return value.copy() elif cls.__config__.orm_mode: return cls.from_orm(value) + elif cls.__custom_root_type__: + return cls.parse_obj(value) else: try: value_as_dict = dict(value)
pydantic/pydantic
938335c46f7e31da71e5c2a45eb3cf1ad51030b5
I suspect this is because internally `parse_obj_as` creates a model with `__root__` set to its first argument, so effectively you're doing ```py from pydantic import BaseModel class OperationData(BaseModel): id: str class Operation(BaseModel): __root__: Tuple[int, OperationData] class ParseAsObjectModel(BaseModel): __root__: Operation ``` which then fails, should be fixable via either or both: 1. getting the above to work, even though it looks weird 2. `parse_as_obj` detecting a model (perhaps a model with a custom root type) as it's first argument and using that model instead of creating another one. It occurs to me that 1. might not be possible (or possible without complex or backwards incompatible changes) due to the way we handle custom root types. The second option therefore might be easier. For what it's worth, the following change seems to make the error go away: Change: https://github.com/samuelcolvin/pydantic/blob/e4cd9d2c87b0e6f42366b617de6441f8cd561085/pydantic/main.py#L549-L554 to ```python else: if cls.__custom_root_type__: value_as_dict = {"__root__": value} else: try: value_as_dict = dict(value) except (TypeError, ValueError) as e: raise DictError() from e return cls(**value_as_dict) ``` I don't necessarily think this is the optimal fix, but it might be useful as a starting point.
diff --git a/tests/test_parse.py b/tests/test_parse.py --- a/tests/test_parse.py +++ b/tests/test_parse.py @@ -1,10 +1,10 @@ import json import pickle -from typing import List, Union +from typing import List, Tuple, Union import pytest -from pydantic import BaseModel, Field, Protocol, ValidationError +from pydantic import BaseModel, Field, Protocol, ValidationError, parse_obj_as class Model(BaseModel): @@ -57,6 +57,55 @@ class MyModel(BaseModel): assert m.__root__ == ['a'] +def test_parse_nested_root_list(): + class NestedData(BaseModel): + id: str + + class NestedModel(BaseModel): + __root__: List[NestedData] + + class MyModel(BaseModel): + nested: NestedModel + + m = MyModel.parse_obj({'nested': [{'id': 'foo'}]}) + assert isinstance(m.nested, NestedModel) + assert isinstance(m.nested.__root__[0], NestedData) + + +def test_parse_nested_root_tuple(): + class NestedData(BaseModel): + id: str + + class NestedModel(BaseModel): + __root__: Tuple[int, NestedData] + + class MyModel(BaseModel): + nested: List[NestedModel] + + data = [0, {'id': 'foo'}] + m = MyModel.parse_obj({'nested': [data]}) + assert isinstance(m.nested[0], NestedModel) + assert isinstance(m.nested[0].__root__[1], NestedData) + + nested = parse_obj_as(NestedModel, data) + assert isinstance(nested, NestedModel) + + +def test_parse_nested_custom_root(): + class NestedModel(BaseModel): + __root__: List[str] + + class MyModel(BaseModel): + __root__: NestedModel + + nested = ['foo', 'bar'] + m = MyModel.parse_obj(nested) + assert isinstance(m, MyModel) + assert isinstance(m.__root__, NestedModel) + assert isinstance(m.__root__.__root__, List) + assert isinstance(m.__root__.__root__[0], str) + + def test_json(): assert Model.parse_raw('{"a": 12, "b": 8}') == Model(a=12, b=8)
Broken loading list of tuples. # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.4 pydantic compiled: True install path: /home/**removed**/venv/lib/python3.7/site-packages/pydantic python version: 3.7.3 (default, Apr 3 2019, 19:16:38) [GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] platform: Linux-4.19.86-041986-generic-x86_64-with-Ubuntu-18.04-bionic optional deps. installed: [] ``` There is pretty strange behaviour on loading nested list of tuples. I firstly think that this might be intended, but then found out that parse_obj and parse_obj_as give different execution flow which frustrates me. ```py from pydantic import BaseModel class OperationData(BaseModel): id: str class Operation(BaseModel): __root__: Tuple[int, OperationData] data = [0, {'id': '1.11.0'}] # this one works as expected print(Operation.parse_obj(data)) # printed: __root__=(0, OperationData(id='1.11.0')) # However, this one doesn't print(parse_obj_as(Operation, data)) # Traceback (most recent call last): # File "/home/**removed**/protocol/base.py", line 238, in <module> # print(parse_obj_as(Operation, data)) # File "pydantic/tools.py", line 35, in pydantic.tools.parse_obj_as # File "pydantic/main.py", line 283, in pydantic.main.BaseModel.__init__ # pydantic.error_wrappers.ValidationError: 1 validation error for ParsingModel[Operation] #__root__ # value is not a valid dict (type=type_error.dict) # Which is not a big problem. The problem is that I have nested class class OperationsBatch(BaseModel): batch_desc: str operations: List[Operation] # and it produces same exception on print(OperationsBatch.parse_obj({'batch_desc': '123', 'operations': [data, data]})) # Traceback (most recent call last): # File "/home/**removed**/protocol/base.py", line 243, in <module> # OperationsBatch.parse_obj({'batch_desc': '123', 'operations': [data, data]}) # File "pydantic/main.py", line 402, in pydantic.main.BaseModel.parse_obj # File "pydantic/main.py", line 283, in pydantic.main.BaseModel.__init__ # pydantic.error_wrappers.ValidationError: 2 validation errors for OperationsBatch # operations -> 0 # value is not a valid dict (type=type_error.dict) # operations -> 1 # value is not a valid dict (type=type_error.dict) ``` It doesn't look like a right behaviour.
0.0
938335c46f7e31da71e5c2a45eb3cf1ad51030b5
[ "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_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_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_test_patch": true, "is_lite": true }
2020-02-25 03:44:43+00:00
mit
4,735
pydantic__pydantic-1291
diff --git a/docs/examples/exporting_models_json.py b/docs/examples/exporting_models_json.py --- a/docs/examples/exporting_models_json.py +++ b/docs/examples/exporting_models_json.py @@ -1,6 +1,5 @@ -from datetime import datetime, timedelta +from datetime import datetime from pydantic import BaseModel -from pydantic.json import timedelta_isoformat class BarModel(BaseModel): whatever: int @@ -11,16 +10,3 @@ class FooBarModel(BaseModel): m = FooBarModel(foo=datetime(2032, 6, 1, 12, 13, 14), bar={'whatever': 123}) print(m.json()) -# (returns a str) -class WithCustomEncoders(BaseModel): - dt: datetime - diff: timedelta - - class Config: - json_encoders = { - datetime: lambda v: v.timestamp(), - timedelta: timedelta_isoformat, - } - -m = WithCustomEncoders(dt=datetime(2032, 6, 1), diff=timedelta(hours=100)) -print(m.json()) diff --git a/docs/examples/exporting_models_json_encoders.py b/docs/examples/exporting_models_json_encoders.py new file mode 100644 --- /dev/null +++ b/docs/examples/exporting_models_json_encoders.py @@ -0,0 +1,16 @@ +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, + } + +m = WithCustomEncoders(dt=datetime(2032, 6, 1), diff=timedelta(hours=100)) +print(m.json()) diff --git a/docs/examples/exporting_models_json_subclass.py b/docs/examples/exporting_models_json_subclass.py new file mode 100644 --- /dev/null +++ b/docs/examples/exporting_models_json_subclass.py @@ -0,0 +1,23 @@ +from datetime import date, timedelta +from pydantic import BaseModel +from pydantic.validators import int_validator + +class DayThisYear(date): + """ + Contrived example of a special type of date that + takes an int and interprets it as a day in the current year + """ + @classmethod + def __get_validators__(cls): + yield int_validator + yield cls.validate + + @classmethod + def validate(cls, v: int): + return date.today().replace(month=1, day=1) + timedelta(days=v) + +class FooModel(BaseModel): + date: DayThisYear + +m = FooModel(date=300) +print(m.json()) diff --git a/pydantic/json.py b/pydantic/json.py --- a/pydantic/json.py +++ b/pydantic/json.py @@ -18,25 +18,27 @@ def isoformat(o: Union[datetime.date, datetime.time]) -> str: ENCODERS_BY_TYPE: Dict[Type[Any], Callable[[Any], Any]] = { + bytes: lambda o: o.decode(), Color: str, + datetime.date: isoformat, + datetime.datetime: isoformat, + datetime.time: isoformat, + datetime.timedelta: lambda td: td.total_seconds(), + Decimal: float, + Enum: lambda o: o.value, + frozenset: list, + GeneratorType: list, IPv4Address: str, - IPv6Address: str, IPv4Interface: str, - IPv6Interface: str, IPv4Network: str, + IPv6Address: str, + IPv6Interface: str, IPv6Network: str, - SecretStr: str, + Path: str, SecretBytes: str, - UUID: str, - datetime.datetime: isoformat, - datetime.date: isoformat, - datetime.time: isoformat, - datetime.timedelta: lambda td: td.total_seconds(), + SecretStr: str, set: list, - frozenset: list, - GeneratorType: list, - bytes: lambda o: o.decode(), - Decimal: float, + UUID: str, } @@ -46,26 +48,29 @@ def pydantic_encoder(obj: Any) -> Any: if isinstance(obj, BaseModel): return obj.dict() - elif isinstance(obj, Enum): - return obj.value - elif isinstance(obj, Path): - return str(obj) elif is_dataclass(obj): return asdict(obj) - try: - encoder = ENCODERS_BY_TYPE[obj.__class__] - except KeyError: - raise TypeError(f"Object of type '{obj.__class__.__name__}' is not JSON serializable") - else: + # Check the class type and its superclasses for a matching encoder + for base in obj.__class__.__mro__[:-1]: + try: + encoder = ENCODERS_BY_TYPE[base] + except KeyError: + continue return encoder(obj) + else: # We have exited the for loop without finding a suitable encoder + raise TypeError(f"Object of type '{obj.__class__.__name__}' is not JSON serializable") def custom_pydantic_encoder(type_encoders: Dict[Any, Callable[[Type[Any]], Any]], obj: Any) -> Any: - encoder = type_encoders.get(obj.__class__) - if encoder: + # Check the class type and its superclasses for a matching encoder + for base in obj.__class__.__mro__[:-1]: + try: + encoder = type_encoders[base] + except KeyError: + continue return encoder(obj) - else: + else: # We have exited the for loop without finding a suitable encoder return pydantic_encoder(obj)
pydantic/pydantic
5a705a202fd6d10f895145bb625e4c8c9a54e4e3
diff --git a/tests/test_json.py b/tests/test_json.py --- a/tests/test_json.py +++ b/tests/test_json.py @@ -91,6 +91,41 @@ class Model(BaseModel): assert m.json(exclude={'b'}) == '{"a": 10.2, "c": 10.2, "d": {"x": 123, "y": "123"}}' +def test_subclass_encoding(): + class SubDate(datetime.datetime): + pass + + class Model(BaseModel): + a: datetime.datetime + b: SubDate + + m = Model(a=datetime.datetime(2032, 1, 1, 1, 1), b=SubDate(2020, 2, 29, 12, 30)) + assert m.dict() == {'a': datetime.datetime(2032, 1, 1, 1, 1), 'b': SubDate(2020, 2, 29, 12, 30)} + assert m.json() == '{"a": "2032-01-01T01:01:00", "b": "2020-02-29T12:30:00"}' + + +def test_subclass_custom_encoding(): + class SubDate(datetime.datetime): + pass + + class SubDelta(datetime.timedelta): + pass + + class Model(BaseModel): + a: SubDate + b: SubDelta + + class Config: + json_encoders = { + datetime.datetime: lambda v: v.strftime('%a, %d %b %C %H:%M:%S'), + datetime.timedelta: timedelta_isoformat, + } + + m = Model(a=SubDate(2032, 1, 1, 1, 1), b=SubDelta(hours=100)) + assert m.dict() == {'a': SubDate(2032, 1, 1, 1, 1), 'b': SubDelta(days=4, seconds=14400)} + assert m.json() == '{"a": "Thu, 01 Jan 20 01:01:00", "b": "P4DT4H0M0.000000S"}' + + def test_invalid_model(): class Foo: pass
Subclasses of known types are not JSON serializable # Feature Request/(Bug?) Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.4 pydantic compiled: False install path: /Users/step7212/.pyenv/versions/3.8.1/envs/fastdate/lib/python3.8/site-packages/pydantic python version: 3.8.1 (default, Jan 10 2020, 09:36:37) [Clang 11.0.0 (clang-1100.0.33.16)] platform: macOS-10.14.6-x86_64-i386-64bit optional deps. installed: [] ``` I would like to use a package that subclasses a standard python library class, adding convenience features but maintaining the interface of it's inheritance. Currently, pydantic will error when attempting to serialize the subclass, as it is not known in `ENCODERS_BY_TYPE`: https://github.com/samuelcolvin/pydantic/blob/e3243d267b06bda2d7b2213a8bad70f82171033c/pydantic/json.py#L20-L40 Example: ```py >>> import pendulum >>> import pydantic >>> class MyModel(pydantic.BaseModel): ... date_field: pendulum.DateTime ... >>> m = MyModel(date_field=pendulum.now('UTC')) >>> m MyModel(date_field=DateTime(2020, 3, 2, 16, 44, 42, 977836, tzinfo=Timezone('UTC'))) >>> m.dict() {'date_field': DateTime(2020, 3, 2, 16, 44, 42, 977836, tzinfo=Timezone('UTC'))} >>> m.json() Traceback (most recent call last): File "/Users/step7212/git/hub/pydantic/pydantic/json.py", line 57, in pydantic_encoder encoder = ENCODERS_BY_TYPE[type(obj)] KeyError: <class 'pendulum.datetime.DateTime'> During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/step7212/git/hub/pydantic/pydantic/main.py", line 419, in json return self.__config__.json_dumps(data, default=encoder, **dumps_kwargs) File "/Users/step7212/.pyenv/versions/3.8.1/lib/python3.8/json/__init__.py", line 234, in dumps return cls( File "/Users/step7212/.pyenv/versions/3.8.1/lib/python3.8/json/encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "/Users/step7212/.pyenv/versions/3.8.1/lib/python3.8/json/encoder.py", line 257, in iterencode return _iterencode(o, 0) File "/Users/step7212/git/hub/pydantic/pydantic/json.py", line 59, in pydantic_encoder raise TypeError(f"Object of type '{obj.__class__.__name__}' is not JSON serializable") TypeError: Object of type 'DateTime' is not JSON serializable ``` Since all pendulum types are children of the std `datetime` types, they should be serializable in the same way: ```py >>> import pendulum >>> import pydantic >>> >>> class MyModel(pydantic.BaseModel): ... date_field: pendulum.DateTime ... >>> m = MyModel(date_field=pendulum.now('UTC')) >>> m MyModel(date_field=DateTime(2020, 3, 2, 16, 42, 22, 403965, tzinfo=Timezone('UTC'))) >>> m.dict() {'date_field': DateTime(2020, 3, 2, 16, 42, 22, 403965, tzinfo=Timezone('UTC'))} >>> m.json() '{"date_field": "2020-03-02T16:42:22.403965+00:00"}' ``` This is doable by iterating over the [method resolution order](https://docs.python.org/3/library/stdtypes.html#class.__mro__) attribute, and I've created a branch to demonstrate, which was used for the desired output above: https://github.com/samuelcolvin/pydantic/compare/master...StephenBrown2:encode_known_subclasses <details> <summary>Benchmarks for funsies, this actually turns out to be a little faster than before:</summary> ``` ❯ git checkout master Switched to branch 'master' Your branch is up to date with 'origin/master'. ❯ make benchmark-pydantic python benchmarks/run.py pydantic-only generating test cases... pydantic time=1.043s, success=50.10% pydantic time=0.982s, success=50.10% pydantic time=0.788s, success=50.10% pydantic time=0.732s, success=50.10% pydantic time=0.741s, success=50.10% pydantic best=0.732s, avg=0.857s, stdev=0.145s pydantic best=121.947μs/iter avg=142.857μs/iter stdev=24.164μs/iter version=1.4a1 ❯ git checkout encode_known_subclasses Switched to branch 'encode_known_subclasses' Your branch is up to date with 'mine/encode_known_subclasses'. ❯ make benchmark-pydantic python benchmarks/run.py pydantic-only pydantic time=0.973s, success=50.10% pydantic time=0.742s, success=50.10% pydantic time=0.731s, success=50.10% pydantic time=0.764s, success=50.10% pydantic time=0.734s, success=50.10% pydantic best=0.731s, avg=0.789s, stdev=0.104s pydantic best=121.800μs/iter avg=131.485μs/iter stdev=17.306μs/iter version=1.4a1 ``` Perhaps this could also encourage the merge of using the `__class__` attribute instead of `type()` as well: https://github.com/samuelcolvin/pydantic/compare/samuelcolvin:master...use-class-attribute EDITED Rebased on current master: https://github.com/samuelcolvin/pydantic/compare/master...StephenBrown2:use-class-attribute </details> <details> <summary>Aside on usage of __mro__:</summary> I noticed that [`__mro__`](https://docs.python.org/3/library/stdtypes.html?highlight=__mro__#class.__mro__) is not used in many places, though it is referenced in a few places, mostly in mypy.py: https://github.com/samuelcolvin/pydantic/blob/e3243d267b06bda2d7b2213a8bad70f82171033c/pydantic/class_validators.py#L331-L332 https://github.com/samuelcolvin/pydantic/blob/e3243d267b06bda2d7b2213a8bad70f82171033c/pydantic/main.py#L153 https://github.com/samuelcolvin/pydantic/blob/e3243d267b06bda2d7b2213a8bad70f82171033c/pydantic/mypy.py#L84 https://github.com/samuelcolvin/pydantic/blob/e3243d267b06bda2d7b2213a8bad70f82171033c/pydantic/mypy.py#L174 https://github.com/samuelcolvin/pydantic/blob/e3243d267b06bda2d7b2213a8bad70f82171033c/pydantic/mypy.py#L204 https://github.com/samuelcolvin/pydantic/blob/e3243d267b06bda2d7b2213a8bad70f82171033c/pydantic/mypy.py#L275 Rather, [typing's `__supertype__`](https://github.com/python/cpython/blob/ab6423fe2de0ed5f8a0dc86a9c7070229326b0f0/Lib/typing.py#L1929) is used, which I assumed was custom only because I couldn't find it in the [Python docs](https://docs.python.org/3/search.html?q=__supertype__) or anywhere outside of https://github.com/samuelcolvin/pydantic/blob/e3243d267b06bda2d7b2213a8bad70f82171033c/pydantic/typing.py#L180-L187 Would it be prudent/performant to replace the usage of `__supertype__` with a fast-breaking iteration of `__mro__` or perhaps more common usage of `lenient_subclass` in `typing.py`? and subsequently: https://github.com/samuelcolvin/pydantic/blob/e3243d267b06bda2d7b2213a8bad70f82171033c/pydantic/fields.py#L361-L362 https://github.com/samuelcolvin/pydantic/blob/e3243d267b06bda2d7b2213a8bad70f82171033c/pydantic/schema.py#L641-L642 In particular, other checks for inheritance: https://github.com/samuelcolvin/pydantic/blob/e3243d267b06bda2d7b2213a8bad70f82171033c/pydantic/validators.py#L554-L565 https://github.com/samuelcolvin/pydantic/blob/e3243d267b06bda2d7b2213a8bad70f82171033c/pydantic/utils.py#L103-L104 and of course, the tests: https://github.com/samuelcolvin/pydantic/blob/e3243d267b06bda2d7b2213a8bad70f82171033c/tests/test_utils.py#L141-L153 </details>
0.0
5a705a202fd6d10f895145bb625e4c8c9a54e4e3
[ "tests/test_json.py::test_subclass_encoding", "tests/test_json.py::test_subclass_custom_encoding" ]
[ "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[<genexpr>-[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", "tests/test_json.py::test_custom_decode_encode" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-03-04 19:27:19+00:00
mit
4,736
pydantic__pydantic-1306
diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -21,6 +21,7 @@ Union, cast, no_type_check, + overload, ) from .class_validators import ROOT_KEY, ValidatorGroup, extract_root_validators, extract_validators, inherit_validators @@ -43,6 +44,7 @@ ) if TYPE_CHECKING: + import typing_extensions from inspect import Signature from .class_validators import ValidatorListDict from .types import ModelOrDc @@ -52,6 +54,16 @@ ConfigType = Type['BaseConfig'] Model = TypeVar('Model', bound='BaseModel') + class SchemaExtraCallable(typing_extensions.Protocol): + @overload + def __call__(self, schema: Dict[str, Any]) -> None: + pass + + @overload # noqa: F811 + def __call__(self, schema: Dict[str, Any], model_class: Type['Model']) -> None: # noqa: F811 + pass + + try: import cython # type: ignore except ImportError: @@ -89,7 +101,7 @@ class BaseConfig: getter_dict: Type[GetterDict] = GetterDict alias_generator: Optional[Callable[[str], str]] = None keep_untouched: Tuple[type, ...] = () - schema_extra: Union[Dict[str, Any], Callable[[Dict[str, Any]], None]] = {} + schema_extra: Union[Dict[str, Any], 'SchemaExtraCallable'] = {} json_loads: Callable[[str], Any] = json.loads json_dumps: Callable[..., str] = json.dumps json_encoders: Dict[AnyType, AnyCallable] = {} diff --git a/pydantic/schema.py b/pydantic/schema.py --- a/pydantic/schema.py +++ b/pydantic/schema.py @@ -5,7 +5,6 @@ from enum import Enum from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network from pathlib import Path -from types import FunctionType from typing import ( TYPE_CHECKING, Any, @@ -467,8 +466,6 @@ def model_process_schema( s.update(m_schema) schema_extra = model.__config__.schema_extra if callable(schema_extra): - if not isinstance(schema_extra, FunctionType): - raise TypeError(f'{model.__name__}.Config.schema_extra callable is expected to be a staticmethod') if len(signature(schema_extra).parameters) == 1: schema_extra(s) else:
pydantic/pydantic
938335c46f7e31da71e5c2a45eb3cf1ad51030b5
PR welcome to relax the check.
diff --git a/tests/test_schema.py b/tests/test_schema.py --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -1534,18 +1534,33 @@ def schema_extra(schema): assert Model.schema() == {'title': 'Model', 'type': 'override'} -def test_model_with_schema_extra_callable_classmethod_asserts(): +def test_model_with_schema_extra_callable_classmethod(): class Model(BaseModel): name: str = None class Config: + type = 'foo' + @classmethod def schema_extra(cls, schema, model_class): + schema.pop('properties') + schema['type'] = cls.type + assert model_class is Model + + assert Model.schema() == {'title': 'Model', 'type': 'foo'} + + +def test_model_with_schema_extra_callable_instance_method(): + class Model(BaseModel): + name: str = None + + class Config: + def schema_extra(schema, model_class): schema.pop('properties') schema['type'] = 'override' + assert model_class is Model - with pytest.raises(TypeError, match='Model.Config.schema_extra callable is expected to be a staticmethod'): - Model.schema() + assert Model.schema() == {'title': 'Model', 'type': 'override'} def test_model_with_extra_forbidden():
schema_extra should be allowed to be a classmethod In my opinion, this check is unnecessarily restrictive: https://github.com/samuelcolvin/pydantic/blob/938335c46f7e31da71e5c2a45eb3cf1ad51030b5/pydantic/schema.py#L470-L471 Also, it raises `TypeError` only for classmethods, but not for regular methods.
0.0
938335c46f7e31da71e5c2a45eb3cf1ad51030b5
[ "tests/test_schema.py::test_model_with_schema_extra_callable_classmethod" ]
[ "tests/test_schema.py::test_key", "tests/test_schema.py::test_by_alias", "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_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_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_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_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_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_conlist", "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_path_modify_schema", "tests/test_schema.py::test_frozen_set", "tests/test_schema.py::test_iterable" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2020-03-12 15:08:49+00:00
mit
4,737
pydantic__pydantic-1321
diff --git a/pydantic/types.py b/pydantic/types.py --- a/pydantic/types.py +++ b/pydantic/types.py @@ -591,7 +591,7 @@ def get_secret_value(self) -> bytes: return self._secret_value -class PaymentCardBrand(Enum): +class PaymentCardBrand(str, Enum): amex = 'American Express' mastercard = 'Mastercard' visa = 'Visa' @@ -666,7 +666,7 @@ def validate_length_for_brand(cls, card_number: 'PaymentCardNumber') -> 'Payment https://en.wikipedia.org/wiki/Payment_card_number#Issuer_identification_number_(IIN) """ required_length: Optional[int] = None - if card_number.brand is (PaymentCardBrand.visa or PaymentCardBrand.mastercard): + if card_number.brand in {PaymentCardBrand.visa, PaymentCardBrand.mastercard}: required_length = 16 valid = len(card_number) == required_length elif card_number.brand is PaymentCardBrand.amex:
pydantic/pydantic
938335c46f7e31da71e5c2a45eb3cf1ad51030b5
Probably works because of some `Enum` class magic, but could be reworked to: ```py if card_number.brand in (PaymentCardBrand.visa, PaymentCardBrand.mastercard) ``` I guess it depends if equality is acceptable compared to identity? I don't think magic works with is, and I'm kinda glad of that: ``` >>> from enum import Enum >>> class CardType(Enum): ... Diners = 1 ... Visa = 2 ... MasterCard = 3 ... >>> CardType.Visa is (CardType.MasterCard or CardType.Visa) False ``` Good to confirm. Assuming this is resolved. Sadly not resolved, code is still ```python if card_number.brand is (PaymentCardBrand.visa or PaymentCardBrand.mastercard): ``` which won't work if `card_number.brand` is `PaymentCardBrand.mastercard`. Yes, I was just confirming the logic is broken. @mike-hart you might want to submit a PR referencing this issue with the fix. The use of `x is (y or z)` is just a mistake, it simplifies to `x is y` if y is truey or `x is z` otherwise. In this case since `PaymentCardBrand.visa` is truey we're effectively just doing `brand is PaymentCardBrand.visa`. I'll replace it with an `in` check. A bit more background on enums: * Identity checks work with the actual enum member but not with the enum value * equality checks work with both the enum member and the enum value, but **only if** the enum inherits from the correct type as well as `Enum`. ```py class PaymentCardBrand(str, Enum): amex = 'American Express' mastercard = 'Mastercard' visa = 'Visa' other = 'other' b = PaymentCardBrand.visa b is PaymentCardBrand.visa #> True b == PaymentCardBrand.visa #> True b = 'Visa' b is PaymentCardBrand.visa #> False b == PaymentCardBrand.visa #> True (This would not work with the current PaymentCardBrand which doesn't inherit from str) ``` I don't know if `card_number.brand` can be a string or only a `PaymentCardBrand`, but better to fix anyway.
diff --git a/tests/test_types_payment_card_number.py b/tests/test_types_payment_card_number.py --- a/tests/test_types_payment_card_number.py +++ b/tests/test_types_payment_card_number.py @@ -78,6 +78,7 @@ def test_validate_luhn_check_digit(card_number: str, valid: bool): (VALID_AMEX, PaymentCardBrand.amex, True), (VALID_OTHER, PaymentCardBrand.other, True), (LEN_INVALID, PaymentCardBrand.visa, False), + (VALID_AMEX, PaymentCardBrand.mastercard, False), ], ) def test_length_for_brand(card_number: str, brand: PaymentCardBrand, valid: bool): @@ -123,3 +124,21 @@ def test_error_types(card_number: Any, error_message: str): with pytest.raises(ValidationError, match=error_message) as exc_info: PaymentCard(card_number=card_number) assert exc_info.value.json().startswith('[') + + +def test_payment_card_brand(): + b = PaymentCardBrand.visa + assert str(b) == 'Visa' + assert b is PaymentCardBrand.visa + assert b == PaymentCardBrand.visa + assert b in {PaymentCardBrand.visa, PaymentCardBrand.mastercard} + + b = 'Visa' + assert b is not PaymentCardBrand.visa + assert b == PaymentCardBrand.visa + assert b in {PaymentCardBrand.visa, PaymentCardBrand.mastercard} + + b = PaymentCardBrand.amex + assert b is not PaymentCardBrand.visa + assert b != PaymentCardBrand.visa + assert b not in {PaymentCardBrand.visa, PaymentCardBrand.mastercard}
Invalid `is` check in credit card validation https://github.com/samuelcolvin/pydantic/blob/master/pydantic/types.py#L669 ```python if card_number.brand is (PaymentCardBrand.visa or PaymentCardBrand.mastercard) ``` Assuming brand was reduced to the integers, and we had 3 brands, then this is the equivalent of: `3 is (1 or 2)`, which you'd hope were false, `1 is (1 or 2)` which you'd hope were true, and `2 is (1 or 2)` which you'd also hope were true. However, `or` short-circuits, so these reduce to `3 is 1`, `1 is 1`, and `2 is 1`. This means the preferred outcome for the first two cases works, but it would fail for mastercard. Perhaps this should be ```python if card_number.brand is PaymentCardBrand.visa or card_number.brand is PaymentCardBrand.mastercard: ``` I think this was added relatively recently - https://github.com/samuelcolvin/pydantic/commit/0c5793770be1de8b1a28c3fbaca669cf3bab1e34#diff-470d0730db2e82eaaf27ad3655a667b3R582 - so hopefully it hasn't affected too many people.
0.0
938335c46f7e31da71e5c2a45eb3cf1ad51030b5
[ "tests/test_types_payment_card_number.py::test_length_for_brand[370000000000002-Mastercard-False]", "tests/test_types_payment_card_number.py::test_payment_card_brand" ]
[ "tests/test_types_payment_card_number.py::test_validate_digits", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[0-True]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[00-True]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[18-True]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[0000000000000000-True]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[4242424242424240-False]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[4242424242424241-False]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[4242424242424242-True]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[4242424242424243-False]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[4242424242424244-False]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[4242424242424245-False]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[4242424242424246-False]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[4242424242424247-False]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[4242424242424248-False]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[4242424242424249-False]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[42424242424242426-True]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[424242424242424267-True]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[4242424242424242675-True]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[5164581347216566-True]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[4345351087414150-True]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[343728738009846-True]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[5164581347216567-False]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[4345351087414151-False]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[343728738009847-False]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[000000018-True]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[99999999999999999999-True]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[99999999999999999999999999999999999999999999999999999999999999999997-True]", "tests/test_types_payment_card_number.py::test_length_for_brand[4050000000000001-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[4050000000000001-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_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2020-03-17 19:11:10+00:00
mit
4,738
pydantic__pydantic-1420
diff --git a/pydantic/utils.py b/pydantic/utils.py --- a/pydantic/utils.py +++ b/pydantic/utils.py @@ -174,13 +174,31 @@ def generate_model_signature( # TODO: replace annotation with actual expected types once #1055 solved kwargs = {'default': field.default} if not field.required else {} - merged_params[param_name] = Parameter(param_name, Parameter.KEYWORD_ONLY, annotation=field.type_, **kwargs) + merged_params[param_name] = Parameter( + param_name, Parameter.KEYWORD_ONLY, annotation=field.outer_type_, **kwargs + ) if config.extra is config.extra.allow: use_var_kw = True if var_kw and use_var_kw: - merged_params[var_kw.name] = var_kw + # Make sure the parameter for extra kwargs + # does not have the same name as a field + default_model_signature = [ + ('__pydantic_self__', Parameter.POSITIONAL_OR_KEYWORD), + ('data', Parameter.VAR_KEYWORD), + ] + if [(p.name, p.kind) for p in present_params] == default_model_signature: + # if this is the standard model signature, use extra_data as the extra args name + var_kw_name = 'extra_data' + else: + # else start from var_kw + var_kw_name = var_kw.name + + # generate a name that's definitely unique + while var_kw_name in fields: + var_kw_name += '_' + merged_params[var_kw_name] = var_kw.replace(name=var_kw_name) return Signature(parameters=list(merged_params.values()), return_annotation=None)
pydantic/pydantic
3cd8b1ee2d5aac76528dbe627f40fe1c27bf59f6
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 @@ -71,7 +71,7 @@ def test_invalid_identifiers_signature(): ) assert _equals(str(signature(model)), '(*, valid_identifier: int = 123, yeah: int = 0) -> None') model = create_model('Model', **{'123 invalid identifier!': 123, '!': Field(0, alias='yeah')}) - assert _equals(str(signature(model)), '(*, yeah: int = 0, **data: Any) -> None') + assert _equals(str(signature(model)), '(*, yeah: int = 0, **extra_data: Any) -> None') def test_use_field_name(): @@ -82,3 +82,47 @@ class Config: allow_population_by_field_name = True assert _equals(str(signature(Foo)), '(*, foo: str) -> None') + + +def test_extra_allow_no_conflict(): + class Model(BaseModel): + spam: str + + class Config: + extra = Extra.allow + + assert _equals(str(signature(Model)), '(*, spam: str, **extra_data: Any) -> None') + + +def test_extra_allow_conflict(): + class Model(BaseModel): + extra_data: str + + class Config: + extra = Extra.allow + + assert _equals(str(signature(Model)), '(*, extra_data: str, **extra_data_: Any) -> None') + + +def test_extra_allow_conflict_twice(): + class Model(BaseModel): + extra_data: str + extra_data_: str + + class Config: + extra = Extra.allow + + assert _equals(str(signature(Model)), '(*, extra_data: str, extra_data_: str, **extra_data__: Any) -> None') + + +def test_extra_allow_conflict_custom_signature(): + class Model(BaseModel): + extra_data: int + + def __init__(self, extra_data: int = 1, **foobar: Any): + super().__init__(extra_data=extra_data, **foobar) + + class Config: + extra = Extra.allow + + assert _equals(str(signature(Model)), '(extra_data: int = 1, **foobar: Any) -> None')
Model signature generation makes incorrect signature for models with extras allowed and `data` attribute in spec # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.5 pydantic compiled: False install path: /home/jrootjunior/.cache/pypoetry/virtualenvs/aiogram-BAWpo_Vh-py3.8/lib/python3.8/site-packages/pydantic python version: 3.8.2 (default, Apr 8 2020, 14:31:25) [GCC 9.3.0] platform: Linux-5.6.3-arch1-1-x86_64-with-glibc2.2.5 optional deps. installed: ['typing-extensions'] ``` ## Explanation Feature from #1034 breaks things when model has `data` attribute and extra arguments is allowed and this attribute is not the last one in class. ## Code snippet ```py import inspect from typing import Optional from pydantic import BaseModel, Extra class MyObject(BaseModel): foo: Optional[str] = None data: Optional[str] = None bar: Optional[str] = None class Config: extra = Extra.allow ``` ## Caused an exception ```py Traceback (most recent call last): File "/home/jrootjunior/work/aiogram3/expetiment.py", line 7, in <module> class MyObject(BaseModel): File "/home/jrootjunior/.cache/pypoetry/virtualenvs/aiogram-BAWpo_Vh-py3.8/lib/python3.8/site-packages/pydantic/main.py", line 303, in __new__ cls.__signature__ = generate_model_signature(cls.__init__, fields, config) File "/home/jrootjunior/.cache/pypoetry/virtualenvs/aiogram-BAWpo_Vh-py3.8/lib/python3.8/site-packages/pydantic/utils.py", line 185, in generate_model_signature return Signature(parameters=list(merged_params.values()), return_annotation=None) File "/usr/lib/python3.8/inspect.py", line 2785, in __init__ raise ValueError(msg) ValueError: wrong parameter order: variadic keyword parameter before keyword-only parameter ``` ## Information from debugger As i see the `data` argument has incorrect signature: ![image](https://user-images.githubusercontent.com/6726423/80035891-77366c80-84f9-11ea-9b4c-e3c7c498d8a3.png)
0.0
3cd8b1ee2d5aac76528dbe627f40fe1c27bf59f6
[ "tests/test_model_signature.py::test_invalid_identifiers_signature", "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_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_use_field_name", "tests/test_model_signature.py::test_extra_allow_conflict_custom_signature" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_media" ], "has_test_patch": true, "is_lite": false }
2020-04-22 23:06:39+00:00
mit
4,739
pydantic__pydantic-1466
diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -35,6 +35,7 @@ from .types import PyObject, StrBytes from .typing import AnyCallable, AnyType, ForwardRef, is_classvar, resolve_annotations, update_field_forward_refs from .utils import ( + ClassAttribute, GetterDict, Representation, ValueItems, @@ -300,7 +301,8 @@ def __new__(mcs, name, bases, namespace, **kwargs): # noqa C901 } cls = super().__new__(mcs, name, bases, new_namespace, **kwargs) - cls.__signature__ = generate_model_signature(cls.__init__, fields, config) + # set __signature__ attr only for model class, but not for its instances + cls.__signature__ = ClassAttribute('__signature__', generate_model_signature(cls.__init__, fields, config)) return cls diff --git a/pydantic/utils.py b/pydantic/utils.py --- a/pydantic/utils.py +++ b/pydantic/utils.py @@ -45,6 +45,7 @@ 'GetterDict', 'ValueItems', 'version_info', # required here to match behaviour in v1.3 + 'ClassAttribute', ) @@ -439,3 +440,23 @@ def _normalize_indexes( def __repr_args__(self) -> 'ReprArgs': return [(None, self._items)] + + +class ClassAttribute: + """ + Hide class attribute from its instances + """ + + __slots__ = ( + 'name', + 'value', + ) + + def __init__(self, name: str, value: Any) -> None: + self.name = name + self.value = value + + def __get__(self, instance: Any, owner: Type[Any]) -> None: + if instance is None: + return self.value + raise AttributeError(f'{self.name!r} attribute of {owner.__name__!r} is class-only')
pydantic/pydantic
881df8bde7bfc90e3a349c420d0b0b7d46237d59
thanks for reporting, PR welcome. Just saw this, ugh. Will make a PR soon :)
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 @@ -126,3 +126,15 @@ class Config: extra = Extra.allow assert _equals(str(signature(Model)), '(extra_data: int = 1, **foobar: Any) -> None') + + +def test_signature_is_class_only(): + class Model(BaseModel): + foo: int = 123 + + def __call__(self, a: int) -> bool: + pass + + assert _equals(str(signature(Model)), '(*, foo: int = 123) -> None') + assert _equals(str(signature(Model())), '(a: int) -> bool') + assert not hasattr(Model(), '__signature__') diff --git a/tests/test_utils.py b/tests/test_utils.py --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -12,7 +12,15 @@ from pydantic.dataclasses import dataclass from pydantic.fields import Undefined from pydantic.typing import display_as_type, is_new_type, new_type_supertype -from pydantic.utils import ValueItems, deep_update, get_model, import_string, lenient_issubclass, truncate +from pydantic.utils import ( + ClassAttribute, + ValueItems, + deep_update, + get_model, + import_string, + lenient_issubclass, + truncate, +) from pydantic.version import version_info try: @@ -298,3 +306,17 @@ def test_version_info(): def test_version_strict(): assert str(StrictVersion(VERSION)) == VERSION + + +def test_class_attribute(): + class Foo: + attr = ClassAttribute('attr', 'foo') + + assert Foo.attr == 'foo' + + with pytest.raises(AttributeError, match="'attr' attribute of 'Foo' is class-only"): + Foo().attr + + f = Foo() + f.attr = 'not foo' + assert f.attr == 'not foo'
Incorrect signature for instances of models # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.5 pydantic compiled: False install path: /home/jrootjunior/.cache/pypoetry/virtualenvs/aiogram-BAWpo_Vh-py3.8/lib/python3.8/site-packages/pydantic python version: 3.8.2 (default, Apr 8 2020, 14:31:25) [GCC 9.3.0] platform: Linux-5.6.3-arch1-1-x86_64-with-glibc2.2.5 optional deps. installed: ['typing-extensions'] ``` ## Explanation Feature from #1034 generates incorrect signature for callable instances of models. ## Code examples ### Current behavior ```py import inspect from pydantic import BaseModel class MyModel(BaseModel): foo: str def __call__(self, bar: str): pass print(inspect.getfullargspec(MyModel)) print(inspect.getfullargspec(MyModel(foo="baz"))) ``` will print ```py FullArgSpec(args=[], varargs=None, varkw=None, defaults=None, kwonlyargs=['foo'], kwonlydefaults=None, annotations={'return': None, 'foo': <class 'str'>}) FullArgSpec(args=[], varargs=None, varkw=None, defaults=None, kwonlyargs=['foo'], kwonlydefaults=None, annotations={'return': None, 'foo': <class 'str'>}) ``` Spec for class is correct in most of cases. Is only needed to add `self` to `args` Spec for instance of that model is incorrect in due to instance can not be called with this spec ### Expected behavior ```py import inspect class MyModel: def __init__(self, *, foo: str): self.foo = foo def __call__(self, bar: str): pass print(inspect.getfullargspec(MyModel)) print(inspect.getfullargspec(MyModel(foo="baz"))) ``` will print ```py FullArgSpec(args=['self'], varargs=None, varkw=None, defaults=None, kwonlyargs=['foo'], kwonlydefaults=None, annotations={'foo': <class 'str'>}) FullArgSpec(args=['self', 'bar'], varargs=None, varkw=None, defaults=None, kwonlyargs=[], kwonlydefaults=None, annotations={'bar': <class 'str'>} ``` `getfullargspec` for class returns spec of `__init__` `getfullargspec` for instance returns spec of `__call__` method ### Another expected behavior ```py import inspect class MyModel: def __init__(self, *, foo: str): self.foo = foo print(inspect.getfullargspec(MyModel)) print(inspect.getfullargspec(MyModel(foo="baz"))) ``` will print ```py FullArgSpec(args=['self'], varargs=None, varkw=None, defaults=None, kwonlyargs=['foo'], kwonlydefaults=None, annotations={'foo': <class 'str'>}) Traceback (most recent call last): File "/usr/lib/python3.8/inspect.py", line 1123, in getfullargspec sig = _signature_from_callable(func, File "/usr/lib/python3.8/inspect.py", line 2216, in _signature_from_callable raise TypeError('{!r} is not a callable object'.format(obj)) TypeError: <__main__.MyModel object at 0x7fb1f405b490> is not a callable object The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/jrootjunior/work/aiogram3/expetiment.py", line 19, in <module> print(inspect.getfullargspec(MyModel(foo="baz"))) File "/usr/lib/python3.8/inspect.py", line 1132, in getfullargspec raise TypeError('unsupported callable') from ex TypeError: unsupported callable ``` `getfullargspec` for class returns spec of `__init__` `getfullargspec` for instance raises an error about instance is not callable.
0.0
881df8bde7bfc90e3a349c420d0b0b7d46237d59
[ "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", "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_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", "tests/test_utils.py::test_undefined_repr", "tests/test_utils.py::test_get_model", "tests/test_utils.py::test_version_info", "tests/test_utils.py::test_version_strict", "tests/test_utils.py::test_class_attribute" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2020-04-30 22:13:23+00:00
mit
4,740
pydantic__pydantic-1527
diff --git a/pydantic/networks.py b/pydantic/networks.py --- a/pydantic/networks.py +++ b/pydantic/networks.py @@ -329,6 +329,9 @@ def __init__(self, name: str, email: str): self.name = name self.email = email + def __eq__(self, other: Any) -> bool: + return isinstance(other, NameEmail) and (self.name, self.email) == (other.name, other.email) + @classmethod def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None: field_schema.update(type='string', format='name-email')
pydantic/pydantic
5067508eca6222b9315b1e38a30ddc975dee05e7
Thanks for reporting. Happy to accept a PR to add a proper `__eq__` method to `NameEmail`
diff --git a/tests/test_networks.py b/tests/test_networks.py --- a/tests/test_networks.py +++ b/tests/test_networks.py @@ -453,3 +453,5 @@ class Model(BaseModel): assert str(Model(v=NameEmail('foo bar', '[email protected]')).v) == 'foo bar <[email protected]>' assert str(Model(v='foo bar <[email protected]>').v) == 'foo bar <[email protected]>' + assert NameEmail('foo bar', '[email protected]') == NameEmail('foo bar', '[email protected]') + assert NameEmail('foo bar', '[email protected]') != NameEmail('foo bar', '[email protected]')
Same NameEmail field instances are not equal # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.5.1 pydantic compiled: True install path: /Users/***/.local/share/virtualenvs/tempenv-42b2286175873/lib/python3.7/site-packages/pydantic python version: 3.7.4 (default, Jul 22 2019, 11:21:52) [Clang 10.0.1 (clang-1001.0.46.4)] platform: Darwin-18.7.0-x86_64-i386-64bit optional deps. installed: ['email-validator'] ``` I'm assuming that equality should be enforced on field types such as `NameEmail`. At the moment it seems that instances that appear to be equal are generating different hashes. Unsure if this is desired, but I would argue it shouldn't be. ```py import pydantic # will raise an AssertionError assert pydantic.NameEmail("test", "[email protected]") == pydantic.NameEmail("test", "[email protected]") ```
0.0
5067508eca6222b9315b1e38a30ddc975dee05e7
[ "tests/test_networks.py::test_name_email" ]
[ "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+psycopg2://postgres:postgres@localhost:5432/hatch]", "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_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_parts", "tests/test_networks.py::test_url_repr", "tests/test_networks.py::test_ipv4_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_at_in_path", "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_postgres_dsns", "tests/test_networks.py::test_redis_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_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" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2020-05-18 16:10:24+00:00
mit
4,741
pydantic__pydantic-1562
diff --git a/pydantic/schema.py b/pydantic/schema.py --- a/pydantic/schema.py +++ b/pydantic/schema.py @@ -239,7 +239,7 @@ def get_field_schema_validations(field: ModelField) -> Dict[str, Any]: f_schema['const'] = field.default if field.field_info.extra: f_schema.update(field.field_info.extra) - modify_schema = getattr(field.type_, '__modify_schema__', None) + modify_schema = getattr(field.outer_type_, '__modify_schema__', None) if modify_schema: modify_schema(f_schema) return f_schema
pydantic/pydantic
2eb62a3b2f2d345aa7b4625306331f68a7bc0fd5
diff --git a/tests/test_schema.py b/tests/test_schema.py --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -1822,6 +1822,7 @@ def __modify_schema__(cls, schema): class Model(BaseModel): path1: Path path2: MyPath + path3: List[MyPath] assert Model.schema() == { 'title': 'Model', @@ -1829,8 +1830,9 @@ class Model(BaseModel): 'properties': { 'path1': {'title': 'Path1', 'type': 'string', 'format': 'path'}, 'path2': {'title': 'Path2', 'type': 'string', 'format': 'path', 'foobar': 123}, + 'path3': {'title': 'Path3', 'type': 'array', 'items': {'type': 'string', 'format': 'path', 'foobar': 123}}, }, - 'required': ['path1', 'path2'], + 'required': ['path1', 'path2', 'path3'], }
Possible regression of __modify_schema__ on master # Bug I think #1422 causes an unintentional (?) change in the behaviour of `__modify_schema__` - it's now applying to the list schema as well as the item schema. Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.5.1 pydantic compiled: False install path: /home/johnc/Projects/pydantic/pydantic python version: 3.7.7 (default, Apr 18 2020, 02:59:53) [GCC 9.3.0] platform: Linux-5.4.0-29-generic-x86_64-with-Ubuntu-20.04-focal optional deps. installed: [] ``` Actually at git version 5195e55c102e537be6c00579df8f464ecd90b5ff - ``` pip freeze | grep pydantic -e git+https://github.com/samuelcolvin/pydantic.git@5195e55c102e537be6c00579df8f464ecd90b5ff#egg=pydantic ``` The output of the following code is different between master and v1.5.1 ```py from typing import List import pydantic class MyField(str): @classmethod def __modify_schema__(cls, field_schema): field_schema["foo"] = "buzz" class Foo(pydantic.BaseModel): a_field: MyField some_fields: List[MyField] print(Foo.schema_json(indent=2)) ``` With 1.5.1 this outputs: ``` { "title": "Foo", "type": "object", "properties": { "a_field": { "title": "A Field", "type": "string", "foo": "buzz" }, "some_fields": { "title": "Some Fields", "type": "array", "items": { "type": "string", "foo": "buzz" } } }, "required": [ "a_field", "some_fields" ] } ``` With current master this outputs: ``` { "title": "Foo", "type": "object", "properties": { "a_field": { "title": "A Field", "foo": "buzz", "type": "string" }, "some_fields": { "title": "Some Fields", "foo": "buzz", "type": "array", "items": { "type": "string", "foo": "buzz" } } }, "required": [ "a_field", "some_fields" ] } ``` Diff: ```diff { "title": "Foo", "type": "object", "properties": { "a_field": { "title": "A Field", - "type": "string", - "foo": "buzz" + "foo": "buzz", + "type": "string" }, "some_fields": { "title": "Some Fields", + "foo": "buzz", "type": "array", "items": { "type": "string", "foo": "buzz" } } }, "required": [ "a_field", "some_fields" ] } ``` Note the extra "foo" in `some_fields` - I think this is a regression?
0.0
2eb62a3b2f2d345aa7b4625306331f68a7bc0fd5
[ "tests/test_schema.py::test_path_modify_schema" ]
[ "tests/test_schema.py::test_key", "tests/test_schema.py::test_by_alias", "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_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_overrides_w_union", "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-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-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_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_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_conlist", "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_frozen_set", "tests/test_schema.py::test_iterable", "tests/test_schema.py::test_new_type" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_git_commit_hash" ], "has_test_patch": true, "is_lite": false }
2020-05-26 09:11:54+00:00
mit
4,742
pydantic__pydantic-1581
diff --git a/pydantic/schema.py b/pydantic/schema.py --- a/pydantic/schema.py +++ b/pydantic/schema.py @@ -545,6 +545,10 @@ def enum_process_schema(enum: Type[Enum]) -> Dict[str, Any]: add_field_type_to_schema(enum, schema) + modify_schema = getattr(enum, '__modify_schema__', None) + if modify_schema: + modify_schema(schema) + return schema @@ -698,9 +702,9 @@ def field_singleton_schema( # noqa: C901 (ignore complexity) else: add_field_type_to_schema(field_type, f_schema) - modify_schema = getattr(field_type, '__modify_schema__', None) - if modify_schema: - modify_schema(f_schema) + modify_schema = getattr(field_type, '__modify_schema__', None) + if modify_schema: + modify_schema(f_schema) if f_schema: return f_schema, definitions, nested_models
pydantic/pydantic
2eb62a3b2f2d345aa7b4625306331f68a7bc0fd5
diff --git a/tests/test_schema.py b/tests/test_schema.py --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -222,6 +222,34 @@ class Model(BaseModel): } +def test_enum_modify_schema(): + class SpamEnum(str, Enum): + foo = 'f' + bar = 'b' + + @classmethod + def __modify_schema__(cls, field_schema): + field_schema['tsEnumNames'] = [e.name for e in cls] + + class Model(BaseModel): + spam: SpamEnum = Field(None) + + assert Model.schema() == { + 'definitions': { + 'SpamEnum': { + 'description': 'An enumeration.', + 'enum': ['f', 'b'], + 'title': 'SpamEnum', + 'tsEnumNames': ['foo', 'bar'], + 'type': 'string', + } + }, + 'properties': {'spam': {'$ref': '#/definitions/SpamEnum'}}, + 'title': 'Model', + 'type': 'object', + } + + def test_json_schema(): class Model(BaseModel): a = b'foobar'
Possible regression of __modify_schema__ for enum fields # Bug A side-effect of #1432 is that `__modify_schema__` on enum subclasses is still affecting the field schema, rather than the enumeration schema. I'd like it if `__modify_schema__` applied to the resulting enum model. Does that seem reasonable? In my use case I'm subclassing enum to add a `tsEnumNames` property, so that I could generate proper typescript enums from the resulting Json schema (using json-schema-to-typescript - see https://github.com/bcherny/json-schema-to-typescript/pull/15 ). Using latest master 2eb62a3b2f2d345aa7b4625306331f68a7bc0fd5 (or d560c57dbcfe91e9f67782ede3e871ce19b88373 from #1562) ```py import enum import pydantic class TsCompatibleEnum(enum.Enum): """Enum subclass that adds tsEnumNames to enumeration fields for compatibility with json-schema-to-typescript See https://github.com/bcherny/json-schema-to-typescript/pull/15 """ @classmethod def __modify_schema__(cls, field_schema): field_schema["tsEnumNames"] = list(e.name for e in cls) class MyEnum(TsCompatibleEnum): """Enumeration - note that the names and values are different""" FOO = "foo" BAR = "bar" class MyModel(pydantic.BaseModel): my_field: MyEnum = MyEnum.FOO print(MyModel.schema_json(indent=2)) ``` Outputs: ```json { "title": "MyModel", "type": "object", "properties": { "my_field": { "$ref": "#/definitions/MyEnum", "tsEnumNames": [ "FOO", "BAR" ] } }, "definitions": { "MyEnum": { "title": "MyEnum", "description": "Enumeration - note that the names and values are different", "enum": [ "foo", "bar" ] } } } ``` vs with pydantic 1.5.1: ```json { "title": "MyModel", "type": "object", "properties": { "my_field": { "title": "My Field", "default": "foo", "enum": [ "foo", "bar" ], "tsEnumNames": [ "FOO", "BAR" ] } } } ``` I'd like to get this instead: ```json { "title": "MyModel", "type": "object", "properties": { "my_field": { "$ref": "#/definitions/MyEnum" } }, "definitions": { "MyEnum": { "title": "MyEnum", "description": "Enumeration - note that the names and values are different", "enum": [ "foo", "bar" ], "tsEnumNames": [ "FOO", "BAR" ] } } } ```
0.0
2eb62a3b2f2d345aa7b4625306331f68a7bc0fd5
[ "tests/test_schema.py::test_enum_modify_schema" ]
[ "tests/test_schema.py::test_key", "tests/test_schema.py::test_by_alias", "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_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_overrides_w_union", "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-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-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_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_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_conlist", "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" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_git_commit_hash" ], "has_test_patch": true, "is_lite": false }
2020-05-31 00:47:22+00:00
mit
4,743
pydantic__pydantic-1585
diff --git a/pydantic/env_settings.py b/pydantic/env_settings.py --- a/pydantic/env_settings.py +++ b/pydantic/env_settings.py @@ -4,7 +4,7 @@ from typing import AbstractSet, Any, Dict, List, Mapping, Optional, Union from .fields import ModelField -from .main import BaseModel, Extra +from .main import BaseConfig, BaseModel, Extra from .typing import display_as_type from .utils import deep_update, sequence_like @@ -65,7 +65,7 @@ def _build_environ(self, _env_file: Union[Path, str, None] = None) -> Dict[str, d[field.alias] = env_val return d - class Config: + class Config(BaseConfig): env_prefix = '' env_file = None validate_all = True @@ -76,7 +76,9 @@ class Config: @classmethod def prepare_field(cls, field: ModelField) -> None: env_names: Union[List[str], AbstractSet[str]] - env = field.field_info.extra.get('env') + field_info_from_config = cls.get_field_info(field.name) + + env = field_info_from_config.get('env') or field.field_info.extra.get('env') if env is None: if field.has_alias: warnings.warn(
pydantic/pydantic
f89e372bdaa03adec9ab8b04d167e97b00576e4b
Related: https://github.com/samuelcolvin/pydantic/issues/1091 Apparently, when calling https://github.com/samuelcolvin/pydantic/blob/master/pydantic/main.py#L221 and then https://github.com/samuelcolvin/pydantic/blob/master/pydantic/fields.py#L325 `info_from_config`, fetched from a config, is not actually a part of the field yet (`self.field_info`) and thus on https://github.com/samuelcolvin/pydantic/blob/master/pydantic/env_settings.py#L79 we get a default info Thanks for pointing this out. PR welcome to fix it, I've no idea how hard it would be to solve, maybe quite difficult.
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 Dict, List, Set +from typing import Dict, List, Optional, Set import pytest @@ -221,6 +221,107 @@ class SettingsChild(SettingsParent): assert SettingsChild(foobar='abc').foobar == 'abc' +def test_env_prefix_inheritance_config(env): + env.set('foobar', 'foobar') + env.set('prefix_foobar', 'prefix_foobar') + + env.set('foobar_parent_from_field', 'foobar_parent_from_field') + env.set('foobar_child_from_field', 'foobar_child_from_field') + + env.set('foobar_parent_from_config', 'foobar_parent_from_config') + env.set('foobar_child_from_config', 'foobar_child_from_config') + + # . Child prefix does not override explicit parent field config + class Parent(BaseSettings): + foobar: str = Field(None, env='foobar_parent_from_field') + + class Child(Parent): + class Config: + env_prefix = 'prefix_' + + assert Child().foobar == 'foobar_parent_from_field' + + # c. Child prefix does not override explicit parent class config + class Parent(BaseSettings): + foobar: str = None + + class Config: + fields = { + 'foobar': {'env': ['foobar_parent_from_config']}, + } + + class Child(Parent): + class Config: + env_prefix = 'prefix_' + + assert Child().foobar == 'foobar_parent_from_config' + + # d. Child prefix overrides parent with implicit config + class Parent(BaseSettings): + foobar: str = None + + class Child(Parent): + class Config: + env_prefix = 'prefix_' + + assert Child().foobar == 'prefix_foobar' + + +def test_env_inheritance_config(env): + env.set('foobar', 'foobar') + env.set('prefix_foobar', 'prefix_foobar') + + env.set('foobar_parent_from_field', 'foobar_parent_from_field') + env.set('foobar_child_from_field', 'foobar_child_from_field') + + env.set('foobar_parent_from_config', 'foobar_parent_from_config') + env.set('foobar_child_from_config', 'foobar_child_from_config') + + # a. Child class config overrides prefix and parent field config + class Parent(BaseSettings): + foobar: str = Field(None, env='foobar_parent_from_field') + + class Child(Parent): + class Config: + env_prefix = 'prefix_' + fields = { + 'foobar': {'env': ['foobar_child_from_config']}, + } + + assert Child().foobar == 'foobar_child_from_config' + + # b. Child class config overrides prefix and parent class config + class Parent(BaseSettings): + foobar: str = None + + class Config: + fields = { + 'foobar': {'env': ['foobar_parent_from_config']}, + } + + class Child(Parent): + class Config: + env_prefix = 'prefix_' + fields = { + 'foobar': {'env': ['foobar_child_from_config']}, + } + + assert Child().foobar == 'foobar_child_from_config' + + # . Child class config overrides prefix and parent with implicit config + class Parent(BaseSettings): + foobar: Optional[str] + + class Child(Parent): + class Config: + env_prefix = 'prefix_' + fields = { + 'foobar': {'env': ['foobar_child_from_field']}, + } + + assert Child().foobar == 'foobar_child_from_field' + + def test_env_invalid(env): with pytest.raises(TypeError, match=r'invalid field env: 123 \(int\); should be string, list or set'):
Env settings in the config for a parent field apparently don`t work # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.5.1 pydantic compiled: True install path: /home/yury/.cache/pypoetry/virtualenvs/chatbot-py3.6/lib/python3.6/site-packages/pydantic python version: 3.6.9 (default, Apr 18 2020, 01:56:04) [GCC 8.4.0] platform: Linux-5.3.0-51-generic-x86_64-with-Ubuntu-18.04-bionic optional deps. installed: ['typing-extensions', 'email-validator'] ``` If I configure an alternative prefix for a field `foo` in the same class it gets into the field configuration, but whenever I set that in the descendant it doesn't seem to have effect ```py In [2]: from pydantic import AnyUrl, BaseSettings In [4]: %set_env FOO=7 env: FOO=7 In [9]: class A(BaseSettings): ...: foo : int ...: class Config: ...: env_prefix = 'PREFIX_' ...: fields = { ...: 'foo': {'env': ['FOO', 'PREFIX_FOO'],}, ...: } ...: ...: In [10]: A().foo Out[10]: 7 In [11]: A.__fields__['foo'].field_info Out[11]: FieldInfo(default=Ellipsis, extra={'env': ['FOO', 'PREFIX_FOO'], 'env_names': ['foo', 'prefix_foo']}) In [12]: class A(BaseSettings): ...: foo : int ...: In [13]: class B(A): ...: class Config: ...: env_prefix = 'PREFIX_' ...: fields = { ...: 'foo': {'env': ['FOO', 'PREFIX_FOO'],}, ...: } ...: ...: ...: In [14]: B().foo --------------------------------------------------------------------------- ValidationError Traceback (most recent call last) <ipython-input-14-40329edc0228> in <module> ----> 1 B().foo ~/.cache/pypoetry/virtualenvs/chatbot-py3.6/lib/python3.6/site-packages/pydantic/env_settings.cpython-36m-x86_64-linux-gnu.so in pydantic.env_settings.BaseSettings.__init__() ~/.cache/pypoetry/virtualenvs/chatbot-py3.6/lib/python3.6/site-packages/pydantic/main.cpython-36m-x86_64-linux-gnu.so in pydantic.main.BaseModel.__init__() ValidationError: 1 validation error for B foo field required (type=value_error.missing) In [15]: A.__fields__['foo'] Out[15]: ModelField(name='foo', type=int, required=True) In [16]: A.__fields__['foo'].field_info Out[16]: FieldInfo(default=Ellipsis, extra={'env_names': {'foo'}}) In [17]: B.__fields__['foo'].field_info Out[17]: FieldInfo(default=Ellipsis, extra={'env_names': {'prefix_foo'}}) ```
0.0
f89e372bdaa03adec9ab8b04d167e97b00576e4b
[ "tests/test_settings.py::test_env_inheritance_config" ]
[ "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_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_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_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_alias_set", "tests/test_settings.py::test_prefix_on_parent", "tests/test_settings.py::test_frozenset" ]
{ "failed_lite_validators": [ "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2020-05-31 19:50:48+00:00
mit
4,744
pydantic__pydantic-1605
diff --git a/pydantic/datetime_parse.py b/pydantic/datetime_parse.py --- a/pydantic/datetime_parse.py +++ b/pydantic/datetime_parse.py @@ -75,7 +75,7 @@ def get_numeric(value: StrBytesIntFloat, native_expected_type: str) -> Union[Non def from_unix_seconds(seconds: Union[int, float]) -> datetime: - while seconds > MS_WATERSHED: + while abs(seconds) > MS_WATERSHED: seconds /= 1000 dt = EPOCH + timedelta(seconds=seconds) return dt.replace(tzinfo=timezone.utc)
pydantic/pydantic
5e82689c79103d3508c233272773a2898d516086
Happy to accept a PR to fix this. I guess we should: * raise the correct error resulting in a validation error if the datetime is out of bounds * accept negative timestamps if they result in valid datetimes - there's nothing implicitly wrong with the unix timestamp of `-1`. Stuff happened before 1970 apparently. * comparing with `MS_WATERSHED` as an absolute number makes sense I suppose, we would just need to update the docs to be explicit. I don't get this : > * raise the correct error resulting in a validation error if the datetime is out of bounds For the rest, everything is running fine and ready for PR I think it might be fine, I just meant: make sure passing timestamps like `1_000_000_000_000_000` or `-100_000_000_000_000` cause sensible validation errors not other exceptions. Yes, it runs fine with these timestamps. The generated `datetime` does not match with the real date as these timestamps are greater than `MS_WATERSHED` but it is parsed without any exception.
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 @@ -93,6 +93,7 @@ def test_time_parsing(value, result): (1_494_012_444, datetime(2017, 5, 5, 19, 27, 24, tzinfo=timezone.utc)), # values in ms ('1494012444000.883309', datetime(2017, 5, 5, 19, 27, 24, 883, tzinfo=timezone.utc)), + ('-1494012444000.883309', datetime(1922, 8, 29, 4, 32, 35, 999117, tzinfo=timezone.utc)), (1_494_012_444_000, datetime(2017, 5, 5, 19, 27, 24, tzinfo=timezone.utc)), ('2012-04-23T09:15:00', datetime(2012, 4, 23, 9, 15)), ('2012-4-9 4:8:16', datetime(2012, 4, 9, 4, 8, 16)),
JavaScript negative timestamp are not supported # Bug When parsing a JavaScript positive timestamp (number of milliseconds since EPOCH), pydantic parses it properly. However, for a negative JavaScript timestamp (before 1st January 1970), a `date value out of range` error is thrown. ``` File "pydantic/main.py", line 447, in pydantic.main.BaseModel.parse_obj File "pydantic/main.py", line 336, in pydantic.main.BaseModel.__init__ File "pydantic/main.py", line 887, in pydantic.main.validate_model File "pydantic/fields.py", line 549, in pydantic.fields.ModelField.validate File "pydantic/fields.py", line 704, in pydantic.fields.ModelField._validate_singleton File "pydantic/fields.py", line 711, in pydantic.fields.ModelField._apply_validators File "pydantic/class_validators.py", line 313, in pydantic.class_validators._generic_validator_basic.lambda11 File "pydantic/datetime_parse.py", line 169, in pydantic.datetime_parse.parse_datetime File "pydantic/datetime_parse.py", line 80, in pydantic.datetime_parse.from_unix_seconds OverflowError: date value out of range ``` ## Version Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.5.1 pydantic compiled: True install path: /Users/thibaud/Documents/Programmation/Scopyleft/Terrapeutes/aposto-server/venv/lib/python3.7/site-packages/pydantic python version: 3.7.3 (default, Mar 6 2020, 22:34:30) [Clang 11.0.3 (clang-1103.0.32.29)] platform: Darwin-19.5.0-x86_64-i386-64bit optional deps. installed: ['typing-extensions', 'email-validator'] ``` ## Code example The following code raises the describe error (while it would correctly work with `{ "jsTimestamp": 1118102400000 }`). ```py from datetime import datetime from pydantic import BaseModel class MyModel(BaseModel): jsTimestamp: datetime MyModel.parse_obj({ "jsTimestamp": -1118102400000 }) ``` ## Possible solution A solution would be to update the `from_unix_seconds` function in _datetime_parse.py_ to compare `seconds` with `MS_WATERSHED` as absolute value.
0.0
5e82689c79103d3508c233272773a2898d516086
[ "tests/test_datetime_parse.py::test_datetime_parsing[-1494012444000.883309-result6]" ]
[ "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_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[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_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-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[19999999999-result20]", "tests/test_datetime_parse.py::test_datetime_parsing[20000000001-result21]", "tests/test_datetime_parse.py::test_datetime_parsing[1549316052-result22]", "tests/test_datetime_parse.py::test_datetime_parsing[1549316052104-result23]", "tests/test_datetime_parse.py::test_datetime_parsing[1549316052104324-result24]", "tests/test_datetime_parse.py::test_datetime_parsing[1549316052104324096-result25]", "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-result4]", "tests/test_datetime_parse.py::test_parse_durations[5:30-result5]", "tests/test_datetime_parse.py::test_parse_durations[10:15:30-result6]", "tests/test_datetime_parse.py::test_parse_durations[1:15:30-result7]", "tests/test_datetime_parse.py::test_parse_durations[100:200:300-result8]", "tests/test_datetime_parse.py::test_parse_durations[4", "tests/test_datetime_parse.py::test_parse_durations[15:30.1-result11]", "tests/test_datetime_parse.py::test_parse_durations[15:30.01-result12]", "tests/test_datetime_parse.py::test_parse_durations[15:30.001-result13]", "tests/test_datetime_parse.py::test_parse_durations[15:30.0001-result14]", "tests/test_datetime_parse.py::test_parse_durations[15:30.00001-result15]", "tests/test_datetime_parse.py::test_parse_durations[15:30.000001-result16]", "tests/test_datetime_parse.py::test_parse_durations[15:30.000001-result17]", "tests/test_datetime_parse.py::test_parse_durations[-4", "tests/test_datetime_parse.py::test_parse_durations[-172800-result19]", "tests/test_datetime_parse.py::test_parse_durations[-15:30-result20]", "tests/test_datetime_parse.py::test_parse_durations[-1:15:30-result21]", "tests/test_datetime_parse.py::test_parse_durations[-30.1-result22]", "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-result26]", "tests/test_datetime_parse.py::test_parse_durations[P0.5D-result27]", "tests/test_datetime_parse.py::test_parse_durations[PT5H-result28]", "tests/test_datetime_parse.py::test_parse_durations[PT5M-result29]", "tests/test_datetime_parse.py::test_parse_durations[PT5S-result30]", "tests/test_datetime_parse.py::test_parse_durations[PT0.000005S-result31]", "tests/test_datetime_parse.py::test_parse_durations[PT0.000005S-result32]", "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]" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2020-06-05 13:21:14+00:00
mit
4,745
pydantic__pydantic-1620
diff --git a/pydantic/env_settings.py b/pydantic/env_settings.py --- a/pydantic/env_settings.py +++ b/pydantic/env_settings.py @@ -23,14 +23,28 @@ class BaseSettings(BaseModel): Heroku and any 12 factor app design. """ - def __init__(__pydantic_self__, _env_file: Union[Path, str, None] = env_file_sentinel, **values: Any) -> None: + def __init__( + __pydantic_self__, + _env_file: Union[Path, str, None] = env_file_sentinel, + _env_file_encoding: Optional[str] = None, + **values: Any, + ) -> None: # Uses something other than `self` the first arg to allow "self" as a settable attribute - super().__init__(**__pydantic_self__._build_values(values, _env_file=_env_file)) - - def _build_values(self, init_kwargs: Dict[str, Any], _env_file: Union[Path, str, None] = None) -> Dict[str, Any]: - return deep_update(self._build_environ(_env_file), init_kwargs) - - def _build_environ(self, _env_file: Union[Path, str, None] = None) -> Dict[str, Optional[str]]: + super().__init__( + **__pydantic_self__._build_values(values, _env_file=_env_file, _env_file_encoding=_env_file_encoding) + ) + + def _build_values( + self, + init_kwargs: Dict[str, Any], + _env_file: Union[Path, str, None] = None, + _env_file_encoding: Optional[str] = None, + ) -> Dict[str, Any]: + return deep_update(self._build_environ(_env_file, _env_file_encoding), init_kwargs) + + def _build_environ( + self, _env_file: Union[Path, str, None] = None, _env_file_encoding: Optional[str] = None + ) -> Dict[str, Optional[str]]: """ Build environment variables suitable for passing to the Model. """ @@ -42,10 +56,16 @@ def _build_environ(self, _env_file: Union[Path, str, None] = None) -> Dict[str, env_vars = {k.lower(): v for k, v in os.environ.items()} env_file = _env_file if _env_file != env_file_sentinel else self.__config__.env_file + env_file_encoding = _env_file_encoding if _env_file_encoding is not None else self.__config__.env_file_encoding if env_file is not None: env_path = Path(env_file) if env_path.is_file(): - env_vars = {**read_env_file(env_path, case_sensitive=self.__config__.case_sensitive), **env_vars} + env_vars = { + **read_env_file( + env_path, encoding=env_file_encoding, case_sensitive=self.__config__.case_sensitive + ), + **env_vars, + } for field in self.__fields__.values(): env_val: Optional[str] = None @@ -68,6 +88,7 @@ def _build_environ(self, _env_file: Union[Path, str, None] = None) -> Dict[str, class Config: env_prefix = '' env_file = None + env_file_encoding = None validate_all = True extra = Extra.forbid arbitrary_types_allowed = True @@ -102,13 +123,13 @@ def prepare_field(cls, field: ModelField) -> None: __config__: Config # type: ignore -def read_env_file(file_path: Path, *, case_sensitive: bool = False) -> Dict[str, Optional[str]]: +def read_env_file(file_path: Path, *, encoding: str = None, case_sensitive: bool = False) -> Dict[str, Optional[str]]: try: from dotenv import dotenv_values except ImportError as e: raise ImportError('python-dotenv is not installed, run `pip install pydantic[dotenv]`') from e - file_vars: Dict[str, Optional[str]] = dotenv_values(file_path) + file_vars: Dict[str, Optional[str]] = dotenv_values(file_path, encoding=encoding) if not case_sensitive: return {k.lower(): v for k, v in file_vars.items()} else:
pydantic/pydantic
329b1d3e7b32bd72a4db2d122ef0e325c5725741
diff --git a/tests/test_settings.py b/tests/test_settings.py --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -320,7 +320,7 @@ class Settings(BaseSettings): foo: int bar: str - def _build_values(self, init_kwargs, _env_file): + def _build_values(self, init_kwargs, _env_file, _env_file_encoding): return {**init_kwargs, **self._build_environ()} env.set('BAR', 'env setting') @@ -340,7 +340,7 @@ class Settings(BaseSettings): b: str c: str - def _build_values(self, init_kwargs, _env_file): + def _build_values(self, init_kwargs, _env_file, _env_file_encoding): config_settings = init_kwargs.pop('__config_settings__') return {**config_settings, **init_kwargs, **self._build_environ()} @@ -430,6 +430,22 @@ class Config: assert s.c == 'best string' [email protected](not dotenv, reason='python-dotenv not installed') +def test_env_file_config_custom_encoding(tmp_path): + p = tmp_path / '.env' + p.write_text('pika=p!±@', encoding='latin-1') + + class Settings(BaseSettings): + pika: str + + class Config: + env_file = p + env_file_encoding = 'latin-1' + + s = Settings() + assert s.pika == 'p!±@' + + @pytest.mark.skipif(not dotenv, reason='python-dotenv not installed') def test_env_file_none(tmp_path): p = tmp_path / '.env' @@ -529,6 +545,21 @@ class Settings(BaseSettings): } [email protected](not dotenv, reason='python-dotenv not installed') +def test_env_file_custom_encoding(tmp_path): + p = tmp_path / '.env' + p.write_text('pika=p!±@', encoding='latin-1') + + class Settings(BaseSettings): + pika: str + + with pytest.raises(UnicodeDecodeError): + Settings(_env_file=str(p)) + + s = Settings(_env_file=str(p), _env_file_encoding='latin-1') + assert s.dict() == {'pika': 'p!±@'} + + @pytest.mark.skipif(dotenv, reason='python-dotenv is installed') def test_dotenv_not_installed(tmp_path): p = tmp_path / '.env'
Add encoding to `read_env_file()` # Feature Request Output of `import pydantic.utils; print(pydantic.utils.version_info())`: ``` pydantic version: 1.5.1 pydantic compiled: True python version: 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)] platform: Windows-7-6.1.7601-SP1 optional deps. installed: ['email-validator'] ``` ## Description Hi, there's known problem on Windows with parsing dotenv files - https://github.com/pypa/pipenv/issues/1963. `python-dotenv` would parse files with default encoding (cp1251 for Cyrillic Windows). As a result we get `Лист 1` instead of `Лист 1`. It looks like [this](https://github.com/samuelcolvin/pydantic/blob/960b24a5aab7ae0631bfbfbe0047b4d8600c6012/pydantic/env_settings.py#L111) function need to fetch encoding from `Config` class somehow. <!-- Where possible please include a self-contained code snippet describing your feature request: --> ## Example `.env` file (UTF-8): ``` foo=Лист 1 ``` Code snippet: ```py import pydantic class Settings(pydantic.BaseSettings): foo: str class Config: env_file_encoding = 'utf-8' settings = Settings(_env_file='.env') print(settings) # foo='Лист 1' ```
0.0
329b1d3e7b32bd72a4db2d122ef0e325c5725741
[ "tests/test_settings.py::test_env_takes_precedence", "tests/test_settings.py::test_config_file_settings_nornir", "tests/test_settings.py::test_env_file_config_custom_encoding", "tests/test_settings.py::test_env_file_custom_encoding" ]
[ "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_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_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_alias_set", "tests/test_settings.py::test_prefix_on_parent", "tests/test_settings.py::test_frozenset" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-06-09 11:21:23+00:00
mit
4,746
pydantic__pydantic-1630
diff --git a/pydantic/errors.py b/pydantic/errors.py --- a/pydantic/errors.py +++ b/pydantic/errors.py @@ -1,9 +1,12 @@ from decimal import Decimal from pathlib import Path -from typing import Any, Set, Type, Union +from typing import TYPE_CHECKING, Any, Callable, Set, Tuple, Type, Union from .typing import display_as_type +if TYPE_CHECKING: + from .typing import DictStrAny + # explicitly state exports to avoid "from .errors import *" also importing Decimal, Path etc. __all__ = ( 'PydanticTypeError', @@ -91,6 +94,17 @@ ) +def cls_kwargs(cls: Type['PydanticErrorMixin'], ctx: 'DictStrAny') -> 'PydanticErrorMixin': + """ + For built-in exceptions like ValueError or TypeError, we need to implement + __reduce__ to override the default behaviour (instead of __getstate__/__setstate__) + By default pickle protocol 2 calls `cls.__new__(cls, *args)`. + Since we only use kwargs, we need a little constructor to change that. + Note: the callable can't be a lambda as pickle looks in the namespace to find it + """ + return cls(**ctx) + + class PydanticErrorMixin: code: str msg_template: str @@ -101,6 +115,9 @@ def __init__(self, **ctx: Any) -> None: def __str__(self) -> str: return self.msg_template.format(**self.__dict__) + def __reduce__(self) -> Tuple[Callable[..., 'PydanticErrorMixin'], Tuple[Type['PydanticErrorMixin'], 'DictStrAny']]: + return cls_kwargs, (self.__class__, self.__dict__) + class PydanticTypeError(PydanticErrorMixin, TypeError): pass
pydantic/pydantic
5a2d78765a8b2cb5e0526efb50fd548d0d3bf98b
Surely as simple as implementing `__getstate__` and `__setstate__` on `ValidatoinError`? If it is that simple, PR welcome to implement it. I don't believe so. I did spend a few hours trying to do just that and couldn't get it to work. Iirc, the problem with that approach is that `__setstate__` isn't called until after the object's `__init__` is called. So the error has already occurred and you don't get a chance to fix things. Reading the pickle docs, it seemed like `__getnewargs_ex__` might be a way to get that to work but i failed at getting that to work too. I'm not sure, though, if i just didn't/don't understand getnewargs or if it turned out that exceptions are specialcased already and that specialcasing was interfering (in one of the python bug reports, ncoghlan noted that there were specialcases in exceptions which perhaps no longer worked with the new ways that picked worked) My python.org bug from earlier was a duplicate. I've closed it. This is the older bug: https://bugs.python.org/issue27015 There's a cpython PR which I confirmed would fix at least the mandatory keyword args. It is currently awaiting another review from a python core developer: https://github.com/python/cpython/pull/11580 Hi @abadger I just had a look at it and I think I have something working. I'm opening a PR! Please tell me if it works with your whole example
diff --git a/tests/test_errors.py b/tests/test_errors.py --- a/tests/test_errors.py +++ b/tests/test_errors.py @@ -1,3 +1,4 @@ +import pickle import sys from typing import Dict, List, Optional, Union from uuid import UUID, uuid4 @@ -6,6 +7,7 @@ from pydantic import UUID1, BaseConfig, BaseModel, PydanticTypeError, ValidationError, conint, errors, validator from pydantic.error_wrappers import flatten_errors, get_exc_type +from pydantic.errors import StrRegexError from pydantic.typing import Literal @@ -22,6 +24,17 @@ def __init__(self, *, test_ctx: int) -> None: assert str(exc_info.value) == 'test message template "test_value"' +def test_pydantic_error_pickable(): + """ + Pydantic errors should be (un)pickable. + (this test does not create a custom local error as we can't pickle local objects) + """ + p = pickle.dumps(StrRegexError(pattern='pika')) + error = pickle.loads(p) + assert isinstance(error, StrRegexError) + assert error.pattern == 'pika' + + @pytest.mark.skipif(not Literal, reason='typing_extensions not installed') def test_interval_validation_error(): class Foo(BaseModel):
Make ValidationError unpicklable # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.5.1 pydantic compiled: False install path: /home/badger/.cache/pypoetry/virtualenvs/antsibull-F3umzYPl-py3.8/lib/python3.8/site-packages/pydantic python version: 3.8.3 (default, Feb 26 2020, 00:00:00) [GCC 9.3.1 20200408 (Red Hat 9.3.1-2)] platform: Linux-5.6.15-200.fc31.x86_64-x86_64-with-glibc2.2.5 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: --> ## Use case I'm going to give you two code snippets because it might not be obvious from the simplest case why I would want to do it. A simple approximation of my use case is here: https://gist.github.com/abadger/bfd55741c281ccb534f7bbc8fe9b6202 I am trying to use pydantic to validate and normalize data from a large number of data sources I need to run each validation separately so that I can know which data sources are providing invalid data. I decided to split it up amongst multiple CPUs by using asyncio's run_in_executor with a ProcessPoolExecutor. However, when the pydantic.constr validation failed, I would get a BrokenProcessPool error on everything that had been queued but not run rather than a pydantic ValidationError on the specific task which failed. ## Root cause I was able to workaround the problem by catching the pydantic exception and raising a ValueError with all of the information I needed. This lead me to the root cause: pydantic errors are not **un**picklable. Because of that, the exception raised in the worker process is pickled there and sent back to the parent process. The parent process attempts to unpickle it, encounters the error, and then gives the generic, unhelpful BrokenProcessPool error and cancels the other pending tasks. Here's a reproducer for the root cause: ```python import pickle from pydantic.errors import StrRegexError p = pickle.dumps(StrRegexError(pattern='test')) print(pickle.loads(p)) # Traceback (most recent call last): # File "<stdin>", line 1, in <module> # TypeError: __init__() missing 1 required positional argument: 'pattern' ``` Looking at the python stdlib bugtracker there are many open bugs with interactions between pickle and exceptions. I didn't see this one so I added this: https://bugs.python.org/issue40917 Some others that might cause different bugs with pydantics exceptions: * https://bugs.python.org/issue32696 * https://bugs.python.org/issue30005 Given so many potential bugs, I'm not sure if this is solvable in pydantic code or has to wait for pickle fixes. However, if it's not solvable, adding my workaround and an explanation of what's happening to the docs would be nice. That way searching for pydantic, ProcessPoolExecutor, pickle, multiprocessing might save the next person some time wondering why only a portion of their data was being converted.
0.0
5a2d78765a8b2cb5e0526efb50fd548d0d3bf98b
[ "tests/test_errors.py::test_pydantic_error_pickable" ]
[ "tests/test_errors.py::test_pydantic_error", "tests/test_errors.py::test_interval_validation_error", "tests/test_errors.py::test_error_on_optional", "tests/test_errors.py::test_validation_error[errors-expected0]", "tests/test_errors.py::test_validation_error[json-[\\n", "tests/test_errors.py::test_validation_error[__str__-10", "tests/test_errors.py::test_errors_unknown_error_object", "tests/test_errors.py::test_get_exc_type[exc0-type_error]", "tests/test_errors.py::test_get_exc_type[exc1-value_error]", "tests/test_errors.py::test_get_exc_type[exc2-assertion_error]", "tests/test_errors.py::test_get_exc_type[exc3-value_error.decimal.not_finite]", "tests/test_errors.py::test_single_error", "tests/test_errors.py::test_nested_error", "tests/test_errors.py::test_validate_assignment_error", "tests/test_errors.py::test_submodel_override_validation_error", "tests/test_errors.py::test_validation_error_methods" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2020-06-13 22:24:06+00:00
mit
4,747
pydantic__pydantic-1658
diff --git a/pydantic/networks.py b/pydantic/networks.py --- a/pydantic/networks.py +++ b/pydantic/networks.py @@ -274,7 +274,6 @@ class PostgresDsn(AnyUrl): class RedisDsn(AnyUrl): allowed_schemes = {'redis'} - user_required = True def stricturl(
pydantic/pydantic
70d531ff4c1ae3980615cee07a948fe49b1bc7cf
I guess this code should be changed to require either a username or password: https://github.com/samuelcolvin/pydantic/blob/e3243d267b06bda2d7b2213a8bad70f82171033c/pydantic/networks.py#L191-L193 PR welcome to change this. The work around until that is fixed is to define your own `RedisDsn`: ```py class RedisDsn(AnyUrl): allowed_schemes = {'redis'} ``` E.g. without `user_required=True` Why this code should be changed? https://github.com/samuelcolvin/pydantic/blob/e3243d267b06bda2d7b2213a8bad70f82171033c/pydantic/networks.py#L191-L193 Can't we just remove `user_required=True` from RedisDsn? maybe, but it seems extremely rare that someone wants to login to a redis instance without either a username or password. Maybe we shouldn't change the code but simply update the docs to explain you might want to use your own custom `RedisDsn`. Given how easy it is to create your own, I'm concerned with catering to the 99% here. I think 99% of cases a redis server will require either a username or password. As far as I know, there is no username in Redis - only password can be set with `requirepass` config parameter, so `user_required=True` has no sense. But may be I dont understand how RedisDSN should be used... That is true I too didn't see any way that redis has user name. It only has password. If RedisDSN has parameter user_required=False then we can use the RedisDSN directly with aioredis. ```python redis = await aioredis.create_redis_pool( 'redis://:sEcRet@localhost/') ``` Okay, let's remove `user_required=False` from `RedisDsn`. PR welcome.
diff --git a/tests/test_networks.py b/tests/test_networks.py --- a/tests/test_networks.py +++ b/tests/test_networks.py @@ -324,10 +324,11 @@ class Model(BaseModel): Model(a='http://example.org') assert exc_info.value.errors()[0]['type'] == 'value_error.url.scheme' - with pytest.raises(ValidationError) as exc_info: - Model(a='redis://localhost:5432/app') - error = exc_info.value.errors()[0] - assert error == {'loc': ('a',), 'msg': 'userinfo required in URL but missing', 'type': 'value_error.url.userinfo'} + # password is not required for redis + m = Model(a='redis://localhost:5432/app') + assert m.a == 'redis://localhost:5432/app' + assert m.a.user is None + assert m.a.password is None def test_custom_schemes():
RedisDSN with out username # Question Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.4 pydantic compiled: True install path: /home/kesav/.virtualenvs/smtp/lib/python3.8/site-packages/pydantic python version: 3.8.0 (default, Oct 28 2019, 16:14:01) [GCC 9.2.1 20191008] platform: Linux-5.3.0-40-generic-x86_64-with-glibc2.29 optional deps. installed: [] ``` <!-- Where possible please include a self-contained code snippet describing your question: --> ```py import pydantic class AppSettings(pydantic.BaseSettings): redis_dsn: pydantic.RedisDsn = 'redis://:[email protected]' ``` My redis server has no user name only password it has. If I use above setting I get the following error: ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> File "pydantic/env_settings.py", line 28, in pydantic.env_settings.BaseSettings.__init__ File "pydantic/main.py", line 283, in pydantic.main.BaseModel.__init__ pydantic.error_wrappers.ValidationError: 1 validation error for Test redis_dsn userinfo required in URL but missing (type=value_error.url.userinfo) ``` How to use RedisDsn without user name?
0.0
70d531ff4c1ae3980615cee07a948fe49b1bc7cf
[ "tests/test_networks.py::test_redis_dsns" ]
[ "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+psycopg2://postgres:postgres@localhost:5432/hatch]", "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_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_parts", "tests/test_networks.py::test_url_repr", "tests/test_networks.py::test_ipv4_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_at_in_path", "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_postgres_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_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_test_patch": true, "is_lite": true }
2020-06-25 18:35:11+00:00
mit
4,748
pydantic__pydantic-1678
diff --git a/pydantic/errors.py b/pydantic/errors.py --- a/pydantic/errors.py +++ b/pydantic/errors.py @@ -27,6 +27,7 @@ 'UrlUserInfoError', 'UrlHostError', 'UrlHostTldError', + 'UrlPortError', 'UrlExtraError', 'EnumError', 'IntegerError', @@ -205,6 +206,11 @@ class UrlHostTldError(UrlError): msg_template = 'URL host invalid, top level domain required' +class UrlPortError(UrlError): + code = 'url.port' + msg_template = 'URL port invalid, port cannot exceed 65535' + + class UrlExtraError(UrlError): code = 'url.extra' msg_template = 'URL invalid, extra characters found after valid URL: {extra!r}' diff --git a/pydantic/networks.py b/pydantic/networks.py --- a/pydantic/networks.py +++ b/pydantic/networks.py @@ -185,9 +185,14 @@ def validate(cls, value: Any, field: 'ModelField', config: 'BaseConfig') -> 'Any scheme = parts['scheme'] if scheme is None: raise errors.UrlSchemeError() + if cls.allowed_schemes and scheme.lower() not in cls.allowed_schemes: raise errors.UrlSchemePermittedError(cls.allowed_schemes) + port = parts['port'] + if port is not None and int(port) > 65_535: + raise errors.UrlPortError() + user = parts['user'] if cls.user_required and user is None: raise errors.UrlUserInfoError() @@ -205,7 +210,7 @@ def validate(cls, value: Any, field: 'ModelField', config: 'BaseConfig') -> 'Any host=host, tld=tld, host_type=host_type, - port=parts['port'], + port=port, path=parts['path'], query=parts['query'], fragment=parts['fragment'],
pydantic/pydantic
259a1a0ff8eb9a0c4450331b9bae6730d55b9124
Is there a nice RFC explicitly stating a limit for port? If so I guess we could add a check, but this is not a bug, just a limit of the current validation. You can implement a much cleaner validator: ```py class Test(BaseModel): url: stricturl(allowed_schemes=['tcp']) @validator('url') def validate_port(cls, v): if int(v.port) > 2**16: raise ValueError('port overflow') return v ``` Hi, [rfc 793](https://tools.ietf.org/html/rfc793#section-3.1) explain ports are 16 unsigned bits Your validator will fail if port is missing, with tcp protocol that doesn't really make sense but with http(s) protocol is does: example `http://example.com` the validator will fail because v.port is None, int will raise a TypeError, but thanks for the tips I totally forgot port attribute 🤦 ```py class Test(BaseModel): url: stricturl(allowed_schemes=['tcp']) @validator('url') def validate_port(cls, v): if v.port is None: return v elif int(v.port) > 2**16: raise ValueError('port overflow') return v ``` (the tcp protocol is a bad showcase about default port) Good point, `if v.port is not None and int(v.port) > 2**16` would be better. (is `port=0` allowed?) > rfc 793 explain ports are 16 unsigned bits PR welcome to add this check to all URL validation, I know technically it's a breaking chance, but I think a reasonable one, given that a higher port is invalid anyway. the port 0 is tagged as reserved and should not be usable as such since most routers will reject it. In a other hand in a lot of APIs port 0 mean "use the first avaiable socket" so I would say yes. I'll work on a PR within a few days (this weekend I hope if I have time) makes sense to allow 0, also makes the check easier. > I'll work on a PR within a few days (this weekend I hope if I have time) Thanks so much I'm currently working on a PR, looking at the sources of networks I have few questions about some design choices Should I open news issues for each or asking here is fine ?
diff --git a/tests/test_networks.py b/tests/test_networks.py --- a/tests/test_networks.py +++ b/tests/test_networks.py @@ -94,6 +94,7 @@ class Model(BaseModel): {'extra': ':db8::ff00:42:8329'}, ), ('http://[192.168.1.1]:8329', 'value_error.url.host', 'URL host invalid', None), + ('http://example.com:99999', 'value_error.url.port', 'URL port invalid, port cannot exceed 65535', None), ], ) def test_any_url_invalid(value, err_type, err_msg, err_ctx):
Url type port limit not checked ``` pydantic version: 1.5.1 pydantic compiled: False install path: /opt/fastapi/backend/venv/lib/python3.8/site-packages/pydantic python version: 3.8.3 (default, Jun 21 2020, 00:03:19) [GCC 8.3.0] platform: Linux-4.19.0-9-amd64-x86_64-with-glibc2.28 optional deps. installed: ['email-validator'] ``` Hi, The port limit is not checked by URLs types: ```py >>> from pydantic import BaseModel, stricturl >>> class Test(BaseModel): url: stricturl(allowed_schemes=["tcp"]) >>> Test(url="tcp://127.0.0.1:100000000000000000000000000000") Test(url=UrlValue('tcp://127.0.0.1:100000000000000000000000000000', scheme='tcp', host='127.0.0.1', host_type='ipv4', port='100000000000000000000000000000')) ``` Excepted result: raise an error, my current workaround ```py >>> from pydantic import BaseModel, stricturl, validator >>> from pydantic.networks import url_regex >>> class Test(BaseModel): url: stricturl(allowed_schemes=["tcp"]) @validator("url") def validate_port(cls, v): port = url_regex().match(v).group("port") if port is None: return v if int(port) > 2**16: raise ValueError("port overflow") return v >>> Test(url="tcp://127.0.0.1:900000") Traceback (most recent call last): File "<pyshell#84>", line 1, in <module> Test(url="tcp://127.0.0.1:900000") File "pydantic\main.py", line 338, in pydantic.main.BaseModel.__init__ pydantic.error_wrappers.ValidationError: 1 validation error for Test url port overflow (type=value_error) ```
0.0
259a1a0ff8eb9a0c4450331b9bae6730d55b9124
[ "tests/test_networks.py::test_any_url_invalid[http://example.com:99999-value_error.url.port-URL" ]
[ "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+psycopg2://postgres:postgres@localhost:5432/hatch]", "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_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_parts", "tests/test_networks.py::test_url_repr", "tests/test_networks.py::test_ipv4_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_at_in_path", "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_postgres_dsns", "tests/test_networks.py::test_redis_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_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_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-07-02 14:47:48+00:00
mit
4,749
pydantic__pydantic-1686
diff --git a/pydantic/generics.py b/pydantic/generics.py --- a/pydantic/generics.py +++ b/pydantic/generics.py @@ -1,4 +1,19 @@ -from typing import TYPE_CHECKING, Any, ClassVar, Dict, Tuple, Type, TypeVar, Union, cast, get_type_hints +import sys +from types import FrameType, ModuleType +from typing import ( + TYPE_CHECKING, + Any, + Callable, + ClassVar, + Dict, + Optional, + Tuple, + Type, + TypeVar, + Union, + cast, + get_type_hints, +) from .class_validators import gather_all_validators from .fields import FieldInfo, ModelField @@ -45,17 +60,27 @@ def __class_getitem__(cls: Type[GenericModelT], params: Union[Type[Any], Tuple[T model_name = cls.__concrete_name__(params) validators = gather_all_validators(cls) fields = _build_generic_fields(cls.__fields__, concrete_type_hints, typevars_map) + model_module = get_caller_module_name() or cls.__module__ created_model = cast( Type[GenericModel], # casting ensures mypy is aware of the __concrete__ and __parameters__ attributes create_model( model_name, - __module__=cls.__module__, + __module__=model_module, __base__=cls, __config__=None, __validators__=validators, **fields, ), ) + + if is_call_from_module(): # create global reference and therefore allow pickling + object_in_module = sys.modules[model_module].__dict__.setdefault(model_name, created_model) + if object_in_module is not created_model: + # this should not ever happen because of _generic_types_cache, but just in case + raise TypeError(f'{model_name!r} already defined above, please consider reusing it') from NameError( + f'Name conflict: {model_name!r} in {model_module!r} is already used by {object_in_module!r}' + ) + created_model.Config = cls.Config concrete = all(not _is_typevar(v) for v in concrete_type_hints.values()) created_model.__concrete__ = concrete @@ -114,3 +139,36 @@ def _parameterize_generic_field(field_type: Type[Any], typevars_map: Dict[TypeVa def _is_typevar(v: Any) -> bool: return isinstance(v, TypeVar) + + +def get_caller_module_name() -> Optional[str]: + """ + Used inside a function to get its caller module name + + Will only work against non-compiled code, therefore used only in pydantic.generics + """ + import inspect + + try: + previous_caller_frame = inspect.stack()[2].frame + except IndexError as e: + raise RuntimeError('This function must be used inside another function') from e + + getmodule = cast(Callable[[FrameType, str], Optional[ModuleType]], inspect.getmodule) + previous_caller_module = getmodule(previous_caller_frame, previous_caller_frame.f_code.co_filename) + return previous_caller_module.__name__ if previous_caller_module is not None else None + + +def is_call_from_module() -> bool: + """ + Used inside a function to check whether it was called globally + + Will only work against non-compiled code, therefore used only in pydantic.generics + """ + import inspect + + try: + previous_caller_frame = inspect.stack()[2].frame + except IndexError as e: + raise RuntimeError('This function must be used inside another function') from e + return previous_caller_frame.f_locals is previous_caller_frame.f_globals diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -803,7 +803,7 @@ def create_model( *, __config__: Type[BaseConfig] = None, __base__: Type[BaseModel] = None, - __module__: Optional[str] = None, + __module__: str = __name__, __validators__: Dict[str, classmethod] = None, **field_definitions: Any, ) -> Type[BaseModel]: @@ -812,8 +812,9 @@ def create_model( :param __model_name: name of the created model :param __config__: config class to use for the new model :param __base__: base class for the new model to inherit from + :param __module__: module of the created model :param __validators__: a dict of method names and @validator class methods - :param **field_definitions: fields of the model (or extra fields if a base is supplied) + :param field_definitions: fields of the model (or extra fields if a base is supplied) in the format `<name>=(<type>, <default default>)` or `<name>=<default value>, e.g. `foobar=(str, ...)` or `foobar=123`, or, for complex use-cases, in the format `<name>=<FieldInfo>`, e.g. `foo=Field(default_factory=datetime.utcnow, alias='bar')`
pydantic/pydantic
29e3877a448e9cb37e058c0a1e10e47a61676b18
diff --git a/tests/conftest.py b/tests/conftest.py --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,10 +1,38 @@ +import inspect import os import secrets +import subprocess +import sys +import textwrap from importlib.machinery import SourceFileLoader +from types import FunctionType import pytest +def _extract_source_code_from_function(function): + if function.__code__.co_argcount: + raise RuntimeError(f'function {function.__qualname__} cannot have any arguments') + + code_lines = '' + body_started = False + for line in textwrap.dedent(inspect.getsource(function)).split('\n'): + if line.startswith('def '): + body_started = True + continue + elif body_started: + code_lines += f'{line}\n' + + return textwrap.dedent(code_lines) + + +def _create_module(code, tmp_path, name): + name = f'{name}_{secrets.token_hex(5)}' + path = tmp_path / f'{name}.py' + path.write_text(code) + return name, path + + class SetEnv: def __init__(self): self.envars = set() @@ -28,11 +56,37 @@ def env(): @pytest.fixture -def create_module(tmp_path): - def run(code): - name = f'test_code_{secrets.token_hex(5)}' - path = tmp_path / f'{name}.py' - path.write_text(code) +def create_module(tmp_path, request): + def run(module_source_code=None): + """ + Creates module and loads it with SourceFileLoader().load_module() + """ + if isinstance(module_source_code, FunctionType): + module_source_code = _extract_source_code_from_function(module_source_code) + name, path = _create_module(module_source_code, tmp_path, request.node.name) return SourceFileLoader(name, str(path)).load_module() return run + + [email protected] +def run_as_module(tmp_path, request): + def run(module_source_code=None): + """ + Creates module source and runs it in subprocess + + This way is much slower than SourceFileLoader().load_module(), + but executes module as __main__ with a clear stack (https://docs.python.org/3/library/__main__.html) + """ + if isinstance(module_source_code, FunctionType): + module_source_code = _extract_source_code_from_function(module_source_code) + _, path = _create_module(module_source_code, tmp_path, request.node.name) + result = subprocess.run([sys.executable, str(path)], stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=5) + if result.returncode != 0: + pytest.fail( + f'Running {path} failed with non-zero return code: {result.returncode}\n' + f'Captured stdout:\n{result.stdout.decode()}\n' + f'Captured stderr:\n{result.stderr.decode()}' + ) + + return run 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 @@ -11,6 +11,7 @@ def test_create_model(): assert model.__fields__.keys() == {'foo', 'bar'} assert model.__validators__ == {} assert model.__config__.__name__ == 'Config' + assert model.__module__ == 'pydantic.main' def test_create_model_usage(): @@ -24,6 +25,29 @@ def test_create_model_usage(): model(foo='hello', bar='xxx') +def test_create_model_pickle(create_module): + """ + Pickle will work for dynamically created model only if it was defined globally with its class name + and module where it's defined was specified + """ + + @create_module + def module(): + import pickle + + from pydantic import create_model + + FooModel = create_model('FooModel', foo=(str, ...), bar=123, __module__=__name__) + + m = FooModel(foo='hello') + d = pickle.dumps(m) + m2 = pickle.loads(d) + assert m2.foo == m.foo == 'hello' + assert m2.bar == m.bar == 123 + assert m2 == m + assert m2 is not m + + def test_invalid_name(): with pytest.warns(RuntimeWarning): model = create_model('FooModel', _foo=(str, ...)) 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 @@ -472,3 +472,15 @@ class Filter(BaseModel): ) Filter = module.Filter assert isinstance(Filter(p={'sort': 'some_field:asc', 'fields': []}), Filter) + + +def test_forward_ref_with_create_model(create_module): + @create_module + def module(): + import pydantic + + Sub = pydantic.create_model('Sub', foo='bar', __module__=__name__) + assert Sub # get rid of "local variable 'Sub' is assigned to but never used" + Main = pydantic.create_model('Main', sub=('Sub', ...), __module__=__name__) + instance = Main(sub={}) + assert instance.sub.dict() == {'foo': 'bar'} diff --git a/tests/test_generics.py b/tests/test_generics.py --- a/tests/test_generics.py +++ b/tests/test_generics.py @@ -5,7 +5,7 @@ import pytest from pydantic import BaseModel, Field, ValidationError, root_validator, validator -from pydantic.generics import GenericModel, _generic_types_cache +from pydantic.generics import GenericModel, _generic_types_cache, get_caller_module_name skip_36 = pytest.mark.skipif(sys.version_info < (3, 7), reason='generics only supported for python 3.7 and above') @@ -412,7 +412,6 @@ class MyModel(GenericModel, Generic[T]): @skip_36 def test_child_schema(): - T = TypeVar('T') class Model(GenericModel, Generic[T]): @@ -599,3 +598,168 @@ class Model(GenericModel, Generic[AT, BT]): {'loc': ('a',), 'msg': 'none is not an allowed value', 'type': 'type_error.none.not_allowed'}, {'loc': ('b',), 'msg': 'none is not an allowed value', 'type': 'type_error.none.not_allowed'}, ] + + +@skip_36 +def test_generic_model_pickle(create_module): + # Using create_module because pickle doesn't support + # objects with <locals> in their __qualname__ (e. g. defined in function) + @create_module + def module(): + import pickle + from typing import Generic, TypeVar + + from pydantic import BaseModel + from pydantic.generics import GenericModel + + t = TypeVar('t') + + class Model(BaseModel): + a: float + b: int = 10 + + class MyGeneric(GenericModel, Generic[t]): + value: t + + original = MyGeneric[Model](value=Model(a='24')) + dumped = pickle.dumps(original) + loaded = pickle.loads(dumped) + assert loaded.value.a == original.value.a == 24 + assert loaded.value.b == original.value.b == 10 + assert loaded == original + + +@skip_36 +def test_generic_model_from_function_pickle_fail(create_module): + @create_module + def module(): + import pickle + from typing import Generic, TypeVar + + import pytest + + from pydantic import BaseModel + from pydantic.generics import GenericModel + + t = TypeVar('t') + + class Model(BaseModel): + a: float + b: int = 10 + + class MyGeneric(GenericModel, Generic[t]): + value: t + + def get_generic(t): + return MyGeneric[t] + + original = get_generic(Model)(value=Model(a='24')) + with pytest.raises(pickle.PicklingError): + pickle.dumps(original) + + +@skip_36 +def test_generic_model_redefined_without_cache_fail(create_module): + @create_module + def module(): + from typing import Generic, TypeVar + + import pytest + + from pydantic.generics import GenericModel, _generic_types_cache + + t = TypeVar('t') + + class MyGeneric(GenericModel, Generic[t]): + value: t + + concrete = MyGeneric[t] + _generic_types_cache.clear() + with pytest.raises( + TypeError, match=r"'MyGeneric\[t\]' already defined above, please consider reusing it" + ) as exc_info: + MyGeneric[t] + + cause = exc_info.value.__cause__ + assert isinstance(cause, NameError), cause + expected_message = f"Name conflict: 'MyGeneric[t]' in {__name__!r} is already used by {concrete!r}" + assert cause.args[0] == expected_message, f'{cause.args[0]} != {expected_message}' + + +def test_get_caller_module_name_from_function(): + def get_current_module_name(): + return get_caller_module_name() + + assert get_current_module_name() == __name__ + + +def test_get_caller_module_name_from_module(create_module): + @create_module + def module(): + from pydantic.generics import get_caller_module_name + + def get_current_module_name(): + return get_caller_module_name() + + module_name = get_current_module_name() + assert module_name == __name__, f'{module_name} != {__name__}' + + def get_current_module_name(): + return get_caller_module_name() + + assert get_current_module_name() == __name__ + + +def test_get_caller_module_name_not_found(mocker): + mocker.patch('inspect.getmodule', return_value=None) + assert get_caller_module_name() is None + + +def test_is_call_from_module(create_module): + @create_module + def module(): + from pydantic.generics import is_call_from_module + + def function(): + assert is_call_from_module() + + another_function() + + def another_function(): + assert not is_call_from_module() + third_function() + + def third_function(): + assert not is_call_from_module() + + function() + + +def test_is_call_from_module_called_in_module(run_as_module): + @run_as_module + def module(): + import pytest + + from pydantic.generics import is_call_from_module + + with pytest.raises(RuntimeError, match='This function must be used inside another function') as exc_info: + is_call_from_module() + + e = exc_info.value + assert isinstance(e.__cause__, IndexError), e.__cause__ + assert isinstance(e.__context__, IndexError), e.__context__ + + +def test_get_caller_module_called_from_module(run_as_module): + @run_as_module + def module(): + import pytest + + from pydantic.generics import get_caller_module_name + + with pytest.raises(RuntimeError, match='This function must be used inside another function') as exc_info: + get_caller_module_name() + + e = exc_info.value + assert isinstance(e.__cause__, IndexError), e.__cause__ + assert isinstance(e.__context__, IndexError), e.__context__
Dynamically create_model that contains forward refs # Question Hi, I am asking this as a question but I feel it could be a bug. In my usecase I actually get type declarations (potentially with cycle deplendencies, optional, ...) dynamically at runtime. I am building a static dict of those types and when it is ready, I will create the models with `create_model()` and apply `update_froward_refs()`. 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.5.1 pydantic compiled: True install path: /Users/A492YC/.virtualenvs/sam-quote-ujUy7lE3/lib/python3.7/site-packages/pydantic python version: 3.7.4 (default, Feb 17 2020, 12:06:24) [Clang 11.0.0 (clang-1100.0.33.17)] platform: Darwin-19.4.0-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 question hasn't already been answered. --> <!-- Where possible please include a self-contained code snippet describing your question: --> I think that this type dict would be enough to play the role of localns. But apparently, the function call `update_froward_refs()` fails because such models do not have `cls.__module__` A simplified implementation: ```py import pydantic test_types = { 'Sub': { "name": (str, ...), "param": (str, ...) }, 'Main': { "name": (str, ...), "male": (bool, ...), "sub": ("Sub", ...) } } sub = test_types["Sub"] sub_model = pydantic.create_model("Sub", **sub) sub_instance = sub_model(**{ "name": "hello", "param": "there" }) main = test_types["Main"] main_model = pydantic.create_model("Main", **main) main_instance = main_model(**{ "name": "world", "male": True, "sub": { "name": "hello", "param": "there" } }) # Traceback (most recent call last): # File "<input>", line 31, in <module> # File "pydantic/main.py", line 336, in pydantic.main.BaseModel.__init__ # File "pydantic/main.py", line 861, in pydantic.main.validate_model # pydantic.errors.ConfigError: field "sub" not yet prepared so type is still a ForwardRef, you might need to call Main.update_forward_refs(). ``` Because of the error above, I instead try to update_forward_refs on my dynamic model ```py main_model.update_forward_refs(Sub=sub_model) # Traceback (most recent call last): # File "<input>", line 1, in <module> # File "pydantic/main.py", line 663, in pydantic.main.BaseModel.update_forward_refs # KeyError: None ``` Could you provide a way to implement this if I am missing something?
0.0
29e3877a448e9cb37e058c0a1e10e47a61676b18
[ "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_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_forward_ref.py::test_forward_ref_with_field", "tests/test_forward_ref.py::test_forward_ref_with_create_model", "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_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", "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_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_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_module_name_from_function", "tests/test_generics.py::test_get_caller_module_name_from_module", "tests/test_generics.py::test_get_caller_module_name_not_found", "tests/test_generics.py::test_is_call_from_module" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-07-05 16:04:19+00:00
mit
4,750
pydantic__pydantic-1755
diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -215,7 +215,6 @@ def __new__(mcs, name, bases, namespace, **kwargs): # noqa C901 fields: Dict[str, ModelField] = {} config = BaseConfig validators: 'ValidatorListDict' = {} - fields_defaults: Dict[str, Any] = {} pre_root_validators, post_root_validators = [], [] for base in reversed(bases): @@ -231,9 +230,6 @@ def __new__(mcs, name, bases, namespace, **kwargs): # noqa C901 vg = ValidatorGroup(validators) for f in fields.values(): - if not f.required: - fields_defaults[f.name] = f.default - f.set_config(config) extra_validators = vg.get_validators(f.name) if extra_validators: @@ -267,8 +263,6 @@ def __new__(mcs, name, bases, namespace, **kwargs): # noqa C901 class_validators=vg.get_validators(ann_name), config=config, ) - if not inferred.required: - fields_defaults[ann_name] = inferred.default for var_name, value in namespace.items(): if ( @@ -291,8 +285,6 @@ def __new__(mcs, name, bases, namespace, **kwargs): # noqa C901 f'if you wish to change the type of this field, please use a type annotation' ) fields[var_name] = inferred - if not inferred.required: - fields_defaults[var_name] = inferred.default _custom_root_type = ROOT_KEY in fields if _custom_root_type: @@ -307,7 +299,6 @@ def __new__(mcs, name, bases, namespace, **kwargs): # noqa C901 new_namespace = { '__config__': config, '__fields__': fields, - '__field_defaults__': fields_defaults, '__validators__': vg.validators, '__pre_root_validators__': unique_list(pre_root_validators + pre_rv_new), '__post_root_validators__': unique_list(post_root_validators + post_rv_new), @@ -327,7 +318,6 @@ class BaseModel(Representation, 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[Tuple[bool, AnyCallable]] @@ -528,7 +518,10 @@ def construct(cls: Type['Model'], _fields_set: Optional['SetStr'] = None, **valu Default values are respected, but no other validation is performed. """ m = cls.__new__(cls) - object.__setattr__(m, '__dict__', {**smart_deepcopy(cls.__field_defaults__), **values}) + # default field values + fields_values = {name: field.get_default() for name, field in cls.__fields__.items() if not field.required} + fields_values.update(values) + object.__setattr__(m, '__dict__', fields_values) if _fields_set is None: _fields_set = set(values.keys()) object.__setattr__(m, '__fields_set__', _fields_set) @@ -718,7 +711,7 @@ def _iter( if ( (allowed_keys is not None and field_key not in allowed_keys) or (exclude_none and v is None) - or (exclude_defaults and self.__field_defaults__.get(field_key, _missing) == v) + or (exclude_defaults and getattr(self.__fields__.get(field_key), 'default', _missing) == v) ): continue if by_alias and field_key in self.__fields__:
pydantic/pydantic
e8326f899e037904a8e47928e4eedec6a56cf5ef
Hi @zoopp, Well we made some changes on `default_factory` to avoid calling it for nothing and avoid some side effects in #1504 and #1712 But [this line](https://github.com/samuelcolvin/pydantic/pull/1504/files#diff-1ef405a6b5a2fa9f20ea7e1f92e4c38eR299) changes the default value that used to be set in v1.5.1 hence the `None`. You could just use `Model()` instead of `Model.construct()` to fix this issue in the meantime. I don't know what we really want in term of behaviour to - avoid calling `default_factory` when not needed - still have meaningful default values with `construct` Thank you for the reply @PrettyWood, It's okay, I can work around the issue until a consensus is reached on what the behavior should be. Speaking from my point of view, or more generally from a user of the library's point of view, I would say it would make sense that if `construct` initializes fields with default values then it should initialize fields with `default_factory` as well. Would it make sense to call the factories inside the `construct` method as needed? @zoopp I'll try to work on this bug soon. I agree the behaviour should be the same as calling `Model.__init__` in term of fields and set values. There is a very easy fix but it's quite ugly and I'd like to take a bit more time to see if we can find a cleaner solution
diff --git a/tests/test_construction.py b/tests/test_construction.py --- a/tests/test_construction.py +++ b/tests/test_construction.py @@ -3,7 +3,7 @@ import pytest -from pydantic import BaseModel +from pydantic import BaseModel, Field class Model(BaseModel): @@ -275,3 +275,13 @@ class X(BaseModel): # deep['deep_thing'] gets modified assert x.deep['deep_thing'] == [1, 2, 3] assert y.deep['deep_thing'] == [1, 2, 3] + + +def test_construct_default_factory(): + class Model(BaseModel): + foo: List[int] = Field(default_factory=list) + bar: str = 'Baz' + + m = Model.construct() + assert m.foo == [] + assert m.bar == 'Baz'
BaseModel.construct returns instances with None assigned to fields with a default_factory # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.6.1 pydantic compiled: True install path: /home/mihai/.virtualenvs/pydantic/lib/python3.8/site-packages/pydantic python version: 3.8.3 (default, May 17 2020, 18:15:42) [GCC 10.1.0] platform: Linux-5.7.7-1-ck-x86_64-with-glibc2.2.5 optional deps. installed: ['devtools'] ``` ```py from pydantic import BaseModel, Field from typing import List class Model(BaseModel): foo: List[int] = Field(default_factory=list) bar: str = 'Baz' print(Model.construct()) # in pydantic 1.5.1 the result is: foo=[] bar='Baz' # in pydantic ^1.6.0 the result is: foo=None bar='Baz' ``` Hello, I'm using pydantic in an application and after updating to v1.6.1 from v1.5.1 I came across this situation which results in a couple of failures. From the changelog and documentation it's not clear if this change was intended or not.
0.0
e8326f899e037904a8e47928e4eedec6a56cf5ef
[ "tests/test_construction.py::test_construct_default_factory" ]
[ "tests/test_construction.py::test_simple_construct", "tests/test_construction.py::test_construct_misuse", "tests/test_construction.py::test_construct_fields_set", "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_construction.py::test_shallow_copy_modify" ]
{ "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-07-22 22:03:33+00:00
mit
4,751
pydantic__pydantic-1804
diff --git a/pydantic/env_settings.py b/pydantic/env_settings.py --- a/pydantic/env_settings.py +++ b/pydantic/env_settings.py @@ -58,7 +58,7 @@ def _build_environ( env_file = _env_file if _env_file != env_file_sentinel else self.__config__.env_file env_file_encoding = _env_file_encoding if _env_file_encoding is not None else self.__config__.env_file_encoding if env_file is not None: - env_path = Path(env_file) + env_path = Path(env_file).expanduser() if env_path.is_file(): env_vars = { **read_env_file(
pydantic/pydantic
094da94da9fab5be4b167c1da46a7848e3fba8d6
diff --git a/tests/test_settings.py b/tests/test_settings.py --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -1,4 +1,6 @@ import os +import uuid +from pathlib import Path from typing import Dict, List, Optional, Set import pytest @@ -547,6 +549,28 @@ class Config: assert s.pika == 'p!±@' [email protected] +def home_tmp(): + tmp_filename = f'{uuid.uuid4()}.env' + home_tmp_path = Path.home() / tmp_filename + yield home_tmp_path, tmp_filename + home_tmp_path.unlink() + + [email protected](not dotenv, reason='python-dotenv not installed') +def test_env_file_home_directory(home_tmp): + home_tmp_path, tmp_filename = home_tmp + home_tmp_path.write_text('pika=baz') + + class Settings(BaseSettings): + pika: str + + class Config: + env_file = f'~/{tmp_filename}' + + assert Settings().pika == 'baz' + + @pytest.mark.skipif(not dotenv, reason='python-dotenv not installed') def test_env_file_none(tmp_path): p = tmp_path / '.env'
Can't use ~ in dotenv file in Settings @HenryDashwood The issue here is that you use `~/.env`, which is not directly resolved by `pathlib.Path`. You could change it to ```python class Config: env_file = os.path.expanduser('~/.env') ``` Maybe we could add `expanduser` directly in the code when `env_path` is created _Originally posted by @PrettyWood in https://github.com/samuelcolvin/pydantic/issues/1368#issuecomment-669312462_
0.0
094da94da9fab5be4b167c1da46a7848e3fba8d6
[ "tests/test_settings.py::test_env_file_home_directory" ]
[ "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_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_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_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" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2020-08-06 01:41:50+00:00
mit
4,752
pydantic__pydantic-1814
diff --git a/pydantic/datetime_parse.py b/pydantic/datetime_parse.py --- a/pydantic/datetime_parse.py +++ b/pydantic/datetime_parse.py @@ -16,23 +16,21 @@ """ import re from datetime import date, datetime, time, timedelta, timezone -from typing import Dict, Union +from typing import Dict, Optional, Type, Union from . import errors -date_re = re.compile(r'(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})$') - -time_re = re.compile( - r'(?P<hour>\d{1,2}):(?P<minute>\d{1,2})(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6})\d{0,6})?)?' -) - -datetime_re = re.compile( - r'(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})' - r'[T ](?P<hour>\d{1,2}):(?P<minute>\d{1,2})' +date_expr = r'(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})' +time_expr = ( + r'(?P<hour>\d{1,2}):(?P<minute>\d{1,2})' r'(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6})\d{0,6})?)?' r'(?P<tzinfo>Z|[+-]\d{2}(?::?\d{2})?)?$' ) +date_re = re.compile(f'{date_expr}$') +time_re = re.compile(time_expr) +datetime_re = re.compile(f'{date_expr}[T ]{time_expr}') + standard_duration_re = re.compile( r'^' r'(?:(?P<days>-?\d+) (days?, )?)?' @@ -81,6 +79,22 @@ def from_unix_seconds(seconds: Union[int, float]) -> datetime: return dt.replace(tzinfo=timezone.utc) +def _parse_timezone(value: Optional[str], error: Type[Exception]) -> Union[None, int, timezone]: + if value == 'Z': + return timezone.utc + elif value is not None: + offset_mins = int(value[-2:]) if len(value) > 3 else 0 + offset = 60 * int(value[1:3]) + offset_mins + if value[0] == '-': + offset = -offset + try: + return timezone(timedelta(minutes=offset)) + except ValueError: + raise error() + else: + return None + + def parse_date(value: Union[date, StrBytesIntFloat]) -> date: """ Parse a date/int/float/string and return a datetime.date. @@ -117,8 +131,6 @@ def parse_time(value: Union[time, StrBytesIntFloat]) -> time: """ Parse a time/string and return a datetime.time. - This function doesn't support time zone offsets. - Raise ValueError if the input is well formatted but not a valid time. Raise ValueError if the input isn't well formatted, in particular if it contains an offset. """ @@ -143,7 +155,9 @@ def parse_time(value: Union[time, StrBytesIntFloat]) -> time: if kw['microsecond']: kw['microsecond'] = kw['microsecond'].ljust(6, '0') - kw_ = {k: int(v) for k, v in kw.items() if v is not None} + tzinfo = _parse_timezone(kw.pop('tzinfo'), errors.TimeError) + kw_: Dict[str, Union[None, int, timezone]] = {k: int(v) for k, v in kw.items() if v is not None} + kw_['tzinfo'] = tzinfo try: return time(**kw_) # type: ignore @@ -179,19 +193,8 @@ def parse_datetime(value: Union[datetime, StrBytesIntFloat]) -> datetime: if kw['microsecond']: kw['microsecond'] = kw['microsecond'].ljust(6, '0') - tzinfo_str = kw.pop('tzinfo') - if tzinfo_str == 'Z': - tzinfo = timezone.utc - elif tzinfo_str is not None: - offset_mins = int(tzinfo_str[-2:]) if len(tzinfo_str) > 3 else 0 - offset = 60 * int(tzinfo_str[1:3]) + offset_mins - if tzinfo_str[0] == '-': - offset = -offset - tzinfo = timezone(timedelta(minutes=offset)) - else: - tzinfo = None - - kw_: Dict[str, Union[int, timezone]] = {k: int(v) for k, v in kw.items() if v is not None} + tzinfo = _parse_timezone(kw.pop('tzinfo'), errors.DateTimeError) + kw_: Dict[str, Union[None, int, timezone]] = {k: int(v) for k, v in kw.items() if v is not None} kw_['tzinfo'] = tzinfo try:
pydantic/pydantic
4bc4230df6294c62667fc3779328019a28912147
This sounds like a bug, but it might need to wait for v2 to be fixed since it could be considered a breaking change. I have a fix for this, duplicating the datetime's method of handling timedeltas. The rest of the module doesn't seem refactored to reduce duplicated code. I assume this change is is okay / better by keeping it that way? This is my work so far: https://github.com/samuelcolvin/pydantic/commit/1d59058a2ae6f4b0f2f119b8eddc1529c5789d86
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 @@ -65,12 +65,20 @@ def test_date_parsing(value, result): (3610, time(1, 0, 10)), (3600.5, time(1, 0, 0, 500000)), (86400 - 1, time(23, 59, 59)), + ('11:05:00-05:30', time(11, 5, 0, tzinfo=create_tz(-330))), + ('11:05:00-0530', time(11, 5, 0, tzinfo=create_tz(-330))), + ('11:05:00Z', time(11, 5, 0, tzinfo=timezone.utc)), + ('11:05:00+00', time(11, 5, 0, tzinfo=timezone.utc)), + ('11:05-06', time(11, 5, 0, tzinfo=create_tz(-360))), + ('11:05+06', time(11, 5, 0, tzinfo=create_tz(360))), # Invalid inputs (86400, errors.TimeError), ('xxx', errors.TimeError), ('091500', errors.TimeError), (b'091500', errors.TimeError), ('09:15:90', errors.TimeError), + ('11:05:00Y', errors.TimeError), + ('11:05:00-25:00', errors.TimeError), ], ) def test_time_parsing(value, result): @@ -108,6 +116,7 @@ def test_time_parsing(value, result): # Invalid inputs ('x20120423091500', errors.DateTimeError), ('2012-04-56T09:15:90', errors.DateTimeError), + ('2012-04-23T11:05:00-25:00', errors.DateTimeError), (19_999_999_999, datetime(2603, 10, 11, 11, 33, 19, tzinfo=timezone.utc)), # just before watershed (20_000_000_001, datetime(1970, 8, 20, 11, 33, 20, 1000, tzinfo=timezone.utc)), # just after watershed (1_549_316_052, datetime(2019, 2, 4, 21, 34, 12, 0, tzinfo=timezone.utc)), # nowish in s
time ignores timedelta without error # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.5.1 pydantic compiled: True install path: C:\...\.venv37\Lib\site-packages\pydantic python version: 3.7.6 (tags/v3.7.6:43364a7ae0, Dec 19 2019, 00:42:30) [MSC v.1916 64 bit (AMD64)] platform: Windows-10-10.0.17134-SP0 optional deps. installed: ['typing-extensions'] ``` In the documentation at https://pydantic-docs.helpmanual.io/usage/types/#datetime-types it is stated that > - time fields can be: > - time, existing time object > - str, following formats work: > - HH:MM[:SS[.ffffff]] but as shown in the example below strings like `11:05+05:00` - are accepted and raise no error - loose the timedelta information Loosing information (especially timedelta) without recognition can e.g. lead to discrepancies when collecting data from different sources and a relationship between single pieces of data must be established based on a timestamp. I tried to track it down to the root cause: ```py >>> from pydantic import datetime_parse >>> incorrect_time = datetime_parse.parse_time("11:05+05:00") >>> print(incorrect_time) datetime.time(11, 5) # Here I would expect to # - either get an error because it is not stated that a format having a timedelta is accepted # - or a datetime.time(11, 5, tzinfo=datetime.timezone(datetime.timedelta(seconds=18000)) as datetime.time.fromisoformat would return ```
0.0
4bc4230df6294c62667fc3779328019a28912147
[ "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[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[2012-04-23T11:05:00-25:00-DateTimeError]" ]
[ "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_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[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_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[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_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-result4]", "tests/test_datetime_parse.py::test_parse_durations[5:30-result5]", "tests/test_datetime_parse.py::test_parse_durations[10:15:30-result6]", "tests/test_datetime_parse.py::test_parse_durations[1:15:30-result7]", "tests/test_datetime_parse.py::test_parse_durations[100:200:300-result8]", "tests/test_datetime_parse.py::test_parse_durations[4", "tests/test_datetime_parse.py::test_parse_durations[15:30.1-result11]", "tests/test_datetime_parse.py::test_parse_durations[15:30.01-result12]", "tests/test_datetime_parse.py::test_parse_durations[15:30.001-result13]", "tests/test_datetime_parse.py::test_parse_durations[15:30.0001-result14]", "tests/test_datetime_parse.py::test_parse_durations[15:30.00001-result15]", "tests/test_datetime_parse.py::test_parse_durations[15:30.000001-result16]", "tests/test_datetime_parse.py::test_parse_durations[15:30.000001-result17]", "tests/test_datetime_parse.py::test_parse_durations[-4", "tests/test_datetime_parse.py::test_parse_durations[-172800-result19]", "tests/test_datetime_parse.py::test_parse_durations[-15:30-result20]", "tests/test_datetime_parse.py::test_parse_durations[-1:15:30-result21]", "tests/test_datetime_parse.py::test_parse_durations[-30.1-result22]", "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-result26]", "tests/test_datetime_parse.py::test_parse_durations[P0.5D-result27]", "tests/test_datetime_parse.py::test_parse_durations[PT5H-result28]", "tests/test_datetime_parse.py::test_parse_durations[PT5M-result29]", "tests/test_datetime_parse.py::test_parse_durations[PT5S-result30]", "tests/test_datetime_parse.py::test_parse_durations[PT0.000005S-result31]", "tests/test_datetime_parse.py::test_parse_durations[PT0.000005S-result32]", "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]" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-08-09 21:14:56+00:00
mit
4,753
pydantic__pydantic-1911
diff --git a/docs/examples/types_urls.py b/docs/examples/types_urls.py --- a/docs/examples/types_urls.py +++ b/docs/examples/types_urls.py @@ -7,6 +7,7 @@ class MyModel(BaseModel): m = MyModel(url='http://www.example.com') print(m.url) + try: MyModel(url='ftp://invalid.url') except ValidationError as e: diff --git a/pydantic/networks.py b/pydantic/networks.py --- a/pydantic/networks.py +++ b/pydantic/networks.py @@ -43,7 +43,6 @@ 'validate_email', ] - _url_regex_cache = None _ascii_domain_regex_cache = None _int_domain_regex_cache = None @@ -54,7 +53,7 @@ def url_regex() -> Pattern[str]: if _url_regex_cache is None: _url_regex_cache = re.compile( r'(?:(?P<scheme>[a-z][a-z0-9+\-.]+)://)?' # scheme https://tools.ietf.org/html/rfc3986#appendix-A - r'(?:(?P<user>[^\s:/]+)(?::(?P<password>[^\s/]*))?@)?' # user info + r'(?:(?P<user>[^\s:/]*)(?::(?P<password>[^\s/]*))?@)?' # user info r'(?:' r'(?P<ipv4>(?:\d{1,3}\.){3}\d{1,3})|' # ipv4 r'(?P<ipv6>\[[A-F0-9]*:[A-F0-9:]+\])|' # ipv6 @@ -147,8 +146,9 @@ def build( url = scheme + '://' if user: url += user - if password: - url += ':' + password + if password: + url += ':' + password + if user or password: url += '@' url += host if port: @@ -183,20 +183,7 @@ def validate(cls, value: Any, field: 'ModelField', config: 'BaseConfig') -> 'Any assert m, 'URL regex failed unexpectedly' parts = m.groupdict() - scheme = parts['scheme'] - if scheme is None: - raise errors.UrlSchemeError() - - if cls.allowed_schemes and scheme.lower() not in cls.allowed_schemes: - raise errors.UrlSchemePermittedError(cls.allowed_schemes) - - port = parts['port'] - if port is not None and int(port) > 65_535: - raise errors.UrlPortError() - - user = parts['user'] - if cls.user_required and user is None: - raise errors.UrlUserInfoError() + parts = cls.validate_parts(parts) host, tld, host_type, rebuild = cls.validate_host(parts) @@ -205,18 +192,41 @@ def validate(cls, value: Any, field: 'ModelField', config: 'BaseConfig') -> 'Any return cls( None if rebuild else url, - scheme=scheme, - user=user, + scheme=parts['scheme'], + user=parts['user'], password=parts['password'], host=host, tld=tld, host_type=host_type, - port=port, + port=parts['port'], path=parts['path'], query=parts['query'], fragment=parts['fragment'], ) + @classmethod + def validate_parts(cls, parts: Dict[str, str]) -> Dict[str, str]: + """ + A method used to validate parts of an URL. + Could be overridden to set default values for parts if missing + """ + scheme = parts['scheme'] + if scheme is None: + raise errors.UrlSchemeError() + + if cls.allowed_schemes and scheme.lower() not in cls.allowed_schemes: + raise errors.UrlSchemePermittedError(cls.allowed_schemes) + + port = parts['port'] + if port is not None and int(port) > 65_535: + raise errors.UrlPortError() + + user = parts['user'] + if cls.user_required and user is None: + raise errors.UrlUserInfoError() + + return parts + @classmethod def validate_host(cls, parts: Dict[str, str]) -> Tuple[str, Optional[str], str, bool]: host, tld, host_type, rebuild = None, None, None, False @@ -279,7 +289,19 @@ class PostgresDsn(AnyUrl): class RedisDsn(AnyUrl): - allowed_schemes = {'redis'} + allowed_schemes = {'redis', 'rediss'} + + @classmethod + def validate_parts(cls, parts: Dict[str, str]) -> Dict[str, str]: + defaults = { + 'domain': 'localhost' if not (parts['ipv4'] or parts['ipv6']) else '', + 'port': '6379', + 'path': '/0', + } + for key, value in defaults.items(): + if not parts[key]: + parts[key] = value + return super().validate_parts(parts) def stricturl(
pydantic/pydantic
de0657e4a5495de9378db9fe15a17334c2b0fae5
diff --git a/tests/test_networks.py b/tests/test_networks.py --- a/tests/test_networks.py +++ b/tests/test_networks.py @@ -190,6 +190,13 @@ def test_user_no_password(): assert url.host == 'example.org' +def test_user_info_no_user(): + url = validate_url('http://:[email protected]') + assert url.user == '' + assert url.password == 'password' + assert url.host == 'example.org' + + def test_at_in_path(): url = validate_url('https://twitter.com/@handle') assert url.scheme == 'https' @@ -321,21 +328,35 @@ def test_redis_dsns(): class Model(BaseModel): a: RedisDsn - m = Model(a='redis://user:pass@localhost:5432/app') - assert m.a == 'redis://user:pass@localhost:5432/app' + m = Model(a='redis://user:pass@localhost:1234/app') + assert m.a == 'redis://user:pass@localhost:1234/app' assert m.a.user == 'user' assert m.a.password == 'pass' + m = Model(a='rediss://user:pass@localhost:1234/app') + assert m.a == 'rediss://user:pass@localhost:1234/app' + + m = Model(a='rediss://:pass@localhost:1234') + assert m.a == 'rediss://:pass@localhost:1234/0' + with pytest.raises(ValidationError) as exc_info: Model(a='http://example.org') assert exc_info.value.errors()[0]['type'] == 'value_error.url.scheme' - # password is not required for redis - m = Model(a='redis://localhost:5432/app') - assert m.a == 'redis://localhost:5432/app' + # Password is not required for Redis protocol + m = Model(a='redis://localhost:1234/app') + assert m.a == 'redis://localhost:1234/app' assert m.a.user is None assert m.a.password is None + # Only schema is required for Redis protocol. Otherwise it will be set to default + # https://www.iana.org/assignments/uri-schemes/prov/redis + m = Model(a='rediss://') + assert m.a.scheme == 'rediss' + assert m.a.host == 'localhost' + assert m.a.port == '6379' + assert m.a.path == '/0' + def test_custom_schemes(): class Model(BaseModel):
RedisDsn canot enable redis url with password and ssl schema `redis://:password@redishost` & `rediss://redis` are valid in redis.py, but cause ValidationError in RedisDsn. ``` In [7]: import redis In [8]: r = redis.StrictRedis.from_url('rediss://redis') In [9]: r = redis.StrictRedis.from_url('redis://:123@redis') In [10]: ``` * type error list below ``` In [3]: from pydantic import BaseModel, RedisDsn In [4]: class RedisURLModel(BaseModel): ...: url: RedisDsn = None ...: In [5]: c = RedisURLModel(url='redis://:myredispwd@redis') --------------------------------------------------------------------------- ValidationError Traceback (most recent call last) <ipython-input-5-23cad9c7fe6b> in <module> ----> 1 c = RedisURLModel(url='redis://:myredispwd@redis') /usr/local/lib/python3.7/site-packages/pydantic/main.cpython-37m-x86_64-linux-gnu.so in pydantic.main.BaseModel.__init__() ValidationError: 1 validation error for RedisURLModel url URL host invalid (type=value_error.url.host) In [6]: c = RedisURLModel(url='rediss://redis') --------------------------------------------------------------------------- ValidationError Traceback (most recent call last) <ipython-input-6-39558dddb3bc> in <module> ----> 1 c = RedisURLModel(url='rediss://redis') /usr/local/lib/python3.7/site-packages/pydantic/main.cpython-37m-x86_64-linux-gnu.so in pydantic.main.BaseModel.__init__() ValidationError: 1 validation error for RedisURLModel url URL scheme not permitted (type=value_error.url.scheme; allowed_schemes={'redis'}) ```
0.0
de0657e4a5495de9378db9fe15a17334c2b0fae5
[ "tests/test_networks.py::test_user_info_no_user", "tests/test_networks.py::test_redis_dsns" ]
[ "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+psycopg2://postgres:postgres@localhost:5432/hatch]", "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_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_parts", "tests/test_networks.py::test_url_repr", "tests/test_networks.py::test_ipv4_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_at_in_path", "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_postgres_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_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_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-09-07 18:05:25+00:00
mit
4,754
pydantic__pydantic-1935
diff --git a/docs/examples/types_iterables.py b/docs/examples/types_iterables.py --- a/docs/examples/types_iterables.py +++ b/docs/examples/types_iterables.py @@ -1,4 +1,6 @@ -from typing import Dict, FrozenSet, List, Optional, Sequence, Set, Tuple, Union +from typing import ( + Deque, Dict, FrozenSet, List, Optional, Sequence, Set, Tuple, Union +) from pydantic import BaseModel @@ -24,6 +26,8 @@ class Model(BaseModel): compound: Dict[Union[str, bytes], List[Set[int]]] = None + deque: Deque[int] = None + print(Model(simple_list=['1', '2', '3']).simple_list) print(Model(list_of_ints=['1', '2', '3']).list_of_ints) @@ -36,3 +40,5 @@ class Model(BaseModel): print(Model(sequence_of_ints=[1, 2, 3, 4]).sequence_of_ints) print(Model(sequence_of_ints=(1, 2, 3, 4)).sequence_of_ints) + +print(Model(deque=[1, 2, 3]).deque) diff --git a/pydantic/errors.py b/pydantic/errors.py --- a/pydantic/errors.py +++ b/pydantic/errors.py @@ -282,6 +282,10 @@ class FrozenSetError(PydanticTypeError): msg_template = 'value is not a valid frozenset' +class DequeError(PydanticTypeError): + msg_template = 'value is not a valid deque' + + class TupleError(PydanticTypeError): msg_template = 'value is not a valid tuple' diff --git a/pydantic/fields.py b/pydantic/fields.py --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -1,8 +1,10 @@ import warnings +from collections import deque from collections.abc import Iterable as CollectionsIterable from typing import ( TYPE_CHECKING, Any, + Deque, Dict, FrozenSet, Generator, @@ -207,6 +209,7 @@ def Schema(default: Any, **kwargs: Any) -> Any: SHAPE_FROZENSET = 8 SHAPE_ITERABLE = 9 SHAPE_GENERIC = 10 +SHAPE_DEQUE = 11 SHAPE_NAME_LOOKUP = { SHAPE_LIST: 'List[{}]', SHAPE_SET: 'Set[{}]', @@ -214,6 +217,7 @@ def Schema(default: Any, **kwargs: Any) -> Any: SHAPE_SEQUENCE: 'Sequence[{}]', SHAPE_FROZENSET: 'FrozenSet[{}]', SHAPE_ITERABLE: 'Iterable[{}]', + SHAPE_DEQUE: 'Deque[{}]', } @@ -477,6 +481,9 @@ def _type_analysis(self) -> None: # noqa: C901 (ignore complexity) elif issubclass(origin, FrozenSet): self.type_ = get_args(self.type_)[0] self.shape = SHAPE_FROZENSET + elif issubclass(origin, Deque): + self.type_ = get_args(self.type_)[0] + self.shape = SHAPE_DEQUE elif issubclass(origin, Sequence): self.type_ = get_args(self.type_)[0] self.shape = SHAPE_SEQUENCE @@ -620,7 +627,7 @@ def _validate_sequence_like( # noqa: C901 (ignore complexity) if errors: return v, errors - converted: Union[List[Any], Set[Any], FrozenSet[Any], Tuple[Any, ...], Iterator[Any]] = result + converted: Union[List[Any], Set[Any], FrozenSet[Any], Tuple[Any, ...], Iterator[Any], Deque[Any]] = result if self.shape == SHAPE_SET: converted = set(result) @@ -628,6 +635,8 @@ def _validate_sequence_like( # noqa: C901 (ignore complexity) converted = frozenset(result) elif self.shape == SHAPE_TUPLE_ELLIPSIS: converted = tuple(result) + elif self.shape == SHAPE_DEQUE: + converted = deque(result) elif self.shape == SHAPE_SEQUENCE: if isinstance(v, tuple): converted = tuple(result) @@ -635,6 +644,8 @@ def _validate_sequence_like( # noqa: C901 (ignore complexity) converted = set(result) elif isinstance(v, Generator): converted = iter(result) + elif isinstance(v, deque): + converted = deque(result) return converted, None def _validate_iterable( diff --git a/pydantic/json.py b/pydantic/json.py --- a/pydantic/json.py +++ b/pydantic/json.py @@ -1,4 +1,5 @@ import datetime +from collections import deque from decimal import Decimal from enum import Enum from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network @@ -27,6 +28,7 @@ def isoformat(o: Union[datetime.date, datetime.time]) -> str: Decimal: float, Enum: lambda o: o.value, frozenset: list, + deque: list, GeneratorType: list, IPv4Address: str, IPv4Interface: str, diff --git a/pydantic/utils.py b/pydantic/utils.py --- a/pydantic/utils.py +++ b/pydantic/utils.py @@ -126,7 +126,7 @@ def truncate(v: Union[str], *, max_len: int = 80) -> str: def sequence_like(v: Type[Any]) -> bool: - return isinstance(v, (list, tuple, set, frozenset, GeneratorType)) + return isinstance(v, (list, tuple, set, frozenset, GeneratorType, deque)) def validate_field_name(bases: List[Type['BaseModel']], field_name: str) -> None: diff --git a/pydantic/validators.py b/pydantic/validators.py --- a/pydantic/validators.py +++ b/pydantic/validators.py @@ -1,5 +1,5 @@ import re -from collections import OrderedDict +from collections import OrderedDict, deque from collections.abc import Hashable from datetime import date, datetime, time, timedelta from decimal import Decimal, DecimalException @@ -10,6 +10,7 @@ TYPE_CHECKING, Any, Callable, + Deque, Dict, FrozenSet, Generator, @@ -245,6 +246,15 @@ def frozenset_validator(v: Any) -> FrozenSet[Any]: raise errors.FrozenSetError() +def deque_validator(v: Any) -> Deque[Any]: + if isinstance(v, deque): + return v + elif sequence_like(v): + return deque(v) + else: + raise errors.DequeError() + + def enum_member_validator(v: Any, field: 'ModelField', config: 'BaseConfig') -> Enum: try: enum_v = field.type_(v) @@ -548,6 +558,7 @@ def check(self, config: Type['BaseConfig']) -> bool: (tuple, [tuple_validator]), (set, [set_validator]), (frozenset, [frozenset_validator]), + (deque, [deque_validator]), (UUID, [uuid_validator]), (Decimal, [decimal_validator]), (IPv4Interface, [ip_v4_interface_validator]),
pydantic/pydantic
d14731f16c70b72263ee8f21de6639b01341c510
diff --git a/tests/test_types.py b/tests/test_types.py --- a/tests/test_types.py +++ b/tests/test_types.py @@ -3,12 +3,13 @@ import re import sys import uuid -from collections import OrderedDict +from collections import OrderedDict, deque from datetime import date, datetime, time, timedelta from decimal import Decimal from enum import Enum, IntEnum from pathlib import Path from typing import ( + Deque, Dict, FrozenSet, Iterable, @@ -852,6 +853,7 @@ class Model(BaseModel): ((1, 2, '3'), [1, 2, '3']), ({1, 2, '3'}, list({1, 2, '3'})), ((i ** 2 for i in range(5)), [0, 1, 4, 9, 16]), + ((deque((1, 2, 3)), list(deque((1, 2, 3))))), ), ) def test_list_success(value, result): @@ -891,6 +893,7 @@ class Model(BaseModel): ((1, 2, '3'), (1, 2, '3')), ({1, 2, '3'}, tuple({1, 2, '3'})), ((i ** 2 for i in range(5)), (0, 1, 4, 9, 16)), + (deque([1, 2, 3]), (1, 2, 3)), ), ) def test_tuple_success(value, result): @@ -998,6 +1001,7 @@ class Model(BaseModel): ( (int, [1, 2, 3], [1, 2, 3]), (int, (1, 2, 3), (1, 2, 3)), + (int, deque((1, 2, 3)), deque((1, 2, 3))), (float, {1.0, 2.0, 3.0}, {1.0, 2.0, 3.0}), (Set[int], [{1, 2}, {3, 4}, {5, 6}], [{1, 2}, {3, 4}, {5, 6}]), (Tuple[int, str], ((1, 'a'), (2, 'b'), (3, 'c')), ((1, 'a'), (2, 'b'), (3, 'c'))), @@ -2288,15 +2292,22 @@ class FrozenSetModel(BaseModel): assert object_under_test.set == test_set -def test_frozenset_field_conversion(): [email protected]( + 'value,result', + [ + ([1, 2, 3], frozenset([1, 2, 3])), + ({1, 2, 3}, frozenset([1, 2, 3])), + ((1, 2, 3), frozenset([1, 2, 3])), + (deque([1, 2, 3]), frozenset([1, 2, 3])), + ], +) +def test_frozenset_field_conversion(value, result): class FrozenSetModel(BaseModel): set: FrozenSet[int] - test_list = [1, 2, 3] - test_set = frozenset(test_list) - object_under_test = FrozenSetModel(set=test_list) + object_under_test = FrozenSetModel(set=value) - assert object_under_test.set == test_set + assert object_under_test.set == result def test_frozenset_field_not_convertible(): @@ -2361,3 +2372,82 @@ class Model(BaseModel): m = Model(size='1MB') with pytest.raises(errors.InvalidByteSizeUnit, match='byte unit'): m.size.to('bad_unit') + + +def test_deque_success(): + class Model(BaseModel): + v: deque + + assert Model(v=[1, 2, 3]).v == deque([1, 2, 3]) + + [email protected]( + 'cls,value,result', + ( + (int, [1, 2, 3], deque([1, 2, 3])), + (int, (1, 2, 3), deque((1, 2, 3))), + (int, deque((1, 2, 3)), deque((1, 2, 3))), + (float, {1.0, 2.0, 3.0}, deque({1.0, 2.0, 3.0})), + (Set[int], [{1, 2}, {3, 4}, {5, 6}], deque([{1, 2}, {3, 4}, {5, 6}])), + (Tuple[int, str], ((1, 'a'), (2, 'b'), (3, 'c')), deque(((1, 'a'), (2, 'b'), (3, 'c')))), + (str, [w for w in 'one two three'.split()], deque(['one', 'two', 'three'])), + (int, frozenset([1, 2, 3]), deque([1, 2, 3])), + ), +) +def test_deque_generic_success(cls, value, result): + class Model(BaseModel): + v: Deque[cls] + + assert Model(v=value).v == result + + [email protected]( + 'cls,value,errors', + ( + (int, [1, 'a', 3], [{'loc': ('v', 1), 'msg': 'value is not a valid integer', 'type': 'type_error.integer'}]), + (int, (1, 2, 'a'), [{'loc': ('v', 2), 'msg': 'value is not a valid integer', 'type': 'type_error.integer'}]), + (float, range(10), [{'loc': ('v',), 'msg': 'value is not a valid sequence', 'type': 'type_error.sequence'}]), + (float, ('a', 2.2, 3.3), [{'loc': ('v', 0), 'msg': 'value is not a valid float', 'type': 'type_error.float'}]), + (float, (1.1, 2.2, 'a'), [{'loc': ('v', 2), 'msg': 'value is not a valid float', 'type': 'type_error.float'}]), + ( + Set[int], + [{1, 2}, {2, 3}, {'d'}], + [{'loc': ('v', 2, 0), 'msg': 'value is not a valid integer', 'type': 'type_error.integer'}], + ), + ( + Tuple[int, str], + ((1, 'a'), ('a', 'a'), (3, 'c')), + [{'loc': ('v', 1, 0), 'msg': 'value is not a valid integer', 'type': 'type_error.integer'}], + ), + ( + List[int], + [{'a': 1, 'b': 2}, [1, 2], [2, 3]], + [{'loc': ('v', 0), 'msg': 'value is not a valid list', 'type': 'type_error.list'}], + ), + ), +) +def test_deque_fails(cls, value, errors): + class Model(BaseModel): + v: Deque[cls] + + with pytest.raises(ValidationError) as exc_info: + Model(v=value) + assert exc_info.value.errors() == errors + + +def test_deque_model(): + class Model2(BaseModel): + x: int + + class Model(BaseModel): + v: Deque[Model2] + + seq = [Model2(x=1), Model2(x=2)] + assert Model(v=seq).v == deque(seq) + + +def test_deque_json(): + class Model(BaseModel): + v: Deque[int] + + assert Model(v=deque((1, 2, 3))).json() == '{"v": [1, 2, 3]}' diff --git a/tests/test_validators.py b/tests/test_validators.py --- a/tests/test_validators.py +++ b/tests/test_validators.py @@ -1,3 +1,4 @@ +from collections import deque from datetime import datetime from itertools import product from typing import Dict, List, Optional, Tuple @@ -56,6 +57,19 @@ class Model(BaseModel): assert Model(a=(6,)).a == frozenset({6}) +def test_deque_validation(): + class Model(BaseModel): + a: deque + + with pytest.raises(ValidationError) as exc_info: + Model(a='snap') + assert exc_info.value.errors() == [{'loc': ('a',), 'msg': 'value is not a valid deque', 'type': 'type_error.deque'}] + assert Model(a={1, 2, 3}).a == deque([1, 2, 3]) + assert Model(a=deque({1, 2, 3})).a == deque([1, 2, 3]) + assert Model(a=[4, 5]).a == deque([4, 5]) + assert Model(a=(6,)).a == deque([6]) + + def test_validate_whole(): class Model(BaseModel): a: List[int]
Accept deque as sequence-like input data 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 feature/change is needed * [x] After submitting this, I commit to one of: * Look through open issues and helped at least one other person * Hit the "watch" button on this repo to receive notifications and I commit to help at least 2 people that ask questions in the future * Implement a Pull Request for a confirmed bug <!-- Sorry to sound so draconian, but every second saved replying to issues is time spend improving pydantic :-) --> # Feature Request Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.6.1 pydantic compiled: True install path: /home/quan/.local/lib/python3.8/site-packages/pydantic python version: 3.8.2 (default, Jul 16 2020, 14:00:26) [GCC 9.3.0] platform: Linux-5.4.0-47-generic-x86_64-with-glibc2.29 optional deps. installed: [] ``` <!-- 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 feature hasn't been asked for before, or already implemented. --> Code snippet: ```py from collections import deque from typing import List from pydantic import BaseModel class Ticket(BaseModel): numbers: List[int] = [] Ticket.parse_obj({'numbers': deque((1, 3, 5))}) ``` Got error: ```py Traceback (most recent call last): File "<stdin>", line 1, in <module> File "pydantic/main.py", line 455, in pydantic.main.BaseModel.parse_obj File "pydantic/main.py", line 346, in pydantic.main.BaseModel.__init__ pydantic.error_wrappers.ValidationError: 1 validation error for Ticket numbers value is not a valid list (type=type_error.list) 1 validation error for Ticket numbers value is not a valid list (type=type_error.list) ``` I expect to get: ```py Ticket(numbers=[1, 3, 5]) ```
0.0
d14731f16c70b72263ee8f21de6639b01341c510
[ "tests/test_types.py::test_list_success[value4-result4]", "tests/test_types.py::test_tuple_success[value4-result4]", "tests/test_types.py::test_sequence_success[int-value2-result2]", "tests/test_types.py::test_frozenset_field_conversion[value3-result3]", "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_model", "tests/test_types.py::test_deque_json", "tests/test_validators.py::test_deque_validation" ]
[ "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_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_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_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_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_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_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[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_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_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_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_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_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_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_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_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_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_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_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_nested_literal_validator" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2020-09-19 10:21:10+00:00
mit
4,755
pydantic__pydantic-1989
diff --git a/pydantic/generics.py b/pydantic/generics.py --- a/pydantic/generics.py +++ b/pydantic/generics.py @@ -1,10 +1,14 @@ import sys +import typing from typing import ( TYPE_CHECKING, Any, ClassVar, Dict, Generic, + Iterable, + Iterator, + List, Optional, Tuple, Type, @@ -17,8 +21,8 @@ from .class_validators import gather_all_validators from .fields import FieldInfo, ModelField from .main import BaseModel, create_model -from .typing import get_origin -from .utils import lenient_issubclass +from .typing import display_as_type, get_args, get_origin, typing_base +from .utils import all_identical, lenient_issubclass _generic_types_cache: Dict[Tuple[Type[Any], Union[Any, Tuple[Any, ...]]], Type[BaseModel]] = {} GenericModelT = TypeVar('GenericModelT', bound='GenericModel') @@ -37,6 +41,16 @@ class GenericModel(BaseModel): # Setting the return type as Type[Any] instead of Type[BaseModel] prevents PyCharm warnings 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. + + """ cached = _generic_types_cache.get((cls, params)) if cached is not None: return cached @@ -50,16 +64,24 @@ def __class_getitem__(cls: Type[GenericModelT], params: Union[Type[Any], Tuple[T raise TypeError(f'Type {cls.__name__} must inherit from typing.Generic before being parameterized') check_parameters_count(cls, params) + # Build map from generic typevars to passed params typevars_map: Dict[TypeVarType, Type[Any]] = dict(zip(cls.__parameters__, params)) + if all_identical(typevars_map.keys(), typevars_map.values()) and typevars_map: + return cls # if arguments are equal to parameters it's the same object + + # Recursively walk class type hints and replace generic typevars + # with concrete types that were passed. type_hints = get_type_hints(cls).items() instance_type_hints = {k: v for k, v in type_hints if get_origin(v) is not ClassVar} concrete_type_hints: Dict[str, Type[Any]] = { - k: resolve_type_hint(v, typevars_map) for k, v in instance_type_hints.items() + k: replace_types(v, typevars_map) for k, v in instance_type_hints.items() } + # Create new model with original model as parent inserting fields with + # updated type hints. model_name = cls.__concrete_name__(params) validators = gather_all_validators(cls) - fields = _build_generic_fields(cls.__fields__, concrete_type_hints, typevars_map) + fields = _build_generic_fields(cls.__fields__, concrete_type_hints) model_module, called_globally = get_caller_frame_info() created_model = cast( Type[GenericModel], # casting ensures mypy is aware of the __concrete__ and __parameters__ attributes @@ -82,12 +104,20 @@ def __class_getitem__(cls: Type[GenericModelT], params: Union[Type[Any], Tuple[T reference_name += '_' created_model.Config = cls.Config - concrete = all(not _is_typevar(v) for v in concrete_type_hints.values()) - created_model.__concrete__ = concrete - if not concrete: - parameters = tuple(v for v in concrete_type_hints.values() if _is_typevar(v)) - parameters = tuple({k: None for k in parameters}.keys()) # get unique params while maintaining order - created_model.__parameters__ = parameters + + # Find any typevars that are still present in the model. + # If none are left, the model is fully "concrete", otherwise the new + # class is a generic class as well taking the found typevars as + # parameters. + new_params = tuple( + {param: None for param in iter_contained_typevars(typevars_map.values())} + ) # use dict as ordered set + created_model.__concrete__ = not new_params + if new_params: + created_model.__parameters__ = new_params + + # 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 if len(params) == 1: _generic_types_cache[(cls, params[0])] = created_model @@ -95,19 +125,74 @@ def __class_getitem__(cls: Type[GenericModelT], params: Union[Type[Any], Tuple[T @classmethod def __concrete_name__(cls: Type[Any], params: Tuple[Type[Any], ...]) -> str: + """Compute class name for child classes. + + :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: String representing a the new class where `params` are + passed to `cls` as type variables. + + This method can be overridden to achieve a custom naming scheme for GenericModels. """ - 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] + param_names = [display_as_type(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]: - if get_origin(type_) and getattr(type_, '__parameters__', None): - concrete_type_args = tuple([typevars_map[x] for x in type_.__parameters__]) - return type_[concrete_type_args] - return typevars_map.get(type_, type_) +def replace_types(type_: Any, type_map: Dict[Any, Any]) -> Any: + """Return type with all occurances of `type_map` keys recursively replaced with their values. + + :param type_: Any type, class or generic alias + :type_map: Mapping from `TypeVar` instance to concrete types. + :return: New type representing the basic structure of `type_` with all + `typevar_map` keys recursively replaced. + + >>> replace_types(Tuple[str, Union[List[str], float]], {str: int}) + Tuple[int, Union[List[int], float]] + + """ + if not type_map: + return type_ + + type_args = get_args(type_) + origin_type = get_origin(type_) + + # Having type args is a good indicator that this is a typing module + # class instantiation or a generic alias of some sort. + if type_args: + resolved_type_args = tuple(replace_types(arg, type_map) for arg in type_args) + if all_identical(type_args, resolved_type_args): + # If all arguments are the same, there is no need to modify the + # type or create a new object at all + return type_ + if origin_type is not None and isinstance(type_, typing_base) and not isinstance(origin_type, typing_base): + # In python < 3.9 generic aliases don't exist so any of these like `list`, + # `type` or `collections.abc.Callable` need to be translated. + # See: https://www.python.org/dev/peps/pep-0585 + origin_type = getattr(typing, type_._name) + return origin_type[resolved_type_args] + + # We handle pydantic generic models separately as they don't have the same + # semantics as "typing" classes or generic aliases + if not origin_type and lenient_issubclass(type_, GenericModel) and not type_.__concrete__: + type_args = type_.__parameters__ + resolved_type_args = tuple(replace_types(t, type_map) for t in type_args) + if all_identical(type_args, resolved_type_args): + return type_ + return type_[resolved_type_args] + + # Handle special case for typehints that can have lists as arguments. + # `typing.Callable[[int, str], int]` is an example for this. + if isinstance(type_, (List, list)): + resolved_list = list(replace_types(element, type_map) for element in type_) + if all_identical(type_, resolved_list): + return type_ + return resolved_list + + # If all else fails, we try to resolve the type directly and otherwise just + # return the input with no modifications. + return type_map.get(type_, type_) def check_parameters_count(cls: Type[GenericModel], parameters: Tuple[Any, ...]) -> None: @@ -118,27 +203,26 @@ def check_parameters_count(cls: Type[GenericModel], parameters: Tuple[Any, ...]) raise TypeError(f'Too {description} parameters for {cls.__name__}; actual {actual}, expected {expected}') +def iter_contained_typevars(v: Any) -> Iterator[TypeVarType]: + """Recursively iterate through all subtypes and type args of `v` and yield any typevars that are found.""" + if isinstance(v, TypeVar): + yield v + elif hasattr(v, '__parameters__') and not get_origin(v) and lenient_issubclass(v, GenericModel): + yield from v.__parameters__ + elif isinstance(v, Iterable): + for var in v: + yield from iter_contained_typevars(var) + else: + args = get_args(v) + for arg in args: + yield from iter_contained_typevars(arg) + + def _build_generic_fields( raw_fields: Dict[str, ModelField], concrete_type_hints: Dict[str, Type[Any]], - typevars_map: Dict[TypeVarType, Type[Any]], ) -> Dict[str, Tuple[Type[Any], FieldInfo]]: - return { - k: (_parameterize_generic_field(v, typevars_map), raw_fields[k].field_info) - for k, v in concrete_type_hints.items() - if k in raw_fields - } - - -def _parameterize_generic_field(field_type: Type[Any], typevars_map: Dict[TypeVarType, Type[Any]]) -> Type[Any]: - if lenient_issubclass(field_type, GenericModel) and not field_type.__concrete__: - parameters = tuple(typevars_map.get(param, param) for param in field_type.__parameters__) - field_type = field_type[parameters] - return field_type - - -def _is_typevar(v: Any) -> bool: - return isinstance(v, TypeVar) + return {k: (v, raw_fields[k].field_info) for k, v in concrete_type_hints.items() if k in raw_fields} def get_caller_frame_info() -> Tuple[Optional[str], bool]: diff --git a/pydantic/typing.py b/pydantic/typing.py --- a/pydantic/typing.py +++ b/pydantic/typing.py @@ -25,6 +25,12 @@ except ImportError: from typing import _Final as typing_base # type: ignore +try: + from typing import GenericAlias # type: ignore +except ImportError: + # python < 3.9 does not have GenericAlias (list[int], tuple[str, ...] and so on) + GenericAlias = () + if sys.version_info < (3, 7): if TYPE_CHECKING: @@ -74,7 +80,7 @@ def evaluate_forwardref(type_: ForwardRef, globalns: Any, localns: Any) -> Any: AnyCallable = TypingCallable[..., Any] NoArgAnyCallable = TypingCallable[[], Any] -if sys.version_info < (3, 8): +if sys.version_info < (3, 8): # noqa: C901 if TYPE_CHECKING: from typing_extensions import Literal else: # due to different mypy warnings raised during CI for python 3.7 and 3.8 @@ -83,8 +89,34 @@ def evaluate_forwardref(type_: ForwardRef, globalns: Any, localns: Any) -> Any: except ImportError: Literal = None - def get_args(t: Type[Any]) -> Tuple[Any, ...]: - return getattr(t, '__args__', ()) + if sys.version_info < (3, 7): + + def get_args(t: Type[Any]) -> Tuple[Any, ...]: + """Simplest get_args compatability layer possible. + + The Python 3.6 typing module does not have `_GenericAlias` so + this won't work for everything. In particular this will not + support the `generics` module (we don't support generic models in + python 3.6). + + """ + return getattr(t, '__args__', ()) + + else: + from typing import _GenericAlias + + def get_args(t: Type[Any]) -> Tuple[Any, ...]: + """Compatability version of get_args for python 3.7. + + Mostly compatible with the python 3.8 `typing` module version + and able to handle almost all use cases. + """ + if isinstance(t, _GenericAlias): + res = t.__args__ + if t.__origin__ is Callable and res and res[0] is not Ellipsis: + res = (list(res[:-1]), res[-1]) + return res + return getattr(t, '__args__', ()) def get_origin(t: Type[Any]) -> Optional[Type[Any]]: return getattr(t, '__origin__', None) @@ -179,7 +211,7 @@ def get_args(tp: Type[Any]) -> Tuple[Any, ...]: def display_as_type(v: Type[Any]) -> str: - if not isinstance(v, typing_base) and not isinstance(v, type): + if not isinstance(v, typing_base) and not isinstance(v, GenericAlias) and not isinstance(v, type): v = v.__class__ if isinstance(v, type) and issubclass(v, Enum): @@ -190,6 +222,10 @@ def display_as_type(v: Type[Any]) -> str: else: return 'enum' + if isinstance(v, GenericAlias): + # Generic alias are constructs like `list[int]` + return str(v).replace('typing.', '') + try: return v.__name__ except AttributeError: diff --git a/pydantic/utils.py b/pydantic/utils.py --- a/pydantic/utils.py +++ b/pydantic/utils.py @@ -2,7 +2,7 @@ import weakref from collections import OrderedDict, defaultdict, deque from copy import deepcopy -from itertools import islice +from itertools import islice, zip_longest from types import BuiltinFunctionType, CodeType, FunctionType, GeneratorType, LambdaType, ModuleType from typing import ( TYPE_CHECKING, @@ -11,6 +11,7 @@ Callable, Dict, Generator, + Iterable, Iterator, List, Mapping, @@ -638,3 +639,21 @@ def is_valid_private_name(name: str) -> bool: '__module__', '__qualname__', } + + +_EMPTY = object() + + +def all_identical(left: Iterable[Any], right: Iterable[Any]) -> bool: + """Check that the items of `left` are the same objects as those in `right`. + + >>> a, b = object(), object() + >>> all_identical([a, b, a], [a, b, a]) + True + >>> all_identical([a, b, [a]], [a, b, [a]]) # new list object, while "equal" is not "identical" + False + """ + for left_item, right_item in zip_longest(left, right, fillvalue=_EMPTY): + if left_item is not right_item: + return False + return True
pydantic/pydantic
1a2791d4223ff1d18400432ef5d020ce6910aa4a
Yep this is definitely a bug. In general, I think it should be possible to subclass even concrete generic models. I'm hopeful it's not too hard to implement. @dmontagu is the expert on `GenericModel`, any idea? I'm hitting this as well, it looks like the value of "concrete" is calculated by running: ``` concrete = all(not _is_typevar(v) for v in concrete_type_hints.values()) ``` and Optional[T] does not qualify as a typevar even though it should. The same goes for any more nested objects (including nested generic models). Most of it can probably be fixed by modifying `_is_typevar` to detect nested type vars. @dmontagu is the expert on `GenericModel`, any idea? I'm hitting this as well, it looks like the value of "concrete" is calculated by running: ``` concrete = all(not _is_typevar(v) for v in concrete_type_hints.values()) ``` and Optional[T] does not qualify as a typevar even though it should. The same goes for any more nested objects (including nested generic models). Most of it can probably be fixed by modifying `_is_typevar` to detect nested type vars.
diff --git a/tests/test_generics.py b/tests/test_generics.py --- a/tests/test_generics.py +++ b/tests/test_generics.py @@ -1,11 +1,11 @@ import sys from enum import Enum -from typing import Any, ClassVar, Dict, Generic, List, Optional, Tuple, Type, TypeVar, Union +from typing import Any, Callable, ClassVar, Dict, Generic, List, Optional, Sequence, Tuple, Type, TypeVar, Union import pytest from pydantic import BaseModel, Field, ValidationError, root_validator, validator -from pydantic.generics import GenericModel, _generic_types_cache +from pydantic.generics import GenericModel, _generic_types_cache, iter_contained_typevars, replace_types skip_36 = pytest.mark.skipif(sys.version_info < (3, 7), reason='generics only supported for python 3.7 and above') @@ -17,7 +17,10 @@ def test_generic_name(): class Result(GenericModel, Generic[data_type]): data: data_type - assert Result[List[int]].__name__ == 'Result[typing.List[int]]' + if sys.version_info >= (3, 9): + assert Result[list[int]].__name__ == 'Result[list[int]]' + assert Result[List[int]].__name__ == 'Result[List[int]]' + assert Result[int].__name__ == 'Result[int]' @skip_36 @@ -248,35 +251,6 @@ class Config: result.data = 2 -@skip_36 -def test_deep_generic(): - T = TypeVar('T') - S = TypeVar('S') - R = TypeVar('R') - - class OuterModel(GenericModel, Generic[T, S, R]): - a: Dict[R, Optional[List[T]]] - b: Optional[Union[S, R]] - c: R - d: float - - class InnerModel(GenericModel, Generic[T, R]): - c: T - d: R - - class NormalModel(BaseModel): - e: int - f: str - - inner_model = InnerModel[int, str] - generic_model = OuterModel[inner_model, NormalModel, int] - - inner_models = [inner_model(c=1, d='a')] - generic_model(a={1: inner_models, 2: None}, b=None, c=1, d=1.5) - generic_model(a={}, b=NormalModel(e=1, f='a'), c=1, d=1.5) - generic_model(a={}, b=1, c=1, d=1.5) - - @skip_36 def test_enum_generic(): T = TypeVar('T') @@ -498,6 +472,26 @@ class Model(GenericModel, Generic[AT, BT]): ] +@skip_36 +def test_partial_specification_with_inner_typevar(): + AT = TypeVar('AT') + BT = TypeVar('BT') + + class Model(GenericModel, Generic[AT, BT]): + a: List[AT] + b: List[BT] + + partial_model = Model[str, BT] + assert partial_model.__concrete__ is False + concrete_model = partial_model[int] + assert concrete_model.__concrete__ is True + + # nested resolution of partial models should work as expected + nested_resolved = concrete_model(a=[123], b=['456']) + assert nested_resolved.a == ['123'] + assert nested_resolved.b == [456] + + @skip_36 def test_partial_specification_name(): AT = TypeVar('AT') @@ -681,7 +675,11 @@ def get_generic(t): @skip_36 -def test_generic_model_redefined_without_cache_fail(create_module): +def test_generic_model_redefined_without_cache_fail(create_module, monkeypatch): + + # match identity checker otherwise we never get to the redefinition check + monkeypatch.setattr('pydantic.generics.all_identical', lambda left, right: False) + @create_module def module(): from typing import Generic, TypeVar @@ -756,3 +754,264 @@ def test_get_caller_frame_info_when_sys_getframe_undefined(): assert get_caller_frame_info() == (None, False) finally: # just to make sure we always setting original attribute back sys._getframe = getframe + + +@skip_36 +def test_iter_contained_typevars(): + T = TypeVar('T') + T2 = TypeVar('T2') + + class Model(GenericModel, Generic[T]): + a: T + + assert list(iter_contained_typevars(Model[T])) == [T] + assert list(iter_contained_typevars(Optional[List[Union[str, Model[T]]]])) == [T] + assert list(iter_contained_typevars(Optional[List[Union[str, Model[int]]]])) == [] + assert list(iter_contained_typevars(Optional[List[Union[str, Model[T], Callable[[T2, T], str]]]])) == [T, T2, T] + + +@skip_36 +def test_nested_identity_parameterization(): + T = TypeVar('T') + T2 = TypeVar('T2') + + class Model(GenericModel, Generic[T]): + a: T + + assert Model[T][T][T] is Model + assert Model[T] is Model + assert Model[T2] is not Model + + +@skip_36 +def test_replace_types(): + T = TypeVar('T') + + class Model(GenericModel, Generic[T]): + a: T + + assert replace_types(T, {T: int}) is int + assert replace_types(List[Union[str, list, T]], {T: int}) == List[Union[str, list, int]] + assert replace_types(Callable, {T: int}) == Callable + assert replace_types(Callable[[int, str, T], T], {T: int}) == Callable[[int, str, int], int] + assert replace_types(T, {}) is T + assert replace_types(Model[List[T]], {T: int}) == Model[List[T]][int] + assert replace_types(T, {}) is T + assert replace_types(Type[T], {T: int}) == Type[int] + assert replace_types(Model[T], {T: T}) == Model[T] + + if sys.version_info >= (3, 9): + # Check generic aliases (subscripted builtin types) to make sure they + # resolve correctly (don't get translated to typing versions for + # example) + assert replace_types(list[Union[str, list, T]], {T: int}) == list[Union[str, list, int]] + + +@skip_36 +def test_replace_types_identity_on_unchanged(): + T = TypeVar('T') + U = TypeVar('U') + + type_ = List[Union[str, Callable[[list], Optional[str]], U]] + assert replace_types(type_, {T: int}) is type_ + + +@skip_36 +def test_deep_generic(): + T = TypeVar('T') + S = TypeVar('S') + R = TypeVar('R') + + class OuterModel(GenericModel, Generic[T, S, R]): + a: Dict[R, Optional[List[T]]] + b: Optional[Union[S, R]] + c: R + d: float + + class InnerModel(GenericModel, Generic[T, R]): + c: T + d: R + + class NormalModel(BaseModel): + e: int + f: str + + inner_model = InnerModel[int, str] + generic_model = OuterModel[inner_model, NormalModel, int] + + inner_models = [inner_model(c=1, d='a')] + generic_model(a={1: inner_models, 2: None}, b=None, c=1, d=1.5) + generic_model(a={}, b=NormalModel(e=1, f='a'), c=1, d=1.5) + generic_model(a={}, b=1, c=1, d=1.5) + + assert InnerModel.__concrete__ is False + assert inner_model.__concrete__ is True + + +@skip_36 +def test_deep_generic_with_inner_typevar(): + T = TypeVar('T') + + class OuterModel(GenericModel, Generic[T]): + a: List[T] + + class InnerModel(OuterModel[T], Generic[T]): + pass + + assert InnerModel[int].__concrete__ is True + assert InnerModel.__concrete__ is False + + with pytest.raises(ValidationError): + InnerModel[int](a=['wrong']) + assert InnerModel[int](a=['1']).a == [1] + + +@skip_36 +def test_deep_generic_with_referenced_generic(): + T = TypeVar('T') + R = TypeVar('R') + + class ReferencedModel(GenericModel, Generic[R]): + a: R + + class OuterModel(GenericModel, Generic[T]): + a: ReferencedModel[T] + + class InnerModel(OuterModel[T], Generic[T]): + pass + + assert InnerModel[int].__concrete__ is True + assert InnerModel.__concrete__ is False + + with pytest.raises(ValidationError): + InnerModel[int](a={'a': 'wrong'}) + assert InnerModel[int](a={'a': 1}).a.a == 1 + + +@skip_36 +def test_deep_generic_with_referenced_inner_generic(): + T = TypeVar('T') + + class ReferencedModel(GenericModel, Generic[T]): + a: T + + class OuterModel(GenericModel, Generic[T]): + a: Optional[List[Union[ReferencedModel[T], str]]] + + class InnerModel(OuterModel[T], Generic[T]): + pass + + assert InnerModel[int].__concrete__ is True + assert InnerModel.__concrete__ is False + + with pytest.raises(ValidationError): + InnerModel[int](a=['s', {'a': 'wrong'}]) + assert InnerModel[int](a=['s', {'a': 1}]).a[1].a == 1 + + assert InnerModel[int].__fields__['a'].outer_type_ == List[Union[ReferencedModel[int], str]] + assert (InnerModel[int].__fields__['a'].sub_fields[0].sub_fields[0].outer_type_.__fields__['a'].outer_type_) == int + + +@skip_36 +def test_deep_generic_with_multiple_typevars(): + T = TypeVar('T') + U = TypeVar('U') + + class OuterModel(GenericModel, Generic[T]): + data: List[T] + + class InnerModel(OuterModel[T], Generic[U, T]): + extra: U + + ConcreteInnerModel = InnerModel[int, float] + assert ConcreteInnerModel.__fields__['data'].outer_type_ == List[float] + assert ConcreteInnerModel.__fields__['extra'].outer_type_ == int + + assert ConcreteInnerModel(data=['1'], extra='2').dict() == {'data': [1.0], 'extra': 2} + + +@skip_36 +def test_deep_generic_with_multiple_inheritance(): + K = TypeVar('K') + V = TypeVar('V') + T = TypeVar('T') + + class OuterModelA(GenericModel, Generic[K, V]): + data: Dict[K, V] + + class OuterModelB(GenericModel, Generic[T]): + stuff: List[T] + + class InnerModel(OuterModelA[K, V], OuterModelB[T], Generic[K, V, T]): + extra: int + + ConcreteInnerModel = InnerModel[int, float, str] + + assert ConcreteInnerModel.__fields__['data'].outer_type_ == Dict[int, float] + assert ConcreteInnerModel.__fields__['stuff'].outer_type_ == List[str] + assert ConcreteInnerModel.__fields__['extra'].outer_type_ == int + + ConcreteInnerModel(data={1.1: '5'}, stuff=[123], extra=5).dict() == { + 'data': {1: 5}, + 'stuff': ['123'], + 'extra': 5, + } + + +@skip_36 +def test_generic_with_referenced_generic_type_1(): + T = TypeVar('T') + + class ModelWithType(GenericModel, Generic[T]): + # Type resolves to type origin of "type" which is non-subscriptible for + # python < 3.9 so we want to make sure it works for other versions + some_type: Type[T] + + class ReferenceModel(GenericModel, Generic[T]): + abstract_base_with_type: ModelWithType[T] + + ReferenceModel[int] + + +@skip_36 +def test_generic_with_referenced_nested_typevar(): + T = TypeVar('T') + + class ModelWithType(GenericModel, Generic[T]): + # Type resolves to type origin of "collections.abc.Sequence" which is + # non-subscriptible for + # python < 3.9 so we want to make sure it works for other versions + some_type: Sequence[T] + + class ReferenceModel(GenericModel, Generic[T]): + abstract_base_with_type: ModelWithType[T] + + ReferenceModel[int] + + +@skip_36 +def test_generic_with_callable(): + T = TypeVar('T') + + class Model(GenericModel, Generic[T]): + # Callable is a test for any type that accepts a list as an argument + some_callable: Callable[[Optional[int], T], None] + + Model[str].__concrete__ is True + Model.__concrete__ is False + + +@skip_36 +def test_generic_with_partial_callable(): + T = TypeVar('T') + U = TypeVar('U') + + class Model(GenericModel, Generic[T, U]): + t: T + u: U + # Callable is a test for any type that accepts a list as an argument + some_callable: Callable[[Optional[int], str], None] + + Model[str, U].__concrete__ is False + Model[str, U].__parameters__ == [U] + Model[str, int].__concrete__ is False diff --git a/tests/test_utils.py b/tests/test_utils.py --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -27,6 +27,7 @@ BUILTIN_COLLECTIONS, ClassAttribute, ValueItems, + all_identical, deep_update, get_model, import_string, @@ -60,11 +61,18 @@ def test_import_no_attr(): assert exc_info.value.args[0] == 'Module "os" does not define a "foobar" attribute' [email protected]('value,expected', ((str, 'str'), ('string', 'str'), (Union[str, int], 'Union[str, int]'))) [email protected]( + 'value,expected', ((str, 'str'), ('string', 'str'), (Union[str, int], 'Union[str, int]'), (list, 'list')) +) def test_display_as_type(value, expected): assert display_as_type(value) == expected [email protected](sys.version_info < (3, 9), reason='generic aliases are not available in python < 3.9') +def test_display_as_type_generic_alias(): + assert display_as_type(list[[Union[str, int]]]) == 'list[[Union[str, int]]]' + + def test_display_as_type_enum(): class SubField(Enum): a = 1 @@ -446,3 +454,18 @@ def test_resolve_annotations_no_module(): # TODO: is there a better test for this, can this case really happen? fr = ForwardRef('Foo') assert resolve_annotations({'Foo': ForwardRef('Foo')}, None) == {'Foo': fr} + + +def test_all_identical(): + a, b = object(), object() + c = [b] + assert all_identical([a, b], [a, b]) is True + assert all_identical([a, b], [a, b]) is True + assert all_identical([a, b, b], [a, b, b]) is True + assert all_identical([a, c, b], [a, c, b]) is True + + assert all_identical([], [a]) is False, 'Expected iterables with different lengths to evaluate to `False`' + assert all_identical([a], []) is False, 'Expected iterables with different lengths to evaluate to `False`' + assert ( + all_identical([a, [b], b], [a, [b], b]) is False + ), 'New list objects are different objects and should therefor not be identical.'
GenericModel does not support generic subclasses # Bug It seems the implementation of pydantic.generics.GenericModel does not support generic subclasses. Example: ``` import pydantic.generics import typing T = typing.TypeVar("T") class ResponseModel(pydantic.generics.GenericModel, typing.Generic[T]): data: List[T] class PaginatedResponseModel(ResponseModel[T]): total_count: int ConcreteModel = PaginatedReponseModel[dict] # TypeError: Cannot parameterize a concrete instantiation of a generic model ``` `PaginatedReponseModel` is erroneously considered "concrete" even though type variables are used as parameters, and not concrete types. It seems GenericModel.__class_getitem__ does not check if any parameters are `TypeVar`, like `typing.Generic` does. To support generic subclasses, `__class_getitem__` should check if all of the parameters are fully concrete type(i.e. any of them are `typing.TypeVar`s, or any of them are generic types that have non-concrete type parameters). If not, a concrete model should not be created. I would consider this a bug since it does not follow the behavior of other `typing.Generic` usages, but it could also be a feature request. Please complete: * OS: Ubuntu 18.04.1 * Python version `import sys; print(sys.version)`: 3.7.1 (default, Oct 22 2018, 11:21:55) [GCC 8.2.0] * Pydantic version `import pydantic; print(pydantic.VERSION)`: `1.0` GenericModel - inheritance and Optional[TypeX] - fail to instantiate a subclass # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.4 pydantic compiled: False install path: /Users/thaisdeboisfosse/envs/thenv/lib/python3.7/site-packages/pydantic python version: 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 16:52:21) [Clang 6.0 (clang-600.0.57)] platform: Darwin-19.3.0-x86_64-i386-64bit optional deps. installed: ['typing-extensions'] ``` ### Summary Thank you for the lib ! I found a weird bug while using GenericModel. I create a BaseClass that inherits GenericModel and uses Generic. It contains a property X of type Optional[TypeX]. I create a subclass that fixes the Generic at runtime. The bug is that I cannot define the type of the Generic without an error. If `X` is of type `TypeX` instead of `Optional[TypeX]` then there is no error (it is what I ended up doing). ### Code to reproduce the error ```py import pydantic TypeX = TypeVar('TypeX') class BaseClass(GenericModel, Generic[TypeX]): X: Optional[TypeX] # This causes the error class ChildClass(BaseClass[TypeX], Generic[TypeX]): pass ChildClass[int] ``` Error: ``` cls = <class 'test_base_format.test_pydantic_failes.<locals>.ChildClass'> params = <class 'int'> def __class_getitem__(cls: Type[GenericModelT], params: Union[Type[Any], Tuple[Type[Any], ...]]) -> Type[Any]: cached = _generic_types_cache.get((cls, params)) if cached is not None: return cached if cls.__concrete__: > raise TypeError('Cannot parameterize a concrete instantiation of a generic model') E TypeError: Cannot parameterize a concrete instantiation of a generic model ``` GenericModel - inheritance and Optional[TypeX] - fail to instantiate a subclass # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.4 pydantic compiled: False install path: /Users/thaisdeboisfosse/envs/thenv/lib/python3.7/site-packages/pydantic python version: 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 16:52:21) [Clang 6.0 (clang-600.0.57)] platform: Darwin-19.3.0-x86_64-i386-64bit optional deps. installed: ['typing-extensions'] ``` ### Summary Thank you for the lib ! I found a weird bug while using GenericModel. I create a BaseClass that inherits GenericModel and uses Generic. It contains a property X of type Optional[TypeX]. I create a subclass that fixes the Generic at runtime. The bug is that I cannot define the type of the Generic without an error. If `X` is of type `TypeX` instead of `Optional[TypeX]` then there is no error (it is what I ended up doing). ### Code to reproduce the error ```py import pydantic TypeX = TypeVar('TypeX') class BaseClass(GenericModel, Generic[TypeX]): X: Optional[TypeX] # This causes the error class ChildClass(BaseClass[TypeX], Generic[TypeX]): pass ChildClass[int] ``` Error: ``` cls = <class 'test_base_format.test_pydantic_failes.<locals>.ChildClass'> params = <class 'int'> def __class_getitem__(cls: Type[GenericModelT], params: Union[Type[Any], Tuple[Type[Any], ...]]) -> Type[Any]: cached = _generic_types_cache.get((cls, params)) if cached is not None: return cached if cls.__concrete__: > raise TypeError('Cannot parameterize a concrete instantiation of a generic model') E TypeError: Cannot parameterize a concrete instantiation of a generic model ```
0.0
1a2791d4223ff1d18400432ef5d020ce6910aa4a
[ "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_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_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_display_as_type_generic_alias", "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_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_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_version_strict", "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_args[ConstrainedListValue-output_value0]", "tests/test_utils.py::test_get_args[ConstrainedList-output_value1]", "tests/test_utils.py::test_get_args[input_value2-output_value2]", "tests/test_utils.py::test_get_args[input_value3-output_value3]", "tests/test_utils.py::test_get_args[int-output_value4]", "tests/test_utils.py::test_get_args[input_value5-output_value5]", "tests/test_utils.py::test_get_args[input_value6-output_value6]", "tests/test_utils.py::test_get_args[input_value7-output_value7]", "tests/test_utils.py::test_resolve_annotations_no_module", "tests/test_utils.py::test_all_identical" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2020-10-10 13:27:58+00:00
mit
4,756
pydantic__pydantic-1991
diff --git a/pydantic/fields.py b/pydantic/fields.py --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -518,10 +518,26 @@ def _type_analysis(self) -> None: # noqa: C901 (ignore complexity) self.sub_fields = [self._create_sub_type(self.type_, '_' + self.name)] def _create_sub_type(self, type_: Type[Any], name: str, *, for_keys: bool = False) -> 'ModelField': + if for_keys: + class_validators = None + else: + # validators for sub items should not have `each_item` as we want to check only the first sublevel + class_validators = { + k: Validator( + func=v.func, + pre=v.pre, + each_item=False, + always=v.always, + check_fields=v.check_fields, + skip_on_failure=v.skip_on_failure, + ) + for k, v in self.class_validators.items() + if v.each_item + } return self.__class__( type_=type_, name=name, - class_validators=None if for_keys else {k: v for k, v in self.class_validators.items() if v.each_item}, + class_validators=class_validators, model_config=self.model_config, )
pydantic/pydantic
13a5c7d676167b415080de5e6e6a74bea095b239
Hello @kataev I agree the behaviour is not the expected one and for me this is a bug.
diff --git a/tests/test_validators.py b/tests/test_validators.py --- a/tests/test_validators.py +++ b/tests/test_validators.py @@ -575,6 +575,19 @@ def check_foobar(cls, v): assert Model(foobar={1: 1}).foobar == {1: 2} +def test_validation_each_item_one_sublevel(): + class Model(BaseModel): + foobar: List[Tuple[int, int]] + + @validator('foobar', each_item=True) + def check_foobar(cls, v: Tuple[int, int]) -> Tuple[int, int]: + v1, v2 = v + assert v1 == v2 + return v + + assert Model(foobar=[(1, 1), (2, 2)]).foobar == [(1, 1), (2, 2)] + + def test_key_validation(): class Model(BaseModel): foobar: Dict[int, int]
`each_item` should iterate only at the top-level instead of going through nested items Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.5.1 pydantic compiled: True install path: ...snip... python version: 3.6.9 (default, Jun 26 2020, 13:24:16) [GCC 4.2.1 Compatible Apple LLVM 11.0.0 (clang-1100.0.33.16)] platform: Darwin-18.7.0-x86_64-i386-64bit optional deps. installed: ['typing-extensions'] ``` I'm seeing what appears to be inconsistent behavior with `each_item=True` when I'm using a field that's a list of tuples. For instance, a 'normal' model illustrates what seems to be logical behavior. ```py from typing import List, Tuple from pydantic import BaseModel, validator class Thing(BaseModel): things: List[str] @validator("things", each_item=False) def validate_all_things(cls, val): print(f"all vals: {val}") return val @validator("things", each_item=True) def validate_single_thing(cls, val): print(f"single val: {val}") return val >>> Thing(things=["one", "two", "three,four"]) single val: one single val: two single val: three,four all vals: ['one', 'two', 'three,four'] Thing(things=['one', 'two', 'three,four']) ``` But if the field is anything like `List[Tuple[str], str]]`, then behavior is absolutely different. ```py class Thing2(BaseModel): things: List[Tuple[str, str]] @validator("things", each_item=False) def validate_all_things(cls, val): print(f"all vals: {val}") return val @validator("things", each_item=True) def validate_single_thing(cls, val): print(f"single val: {val}") return val >>> Thing2(things=[("one", "two"), ("three", "four")]) single val: one single val: two single val: three single val: four all vals: [('one', 'two'), ('three', 'four')] Thing2(things=[('one', 'two'), ('three', 'four')]) ``` The output from `validate_all_things` makes perfect sense - it's just the entire list passed in. I would expect, however, that `each_item` would do just what it implies, namely calling the validator on each item of the list **no matter what the item is**. Instead, it's operating on every value within each tuple within the list, and I cannot get it to perform in a way where `val == ("one", "two")`. Is this expected behavior? If so, why? I mean, strings are iterable just like tuples, so why isn't `each_item` iterating over the characters of each string in the first case?
0.0
13a5c7d676167b415080de5e6e6a74bea095b239
[ "tests/test_validators.py::test_validation_each_item_one_sublevel" ]
[ "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_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_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_field_that_is_being_validated_is_excluded_from_validator_values", "tests/test_validators.py::test_exceptions_in_field_validators_restore_original_field_value" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2020-10-11 00:08:40+00:00
mit
4,757
pydantic__pydantic-2000
diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -367,8 +367,10 @@ def __setattr__(self, name, value): elif self.__config__.validate_assignment: known_field = self.__fields__.get(name, None) if known_field: - value, error_ = known_field.validate(value, self.dict(exclude={name}), loc=name, cls=self.__class__) + original_value = self.__dict__.pop(name) + value, error_ = known_field.validate(value, self.__dict__, loc=name, cls=self.__class__) if error_: + self.__dict__[name] = original_value raise ValidationError([error_], self.__class__) self.__dict__[name] = value self.__fields_set__.add(name)
pydantic/pydantic
8ccc5708f120f65582cf9238592c6004efffc32d
diff --git a/tests/test_validators.py b/tests/test_validators.py --- a/tests/test_validators.py +++ b/tests/test_validators.py @@ -185,6 +185,30 @@ def test_validating_assignment_dict(): ] +def test_validating_assignment_values_dict(): + class ModelOne(BaseModel): + a: int + + class ModelTwo(BaseModel): + m: ModelOne + b: int + + @validator('b') + def validate_b(cls, b, values): + if 'm' in values: + return b + values['m'].a # this fails if values['m'] is a dict + else: + return b + + class Config: + validate_assignment = True + + model = ModelTwo(m=ModelOne(a=1), b=2) + assert model.b == 3 + model.b = 3 + assert model.b == 4 + + def test_validate_multiple(): # also test TypeError class Model(BaseModel):
"values" parameter in validator receives ambiguous types ### 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.6.1 pydantic compiled: True install path: /homes/<redacted>/.conda/envs/<redacted>/lib/python3.7/site-packages/pydantic python version: 3.7.8 | packaged by conda-forge | (default, Jul 31 2020, 02:25:08) [GCC 7.5.0] platform: Linux-4.9.0-0.bpo.6-amd64-x86_64-with-debian-8.11 optional deps. installed: ['typing-extensions'] ``` Hi, In a validator method, when adding the `values` parameter, I expect it to be a map from field names to validated types. When specifying `validate_assignment = True` in model config, `values` gets a different type (just on assignment). This is illustrated by the example below: ```py import pydantic class ModelOne(pydantic.BaseModel): a: int class ModelTwo(pydantic.BaseModel): m: ModelOne b: int @pydantic.validator('b') def validate_b(cls, b, values): print(values) if 'm' in values: return b + values['m'].a # this fails with AttributeError if values['m'] is a dict else: return b class Config: validate_assignment = True model = ModelTwo(m=ModelOne(a=1), b=2) #> {'m': ModelOne(a=1)} model.b = 3 #> {'m': {'a': 1}} ``` As far as I can tell, this behavior is not documented, and I'm pretty sure it's not intended. edit: created a PR "values" parameter in validator receives ambiguous types ### 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.6.1 pydantic compiled: True install path: /homes/<redacted>/.conda/envs/<redacted>/lib/python3.7/site-packages/pydantic python version: 3.7.8 | packaged by conda-forge | (default, Jul 31 2020, 02:25:08) [GCC 7.5.0] platform: Linux-4.9.0-0.bpo.6-amd64-x86_64-with-debian-8.11 optional deps. installed: ['typing-extensions'] ``` Hi, In a validator method, when adding the `values` parameter, I expect it to be a map from field names to validated types. When specifying `validate_assignment = True` in model config, `values` gets a different type (just on assignment). This is illustrated by the example below: ```py import pydantic class ModelOne(pydantic.BaseModel): a: int class ModelTwo(pydantic.BaseModel): m: ModelOne b: int @pydantic.validator('b') def validate_b(cls, b, values): print(values) if 'm' in values: return b + values['m'].a # this fails with AttributeError if values['m'] is a dict else: return b class Config: validate_assignment = True model = ModelTwo(m=ModelOne(a=1), b=2) #> {'m': ModelOne(a=1)} model.b = 3 #> {'m': {'a': 1}} ``` As far as I can tell, this behavior is not documented, and I'm pretty sure it's not intended. edit: created a PR
0.0
8ccc5708f120f65582cf9238592c6004efffc32d
[ "tests/test_validators.py::test_validating_assignment_values_dict" ]
[ "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_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_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_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_nested_literal_validator" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2020-10-12 09:34:29+00:00
mit
4,758
pydantic__pydantic-2006
diff --git a/docs/examples/models_generics_inheritance_extend.py b/docs/examples/models_generics_inheritance_extend.py new file mode 100644 --- /dev/null +++ b/docs/examples/models_generics_inheritance_extend.py @@ -0,0 +1,19 @@ +from typing import TypeVar, Generic +from pydantic.generics import GenericModel + +TypeX = TypeVar('TypeX') +TypeY = TypeVar('TypeY') +TypeZ = TypeVar('TypeZ') + + +class BaseClass(GenericModel, Generic[TypeX, TypeY]): + x: TypeX + y: TypeY + + +class ChildClass(BaseClass[int, TypeY], Generic[TypeY, TypeZ]): + z: TypeZ + + +# Replace TypeY by str +print(ChildClass[str, int](x=1, y='y', z=3)) diff --git a/pydantic/generics.py b/pydantic/generics.py --- a/pydantic/generics.py +++ b/pydantic/generics.py @@ -6,6 +6,7 @@ Callable, ClassVar, Dict, + Generic, Optional, Tuple, Type, @@ -41,7 +42,7 @@ def __class_getitem__(cls: Type[GenericModelT], params: Union[Type[Any], Tuple[T cached = _generic_types_cache.get((cls, params)) if cached is not None: return cached - if cls.__concrete__: + if cls.__concrete__ and Generic not in cls.__bases__: raise TypeError('Cannot parameterize a concrete instantiation of a generic model') if not isinstance(params, tuple): params = (params,)
pydantic/pydantic
6b53cabe036a907a117e3530719befef2c417ae1
diff --git a/tests/test_generics.py b/tests/test_generics.py --- a/tests/test_generics.py +++ b/tests/test_generics.py @@ -600,6 +600,28 @@ class Model(GenericModel, Generic[AT, BT]): ] +@skip_36 +def test_generic_subclass_of_concrete_generic(): + T = TypeVar('T') + U = TypeVar('U') + + class GenericBaseModel(GenericModel, Generic[T]): + data: T + + class GenericSub(GenericBaseModel[int], Generic[U]): + extra: U + + ConcreteSub = GenericSub[int] + + with pytest.raises(ValidationError): + ConcreteSub(data=2, extra='wrong') + + with pytest.raises(ValidationError): + ConcreteSub(data='wrong', extra=2) + + ConcreteSub(data=2, extra=3) + + @skip_36 def test_generic_model_pickle(create_module): # Using create_module because pickle doesn't support
GenericModel - Allow subclasses of concrete generics to be generic ### 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 feature/change is needed * [x] After submitting this, I commit to one of: * Look through open issues and helped at least one other person * Hit the "watch" button on this repo to receive notifications and I commit to help at least 2 people that ask questions in the future * Implement a Pull Request for a confirmed bug # Feature Request Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.6.1 pydantic compiled: False install path: /wayfair/home/ch438l/pydantic/pydantic python version: 3.6.8 (default, Aug 10 2019, 06:54:07) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] platform: Linux-3.10.0-862.3.2.el7.x86_64-x86_64-with-centos-7.5.1804-Core optional deps. installed: ['typing-extensions', 'email-validator', 'devtools'] ``` I'd like to be able to define a generic model, then create a subclass of that generic model that both fills in the type parameter of the superclass, while introducing new type parameters. Here's a currently failing test case that illustrates the issue: ```py @skip_36 def test_generic_subclass_of_concrete_generic(): T = TypeVar("T") U = TypeVar("U") class GenericBaseModel(GenericModel, Generic[T]): data: T class GenericSub(GenericBaseModel[int], Generic[U]): extra: U GenericSub[str] ``` Currently that test case fails with `TypeError: Cannot parameterize a concrete instantiation of a generic model` This happens because `GenericBaseModel[int].__concrete__` gets set to `True`, and `GenericSub` inherits it. This can easily be fixed with the following change to `generics.py`: ```py if cls.__concrete__: raise TypeError('Cannot parameterize a concrete instantiation of a generic model') ``` Should become ```py if cls.__concrete__ and typing.Generic not in cls.__bases__: raise TypeError('Cannot parameterize a concrete instantiation of a generic model') ```
0.0
6b53cabe036a907a117e3530719befef2c417ae1
[ "tests/test_generics.py::test_generic_subclass_of_concrete_generic" ]
[ "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_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", "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_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_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_module_name_from_function", "tests/test_generics.py::test_get_caller_module_name_from_module", "tests/test_generics.py::test_get_caller_module_name_not_found", "tests/test_generics.py::test_is_call_from_module" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files" ], "has_test_patch": true, "is_lite": false }
2020-10-14 17:48:26+00:00
mit
4,759
pydantic__pydantic-2051
diff --git a/docs/examples/dataclasses_arbitrary_types_allowed.py b/docs/examples/dataclasses_arbitrary_types_allowed.py new file mode 100644 --- /dev/null +++ b/docs/examples/dataclasses_arbitrary_types_allowed.py @@ -0,0 +1,42 @@ +import dataclasses + +import pydantic + + +class ArbitraryType: + def __init__(self, value): + self.value = value + + def __repr__(self): + return f'ArbitraryType(value={self.value!r})' + + [email protected] +class DC: + a: ArbitraryType + b: str + + +# valid as it is a builtin dataclass without validation +my_dc = DC(a=ArbitraryType(value=3), b='qwe') + +try: + class Model(pydantic.BaseModel): + dc: DC + other: str + + Model(dc=my_dc, other='other') +except RuntimeError as e: # invalid as it is now a pydantic dataclass + print(e) + + +class Model(pydantic.BaseModel): + dc: DC + other: str + + class Config: + arbitrary_types_allowed = True + + +m = Model(dc=my_dc, other='other') +print(repr(m)) diff --git a/docs/examples/dataclasses_stdlib_inheritance.py b/docs/examples/dataclasses_stdlib_inheritance.py new file mode 100644 --- /dev/null +++ b/docs/examples/dataclasses_stdlib_inheritance.py @@ -0,0 +1,27 @@ +import dataclasses + +import pydantic + + [email protected] +class Z: + z: int + + [email protected] +class Y(Z): + y: int = 0 + + [email protected] +class X(Y): + x: int = 0 + + +foo = X(x=b'1', y='2', z='3') +print(foo) + +try: + X(z='pika') +except pydantic.ValidationError as e: + print(e) diff --git a/pydantic/dataclasses.py b/pydantic/dataclasses.py --- a/pydantic/dataclasses.py +++ b/pydantic/dataclasses.py @@ -8,7 +8,7 @@ from .utils import ClassAttribute if TYPE_CHECKING: - from .main import BaseModel # noqa: F401 + from .main import BaseConfig, BaseModel # noqa: F401 from .typing import CallableGenerator DataclassT = TypeVar('DataclassT', bound='Dataclass') @@ -120,7 +120,9 @@ def _pydantic_post_init(self: 'Dataclass', *initvars: Any) -> None: # ``` # with the exact same fields as the base dataclass if is_builtin_dataclass(_cls): - _cls = type(_cls.__name__, (_cls,), {'__post_init__': _pydantic_post_init}) + _cls = type( + _cls.__name__, (_cls,), {'__annotations__': _cls.__annotations__, '__post_init__': _pydantic_post_init} + ) else: _cls.__post_init__ = _pydantic_post_init cls: Type['Dataclass'] = dataclasses.dataclass( # type: ignore @@ -214,10 +216,10 @@ def wrap(cls: Type[Any]) -> Type['Dataclass']: return wrap(_cls) -def make_dataclass_validator(_cls: Type[Any], **kwargs: Any) -> 'CallableGenerator': +def make_dataclass_validator(_cls: Type[Any], config: Type['BaseConfig']) -> 'CallableGenerator': """ Create a pydantic.dataclass from a builtin dataclass to add type validation and yield the validators """ - cls = dataclass(_cls, **kwargs) + cls = dataclass(_cls, config=config) yield from _get_validators(cls) diff --git a/pydantic/validators.py b/pydantic/validators.py --- a/pydantic/validators.py +++ b/pydantic/validators.py @@ -593,7 +593,7 @@ def find_validators( # noqa: C901 (ignore complexity) yield make_literal_validator(type_) return if is_builtin_dataclass(type_): - yield from make_dataclass_validator(type_) + yield from make_dataclass_validator(type_, config) return if type_ is Enum: yield enum_validator
pydantic/pydantic
95435de4526b609ee904b7a27478cec2e32f8fe8
diff --git a/tests/test_dataclasses.py b/tests/test_dataclasses.py --- a/tests/test_dataclasses.py +++ b/tests/test_dataclasses.py @@ -2,7 +2,7 @@ from collections.abc import Hashable from datetime import datetime from pathlib import Path -from typing import ClassVar, Dict, FrozenSet, Optional +from typing import ClassVar, Dict, FrozenSet, List, Optional import pytest @@ -738,3 +738,42 @@ class File: 'title': 'File', 'type': 'object', } + + +def test_inherit_builtin_dataclass(): + @dataclasses.dataclass + class Z: + z: int + + @dataclasses.dataclass + class Y(Z): + y: int + + @pydantic.dataclasses.dataclass + class X(Y): + x: int + + pika = X(x='2', y='4', z='3') + assert pika.x == 2 + assert pika.y == 4 + assert pika.z == 3 + + +def test_dataclass_arbitrary(): + class ArbitraryType: + def __init__(self): + ... + + @dataclasses.dataclass + class Test: + foo: ArbitraryType + bar: List[ArbitraryType] + + class TestModel(BaseModel): + a: ArbitraryType + b: Test + + class Config: + arbitrary_types_allowed = True + + TestModel(a=ArbitraryType(), b=(ArbitraryType(), [ArbitraryType()]))
arbitrary_types_allowed not respected when validating stdlib dataclasses ### 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.7 pydantic compiled: True install path: /Users/ines/Repos/explosion/spacy/.env37/lib/python3.7/site-packages/pydantic python version: 3.7.2 (default, Oct 6 2019, 23:51:55) [Clang 10.0.1 (clang-1001.0.46.4)] platform: Darwin-19.5.0-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: --> As of v1.7, Pydantic validates dataclasses and their contents, but it fails if the dataclass specifies arbitrary types (which is pretty common in our code bases). Here's an example: ```py from typing import List from dataclasses import dataclass from pydantic import BaseModel class ArbitraryType: def __init__(self): ... @dataclass class Test: foo: ArbitraryType bar: List[ArbitraryType] class TestModel(BaseModel): a: ArbitraryType # this is fine b: Test # this raises RuntimeError class Config: arbitrary_types_allowed = True ``` Even though the `BaseModel` subclass sets `arbitrary_types_allowed` to `True`, this configuration doesn't seem to be taken into account when validating the dataclass fields. Adding custom validation to our dataclasses isn't really an option, since we wouldn't want those Pydantic specifics to leak into the rest of the code base. I'm also wondering whether there should be an option to _not_ validate stdlib dataclasses as Pydantic dataclasses and just use a basic instance check instead, like it previously did (?) before v1.7?
0.0
95435de4526b609ee904b7a27478cec2e32f8fe8
[ "tests/test_dataclasses.py::test_inherit_builtin_dataclass", "tests/test_dataclasses.py::test_dataclass_arbitrary" ]
[ "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_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" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-10-27 09:17:25+00:00
mit
4,760
pydantic__pydantic-2056
diff --git a/pydantic/json.py b/pydantic/json.py --- a/pydantic/json.py +++ b/pydantic/json.py @@ -5,7 +5,7 @@ from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network from pathlib import Path from types import GeneratorType -from typing import Any, Callable, Dict, Type, Union +from typing import Any, Callable, Dict, Pattern, Type, Union from uuid import UUID from .color import Color @@ -54,6 +54,9 @@ def pydantic_encoder(obj: Any) -> Any: elif is_dataclass(obj): return asdict(obj) + if isinstance(obj, Pattern): + return obj.pattern + # Check the class type and its superclasses for a matching encoder for base in obj.__class__.__mro__[:-1]: try:
pydantic/pydantic
95435de4526b609ee904b7a27478cec2e32f8fe8
diff --git a/tests/test_json.py b/tests/test_json.py --- a/tests/test_json.py +++ b/tests/test_json.py @@ -1,5 +1,6 @@ import datetime import json +import re import sys from dataclasses import dataclass as vanilla_dataclass from decimal import Decimal @@ -51,6 +52,7 @@ class MyEnum(Enum): (Decimal('12.34'), '12.34'), (create_model('BarModel', a='b', c='d')(), '{"a": "b", "c": "d"}'), (MyEnum.foo, '"bar"'), + (re.compile('^regex$'), '"^regex$"'), ], ) def test_encoding(input, output):
Pattern type serialisation error ### 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.7 pydantic compiled: True install path: /root/.local/lib/python3.8/site-packages/pydantic python version: 3.8.6 (default, Oct 13 2020, 20:49:19) [GCC 8.3.0] platform: Linux-3.10.0-1127.19.1.el7.x86_64-x86_64-with-glibc2.2.5 optional deps. installed: ['email-validator'] ``` <!-- 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 Pattern from pydantic import BaseModel class Model(BaseModel): filter: Pattern Model(filter="^regex$").json() ``` This produce an error : TypeError: Object of type 'Pattern' is not JSON serializable I had to write a custom encoder to be able to serialize properly a Pattern type : ```py from typing import Pattern from pydantic import BaseModel import re class Model(BaseModel): filter: Pattern class Config: json_encoders = { re.Pattern: lambda v: v.pattern, } Model(filter="^regex$").json() ```
0.0
95435de4526b609ee904b7a27478cec2e32f8fe8
[ "tests/test_json.py::test_encoding[^regex$-\"^regex$\"]" ]
[ "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[<genexpr>-[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_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_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", "tests/test_json.py::test_custom_decode_encode" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2020-10-27 16:24:08+00:00
mit
4,761
pydantic__pydantic-2064
diff --git a/docs/examples/exporting_models_json_encoders_merge.py b/docs/examples/exporting_models_json_encoders_merge.py new file mode 100644 --- /dev/null +++ b/docs/examples/exporting_models_json_encoders_merge.py @@ -0,0 +1,24 @@ +from datetime import datetime, timedelta +from pydantic import BaseModel +from pydantic.json import timedelta_isoformat + + +class BaseClassWithEncoders(BaseModel): + dt: datetime + diff: timedelta + + class Config: + json_encoders = { + datetime: lambda v: v.timestamp() + } + + +class ChildClassWithEncoders(BaseClassWithEncoders): + class Config: + json_encoders = { + timedelta: timedelta_isoformat + } + + +m = ChildClassWithEncoders(dt=datetime(2032, 6, 1), diff=timedelta(hours=100)) +print(m.json()) diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -170,13 +170,19 @@ def prepare_field(cls, field: 'ModelField') -> None: def inherit_config(self_config: 'ConfigType', parent_config: 'ConfigType') -> 'ConfigType': + namespace = {} if not self_config: base_classes = (parent_config,) elif self_config == parent_config: base_classes = (self_config,) else: base_classes = self_config, parent_config # type: ignore - return type('Config', base_classes, {}) + namespace['json_encoders'] = { + **getattr(parent_config, 'json_encoders', {}), + **getattr(self_config, 'json_encoders', {}), + } + + return type('Config', base_classes, namespace) EXTRA_LINK = 'https://pydantic-docs.helpmanual.io/usage/model_config/'
pydantic/pydantic
78934db63169bf6bc661b2c63f61f996bea5deff
diff --git a/tests/test_json.py b/tests/test_json.py --- a/tests/test_json.py +++ b/tests/test_json.py @@ -170,6 +170,35 @@ class Config: assert m.json() == '{"x": "P0DT0H2M3.000000S"}' +def test_json_encoder_simple_inheritance(): + class Parent(BaseModel): + dt: datetime.datetime = datetime.datetime.now() + timedt: datetime.timedelta = datetime.timedelta(hours=100) + + class Config: + json_encoders = {datetime.datetime: lambda _: 'parent_encoder'} + + class Child(Parent): + class Config: + json_encoders = {datetime.timedelta: lambda _: 'child_encoder'} + + assert Child().json() == '{"dt": "parent_encoder", "timedt": "child_encoder"}' + + +def test_json_encoder_inheritance_override(): + class Parent(BaseModel): + dt: datetime.datetime = datetime.datetime.now() + + class Config: + json_encoders = {datetime.datetime: lambda _: 'parent_encoder'} + + class Child(Parent): + class Config: + json_encoders = {datetime.datetime: lambda _: 'child_encoder'} + + assert Child().json() == '{"dt": "child_encoder"}' + + def test_custom_encoder_arg(): class Model(BaseModel): x: datetime.timedelta
json_encoders inheritance # Feature Request Currently, defining `json_encoders` in child classes completely overrides the one defined from the parent classes: ```py from datetime import datetime, timedelta from pydantic import BaseModel class A(BaseModel): dt: datetime = datetime.now() class Config: json_encoders = {datetime: lambda _: "encoded_from_A"} print(A().json()) #> {"dt": "encoded_from_A"} class B(A): timedt: timedelta = timedelta(hours=100) class Config: json_encoders = {timedelta: lambda _: "encoded_from_B"} print(B().json()) #> {"dt": "2020-10-23T01:11:20.613624", "timedt": "encoded_from_B"} ``` I think it would be handy to merge the JSON encoders with the one defined in the parent ones, thus the result would be: ```py print(B().json()) #> {"dt": "encoded_from_A", "timedt": "encoded_from_B"} ``` As an extension, it should still be possible to override the parent ones: ```py class Bbis(A): timedt: timedelta = timedelta(hours=100) class Config: json_encoders = { datetime: lambda _: "encoded_from_Bbis", timedelta: lambda _: "encoded_from_Bbis", } print(Bbis().json()) #> {"dt": "encoded_from_Bbis", "timedt": "encoded_from_Bbis"} ``` I'm eager to implement this feature if you think it's worth it :smile:
0.0
78934db63169bf6bc661b2c63f61f996bea5deff
[ "tests/test_json.py::test_json_encoder_simple_inheritance" ]
[ "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[<genexpr>-[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_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_custom_encoder", "tests/test_json.py::test_custom_iso_timedelta", "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" ]
{ "failed_lite_validators": [ "has_added_files" ], "has_test_patch": true, "is_lite": false }
2020-10-28 18:06:57+00:00
mit
4,762
pydantic__pydantic-2066
diff --git a/docs/examples/dataclasses_stdlib_with_basemodel.py b/docs/examples/dataclasses_stdlib_with_basemodel.py --- a/docs/examples/dataclasses_stdlib_with_basemodel.py +++ b/docs/examples/dataclasses_stdlib_with_basemodel.py @@ -5,14 +5,20 @@ from pydantic import BaseModel, ValidationError [email protected](frozen=True) +class User: + name: str + + @dataclasses.dataclass class File: filename: str - last_modification_time: Optional[datetime] + last_modification_time: Optional[datetime] = None class Foo(BaseModel): file: File + user: Optional[User] = None file = File( @@ -25,3 +31,9 @@ class Foo(BaseModel): Foo(file=file) except ValidationError as e: print(e) + +foo = Foo(file=File(filename='myfile'), user=User(name='pika')) +try: + foo.user.name = 'bulbi' +except dataclasses.FrozenInstanceError as e: + print(e) diff --git a/pydantic/dataclasses.py b/pydantic/dataclasses.py --- a/pydantic/dataclasses.py +++ b/pydantic/dataclasses.py @@ -220,6 +220,9 @@ def make_dataclass_validator(_cls: Type[Any], config: Type['BaseConfig']) -> 'Ca """ Create a pydantic.dataclass from a builtin dataclass to add type validation and yield the validators + It retrieves the parameters of the dataclass and forwards them to the newly created dataclass """ - cls = dataclass(_cls, config=config) + dataclass_params = _cls.__dataclass_params__ + stdlib_dataclass_parameters = {param: getattr(dataclass_params, param) for param in dataclass_params.__slots__} + cls = dataclass(_cls, config=config, **stdlib_dataclass_parameters) yield from _get_validators(cls)
pydantic/pydantic
8dcc87cf422c8344ca565c8ee23b7119bc100949
I've just released v1.7.1 (it'll take 10 minutes or so to be available on pypi), please let me know if that fixes your problem. Hmm damn...20 min after and I would have fixed it in my PR. v1.7.1 doesn't fix it
diff --git a/tests/test_dataclasses.py b/tests/test_dataclasses.py --- a/tests/test_dataclasses.py +++ b/tests/test_dataclasses.py @@ -777,3 +777,21 @@ class Config: arbitrary_types_allowed = True TestModel(a=ArbitraryType(), b=(ArbitraryType(), [ArbitraryType()])) + + +def test_forward_stdlib_dataclass_params(): + @dataclasses.dataclass(frozen=True) + class Item: + name: str + + class Example(BaseModel): + item: Item + other: str + + class Config: + arbitrary_types_allowed = True + + e = Example(item=Item(name='pika'), other='bulbi') + e.other = 'bulbi2' + with pytest.raises(dataclasses.FrozenInstanceError): + e.item.name = 'pika2'
Frozen dataclass behavior change 1.6.1 -> 1.7 ### 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.7 pydantic compiled: True install path: /home/user/miniconda3/envs/debug_pydantic/lib/python3.8/site-packages/pydantic python version: 3.8.2 (default, May 7 2020, 20:00:49) [GCC 7.3.0] platform: Linux-5.4.0-52-generic-x86_64-with-glibc2.10 optional deps. installed: [] ``` <!-- 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: --> This code works in v1.6.1: ```py from dataclasses import dataclass from pydantic import BaseModel @dataclass(frozen=True) class Item: name: str class Example(BaseModel): item: Item class Config: arbitrary_types_allowed = True ``` However, in v1.7, it produces the following error: ```py Traceback (most recent call last): File "/home/user/debug_pydantic.py", line 11, in <module> class Example(BaseModel): File "pydantic/main.py", line 262, in pydantic.main.ModelMetaclass.__new__ File "pydantic/fields.py", line 315, in pydantic.fields.ModelField.infer File "pydantic/fields.py", line 284, in pydantic.fields.ModelField.__init__ File "pydantic/fields.py", line 362, in pydantic.fields.ModelField.prepare File "pydantic/fields.py", line 538, in pydantic.fields.ModelField.populate_validators File "pydantic/validators.py", line 596, in find_validators File "pydantic/dataclasses.py", line 222, in make_dataclass_validator # and only from the field() function, although Field instances are File "pydantic/dataclasses.py", line 214, in pydantic.dataclasses.dataclass type_name = self.type.__name__ File "pydantic/dataclasses.py", line 209, in pydantic.dataclasses.dataclass.wrap def __init__(self, type): File "pydantic/dataclasses.py", line 126, in pydantic.dataclasses._process_class # +=======+=======+=======+========+========+ File "/home/user/miniconda3/envs/debug_pydantic/lib/python3.8/dataclasses.py", line 1019, in dataclass return wrap(cls) File "/home/user/miniconda3/envs/debug_pydantic/lib/python3.8/dataclasses.py", line 1011, in wrap return _process_class(cls, init, repr, eq, order, unsafe_hash, frozen) File "/home/user/miniconda3/envs/debug_pydantic/lib/python3.8/dataclasses.py", line 891, in _process_class raise TypeError('cannot inherit non-frozen dataclass from a ' TypeError: cannot inherit non-frozen dataclass from a frozen one ``` Looking through the changelog, this does not appear to be an intentional change. I can remove the `frozen=True` attribute of the dataclass decorator as a workaround, but this seems less than ideal.
0.0
8dcc87cf422c8344ca565c8ee23b7119bc100949
[ "tests/test_dataclasses.py::test_forward_stdlib_dataclass_params" ]
[ "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_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" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2020-10-28 20:04:26+00:00
mit
4,763
pydantic__pydantic-2075
diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -384,14 +384,14 @@ def __setattr__(self, name, value): # noqa: C901 (ignore complexity) known_field = self.__fields__.get(name, None) if known_field: - original_value = self.__dict__.pop(name) - try: - value, error_ = known_field.validate(value, self.__dict__, loc=name, cls=self.__class__) - if error_: - raise ValidationError([error_], self.__class__) - except Exception: - self.__dict__[name] = original_value - raise + # We want to + # - make sure validators are called without the current value for this field inside `values` + # - keep other values (e.g. submodels) untouched (using `BaseModel.dict()` will change them into dicts) + # - keep the order of the fields + dict_without_original_value = {k: v for k, v in self.__dict__.items() if k != name} + value, error_ = known_field.validate(value, dict_without_original_value, loc=name, cls=self.__class__) + if error_: + raise ValidationError([error_], self.__class__) else: new_values[name] = value
pydantic/pydantic
8dcc87cf422c8344ca565c8ee23b7119bc100949
diff --git a/tests/test_validators.py b/tests/test_validators.py --- a/tests/test_validators.py +++ b/tests/test_validators.py @@ -5,7 +5,7 @@ import pytest -from pydantic import BaseModel, ConfigError, Extra, ValidationError, errors, validator +from pydantic import BaseModel, ConfigError, Extra, Field, ValidationError, errors, validator from pydantic.class_validators import make_generic_validator, root_validator from pydantic.typing import Literal @@ -1162,7 +1162,8 @@ def test_field_that_is_being_validated_is_excluded_from_validator_values(mocker) class Model(BaseModel): foo: str - bar: str + bar: str = Field(alias='pika') + baz: str class Config: validate_assignment = True @@ -1170,12 +1171,27 @@ class Config: @validator('foo') def validate_foo(cls, v, values): check_values({**values}) + return v + + @validator('bar') + def validate_bar(cls, v, values): + check_values({**values}) + return v - model = Model(foo='foo_value', bar='bar_value') + model = Model(foo='foo_value', pika='bar_value', baz='baz_value') check_values.reset_mock() + assert list(dict(model).items()) == [('foo', 'foo_value'), ('bar', 'bar_value'), ('baz', 'baz_value')] + model.foo = 'new_foo_value' - check_values.assert_called_once_with({'bar': 'bar_value'}) + check_values.assert_called_once_with({'bar': 'bar_value', 'baz': 'baz_value'}) + check_values.reset_mock() + + model.bar = 'new_bar_value' + check_values.assert_called_once_with({'foo': 'new_foo_value', 'baz': 'baz_value'}) + + # ensure field order is the same + assert list(dict(model).items()) == [('foo', 'new_foo_value'), ('bar', 'new_bar_value'), ('baz', 'baz_value')] def test_exceptions_in_field_validators_restore_original_field_value():
`validate_assignment` changes the field order ### 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 <!-- Sorry to sound so draconian, but every second saved replying to issues is time spend improving pydantic :-) --> # Bug ``` pydantic version: 1.7.1 pydantic compiled: True install path: /home/user/work/bugs/python/pydantic-ordering/.venv/lib/python3.8/site-packages/pydantic python version: 3.8.5 (default, Jul 28 2020, 12:59:40) [GCC 9.3.0] platform: Linux-4.19.128-microsoft-standard-x86_64-with-glibc2.29 optional deps. installed: [] ``` <!-- 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: --> Including `validate_assignment = True` in a model's config seems to cause assignment to change the field order when using `dict()`. This change was discovered when upgrading to 1.7.0 and also applies to 1.7.1, but was not present in prior versions. This behaviour does not seem to agree with <https://pydantic-docs.helpmanual.io/usage/models/#field-ordering>, and is something that is important for my uses (where it generates massive diffs in the output) and surely others. Running this snippet with and without the `validate_assignment` line produces different output: ```py from pydantic import BaseModel class Model(BaseModel): title: str = '' name: str = '' class Config: validate_assignment = True ... m = Model(name='name') m.title = 'title' print(m.dict()) ```
0.0
8dcc87cf422c8344ca565c8ee23b7119bc100949
[ "tests/test_validators.py::test_field_that_is_being_validated_is_excluded_from_validator_values" ]
[ "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_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_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_nested_literal_validator", "tests/test_validators.py::test_exceptions_in_field_validators_restore_original_field_value" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2020-10-30 08:27:12+00:00
mit
4,764
pydantic__pydantic-2092
diff --git a/docs/examples/model_config_smart_union_off.py b/docs/examples/model_config_smart_union_off.py new file mode 100644 --- /dev/null +++ b/docs/examples/model_config_smart_union_off.py @@ -0,0 +1,19 @@ +from typing import Union + +from pydantic import BaseModel + + +class Foo(BaseModel): + pass + + +class Bar(BaseModel): + pass + + +class Model(BaseModel): + x: Union[str, int] + y: Union[Foo, Bar] + + +print(Model(x=1, y=Bar())) diff --git a/docs/examples/model_config_smart_union_on.py b/docs/examples/model_config_smart_union_on.py new file mode 100644 --- /dev/null +++ b/docs/examples/model_config_smart_union_on.py @@ -0,0 +1,22 @@ +from typing import Union + +from pydantic import BaseModel + + +class Foo(BaseModel): + pass + + +class Bar(BaseModel): + pass + + +class Model(BaseModel): + x: Union[str, int] + y: Union[Foo, Bar] + + class Config: + smart_union = True + + +print(Model(x=1, y=Bar())) diff --git a/docs/examples/model_config_smart_union_on_edge_case.py b/docs/examples/model_config_smart_union_on_edge_case.py new file mode 100644 --- /dev/null +++ b/docs/examples/model_config_smart_union_on_edge_case.py @@ -0,0 +1,14 @@ +from typing import List, Union + +from pydantic import BaseModel + + +class Model(BaseModel, smart_union=True): + x: Union[List[str], List[int]] + + +# Expected coercion +print(Model(x=[1, '2'])) + +# Unexpected coercion +print(Model(x=[1, 2])) diff --git a/pydantic/config.py b/pydantic/config.py --- a/pydantic/config.py +++ b/pydantic/config.py @@ -63,8 +63,10 @@ class BaseConfig: json_encoders: Dict[Type[Any], AnyCallable] = {} underscore_attrs_are_private: bool = False - # Whether or not inherited models as fields should be reconstructed as base model + # whether inherited models as fields should be reconstructed as base model copy_on_model_validation: bool = True + # whether `Union` should check all allowed types before even trying to coerce + smart_union: bool = False @classmethod def get_field_info(cls, name: str) -> Dict[str, Any]: diff --git a/pydantic/env_settings.py b/pydantic/env_settings.py --- a/pydantic/env_settings.py +++ b/pydantic/env_settings.py @@ -6,7 +6,7 @@ from .config import BaseConfig, Extra from .fields import ModelField from .main import BaseModel -from .typing import StrPath, display_as_type, get_origin, is_union_origin +from .typing import StrPath, display_as_type, get_origin, is_union from .utils import deep_update, path_type, sequence_like env_file_sentinel = str(object()) @@ -175,9 +175,7 @@ def __call__(self, settings: BaseSettings) -> Dict[str, Any]: except ValueError as e: raise SettingsError(f'error parsing JSON for "{env_name}"') from e elif ( - is_union_origin(get_origin(field.type_)) - and field.sub_fields - and any(f.is_complex() for f in field.sub_fields) + is_union(get_origin(field.type_)) and field.sub_fields and any(f.is_complex() for f in field.sub_fields) ): try: env_val = settings.__config__.json_loads(env_val) diff --git a/pydantic/fields.py b/pydantic/fields.py --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -42,7 +42,7 @@ is_new_type, is_none_type, is_typeddict, - is_union_origin, + is_union, new_type_supertype, ) from .utils import PyObjectStr, Representation, ValueItems, lenient_issubclass, sequence_like, smart_deepcopy @@ -560,7 +560,7 @@ def _type_analysis(self) -> None: # noqa: C901 (ignore complexity) return if origin is Callable: return - if is_union_origin(origin): + if is_union(origin): types_ = [] for type_ in get_args(self.type_): if type_ is NoneType: @@ -935,6 +935,35 @@ def _validate_singleton( ) -> 'ValidateReturn': if self.sub_fields: errors = [] + + if self.model_config.smart_union and is_union(get_origin(self.type_)): + # 1st pass: check if the value is an exact instance of one of the Union types + # (e.g. to avoid coercing a bool into an int) + for field in self.sub_fields: + if v.__class__ is field.outer_type_: + return v, None + + # 2nd pass: check if the value is an instance of any subclass of the Union types + for field in self.sub_fields: + # This whole logic will be improved later on to support more complex `isinstance` checks + # It will probably be done once a strict mode is added and be something like: + # ``` + # value, error = field.validate(v, values, strict=True) + # if error is None: + # return value, None + # ``` + try: + if isinstance(v, field.outer_type_): + return v, None + except TypeError: + # compound type + if isinstance(v, get_origin(field.outer_type_)): + value, error = field.validate(v, values, loc=loc, cls=cls) + if not error: + return value, None + + # 1st pass by default or 3rd pass with `smart_union` enabled: + # check if the value can be coerced into one of the Union types for field in self.sub_fields: value, error = field.validate(v, values, loc=loc, cls=cls) if error: diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -39,7 +39,7 @@ get_origin, is_classvar, is_namedtuple, - is_union_origin, + is_union, resolve_annotations, update_model_forward_refs, ) @@ -191,7 +191,7 @@ def is_untouched(v: Any) -> bool: elif is_valid_field(ann_name): validate_field_name(bases, ann_name) value = namespace.get(ann_name, Undefined) - allowed_types = get_args(ann_type) if is_union_origin(get_origin(ann_type)) else (ann_type,) + allowed_types = get_args(ann_type) if is_union(get_origin(ann_type)) else (ann_type,) if ( is_untouched(value) and ann_type != PyObject diff --git a/pydantic/schema.py b/pydantic/schema.py --- a/pydantic/schema.py +++ b/pydantic/schema.py @@ -72,7 +72,7 @@ is_literal_type, is_namedtuple, is_none_type, - is_union_origin, + is_union, ) from .utils import ROOT_KEY, get_model, lenient_issubclass, sequence_like @@ -995,7 +995,7 @@ def go(type_: Any) -> Type[Any]: if origin is Annotated: return go(args[0]) - if is_union_origin(origin): + if is_union(origin): return Union[tuple(go(a) for a in args)] # type: ignore if issubclass(origin, List) and (field_info.min_items is not None or field_info.max_items is not None): diff --git a/pydantic/typing.py b/pydantic/typing.py --- a/pydantic/typing.py +++ b/pydantic/typing.py @@ -193,7 +193,7 @@ def get_args(tp: Type[Any]) -> Tuple[Any, ...]: if sys.version_info < (3, 10): - def is_union_origin(tp: Type[Any]) -> bool: + def is_union(tp: Type[Any]) -> bool: return tp is Union WithArgsTypes = (TypingGenericAlias,) @@ -202,8 +202,8 @@ def is_union_origin(tp: Type[Any]) -> bool: import types import typing - def is_union_origin(origin: Type[Any]) -> bool: - return origin is Union or origin is types.UnionType # noqa: E721 + def is_union(tp: Type[Any]) -> bool: + return tp is Union or tp is types.UnionType # noqa: E721 WithArgsTypes = (typing._GenericAlias, types.GenericAlias, types.UnionType) @@ -269,7 +269,7 @@ def is_union_origin(origin: Type[Any]) -> bool: 'get_origin', 'typing_base', 'get_all_type_hints', - 'is_union_origin', + 'is_union', 'StrPath', )
pydantic/pydantic
415eb54f966f0eec7cb2fd0aa61492c17e606367
diff --git a/tests/test_types.py b/tests/test_types.py --- a/tests/test_types.py +++ b/tests/test_types.py @@ -22,6 +22,7 @@ Sequence, Set, Tuple, + Union, ) from uuid import UUID @@ -2838,6 +2839,143 @@ class Model(BaseModel): ] +def test_default_union_types(): + class DefaultModel(BaseModel): + v: Union[int, bool, str] + + assert DefaultModel(v=True).dict() == {'v': 1} + assert DefaultModel(v=1).dict() == {'v': 1} + assert DefaultModel(v='1').dict() == {'v': 1} + + # In 3.6, Union[int, bool, str] == Union[int, str] + allowed_json_types = ('integer', 'string') if sys.version_info[:2] == (3, 6) else ('integer', 'boolean', 'string') + + assert DefaultModel.schema() == { + 'title': 'DefaultModel', + 'type': 'object', + 'properties': {'v': {'title': 'V', 'anyOf': [{'type': t} for t in allowed_json_types]}}, + 'required': ['v'], + } + + +def test_smart_union_types(): + class SmartModel(BaseModel): + v: Union[int, bool, str] + + class Config: + smart_union = True + + assert SmartModel(v=1).dict() == {'v': 1} + assert SmartModel(v=True).dict() == {'v': True} + assert SmartModel(v='1').dict() == {'v': '1'} + + # In 3.6, Union[int, bool, str] == Union[int, str] + allowed_json_types = ('integer', 'string') if sys.version_info[:2] == (3, 6) else ('integer', 'boolean', 'string') + + assert SmartModel.schema() == { + 'title': 'SmartModel', + 'type': 'object', + 'properties': {'v': {'title': 'V', 'anyOf': [{'type': t} for t in allowed_json_types]}}, + 'required': ['v'], + } + + +def test_default_union_class(): + class A(BaseModel): + x: str + + class B(BaseModel): + x: str + + class Model(BaseModel): + y: Union[A, B] + + assert isinstance(Model(y=A(x='a')).y, A) + # `B` instance is coerced to `A` + assert isinstance(Model(y=B(x='b')).y, A) + + +def test_smart_union_class(): + class A(BaseModel): + x: str + + class B(BaseModel): + x: str + + class Model(BaseModel): + y: Union[A, B] + + class Config: + smart_union = True + + assert isinstance(Model(y=A(x='a')).y, A) + assert isinstance(Model(y=B(x='b')).y, B) + + +def test_default_union_subclass(): + class MyStr(str): + ... + + class Model(BaseModel): + x: Union[int, str] + + assert Model(x=MyStr('1')).x == 1 + + +def test_smart_union_subclass(): + class MyStr(str): + ... + + class Model(BaseModel): + x: Union[int, str] + + class Config: + smart_union = True + + assert Model(x=MyStr('1')).x == '1' + + +def test_default_union_compound_types(): + class Model(BaseModel): + values: Union[Dict[str, str], List[str]] + + assert Model(values={'L': '1'}).dict() == {'values': {'L': '1'}} + assert Model(values=['L1']).dict() == {'values': {'L': '1'}} # dict(['L1']) == {'L': '1'} + + +def test_smart_union_compound_types(): + class Model(BaseModel): + values: Union[Dict[str, str], List[str], Dict[str, List[str]]] + + class Config: + smart_union = True + + assert Model(values={'L': '1'}).dict() == {'values': {'L': '1'}} + assert Model(values=['L1']).dict() == {'values': ['L1']} + assert Model(values=('L1',)).dict() == {'values': {'L': '1'}} # expected coercion into first dict if not a list + assert Model(values={'x': ['pika']}) == {'values': {'x': ['pika']}} + assert Model(values={'x': ('pika',)}).dict() == {'values': {'x': ['pika']}} + with pytest.raises(ValidationError) as e: + Model(values={'x': {'a': 'b'}}) + assert e.value.errors() == [ + {'loc': ('values', 'x'), 'msg': 'str type expected', 'type': 'type_error.str'}, + {'loc': ('values',), 'msg': 'value is not a valid list', 'type': 'type_error.list'}, + {'loc': ('values', 'x'), 'msg': 'value is not a valid list', 'type': 'type_error.list'}, + ] + + +def test_smart_union_compouned_types_edge_case(): + """For now, `smart_union` does not support well compound types""" + + class Model(BaseModel, smart_union=True): + x: Union[List[str], List[int]] + + # should consider [1, 2] valid and not coerce once `smart_union` is improved + assert Model(x=[1, 2]).x == ['1', '2'] + # still coerce if needed + assert Model(x=[1, '2']).x == ['1', '2'] + + @pytest.mark.parametrize( 'value,result', (
Wrong assignement of values in `Union[Foo, List[Foo]]` ### 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 validating a model that allows either a single object `Foo` or a list of `Foo` objects, the wrong values are assigned. The key of the second parameter is assigned as value of the first parameter (which is a string). Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.8.2 pydantic compiled: True install path: /home/anaconda3/envs/py38/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.11.0-38-generic-x86_64-with-glibc2.10 optional deps. installed: ['typing-extensions'] ``` The following minimal example repruduces the bug: ```py from pydantic import BaseModel, Field from typing import List, Optional, Union class Foo(BaseModel): a: str = Field( ..., ) b: Optional[float] class Bar(BaseModel): foo: Union[Foo, List[Foo]] bar = { "foo": [ { "a": "some string", "b": 1.0 }, { "a": "another string", "b": 2.0 } ] } a = Bar(**bar) print(a) ``` - Output: `foo=Foo(a='b', b=None)` - Expected Output: `foo=[Foo(a='some string', b=1.0), Foo(a='another string', b=2.0)]` I am not sure if this is related somehow to #2092
0.0
415eb54f966f0eec7cb2fd0aa61492c17e606367
[ "tests/test_types.py::test_smart_union_types", "tests/test_types.py::test_smart_union_class", "tests/test_types.py::test_smart_union_subclass", "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_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_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_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[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_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_default_union_class", "tests/test_types.py::test_default_union_subclass", "tests/test_types.py::test_default_union_compound_types", "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_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-11-04 18:29:22+00:00
mit
4,765
pydantic__pydantic-2094
diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -198,7 +198,11 @@ def validate_custom_root_type(fields: Dict[str, ModelField]) -> None: raise ValueError('__root__ cannot be mixed with other fields') -UNTOUCHED_TYPES = FunctionType, property, type, classmethod, staticmethod +# Annotated fields can have many types like `str`, `int`, `List[str]`, `Callable`... +# If a field is of type `Callable`, its default value should be a function and cannot to ignored. +ANNOTATED_FIELD_UNTOUCHED_TYPES: Tuple[Any, ...] = (property, type, classmethod, staticmethod) +# When creating a `BaseModel` instance, we bypass all the methods, properties... added to the model +UNTOUCHED_TYPES: Tuple[Any, ...] = (FunctionType,) + ANNOTATED_FIELD_UNTOUCHED_TYPES # Note `ModelMetaclass` refers to `BaseModel`, but is also used to *create* `BaseModel`, so we need to add this extra # (somewhat hacky) boolean to keep track of whether we've created the `BaseModel` class yet, and therefore whether it's @@ -245,7 +249,6 @@ def __new__(mcs, name, bases, namespace, **kwargs): # noqa C901 class_vars = set() if (namespace.get('__module__'), namespace.get('__qualname__')) != ('pydantic.main', 'BaseModel'): annotations = resolve_annotations(namespace.get('__annotations__', {}), namespace.get('__module__', None)) - untouched_types = UNTOUCHED_TYPES + config.keep_untouched # annotation only fields need to come first in fields for ann_name, ann_type in annotations.items(): if is_classvar(ann_type): @@ -255,14 +258,14 @@ def __new__(mcs, name, bases, namespace, **kwargs): # noqa C901 value = namespace.get(ann_name, Undefined) allowed_types = get_args(ann_type) if get_origin(ann_type) is Union else (ann_type,) if ( - isinstance(value, untouched_types) + isinstance(value, ANNOTATED_FIELD_UNTOUCHED_TYPES) and ann_type != PyObject and not any( lenient_issubclass(get_origin(allowed_type), Type) for allowed_type in allowed_types ) ): continue - fields[ann_name] = inferred = ModelField.infer( + fields[ann_name] = ModelField.infer( name=ann_name, value=value, annotation=ann_type, @@ -272,6 +275,7 @@ def __new__(mcs, name, bases, namespace, **kwargs): # noqa C901 elif ann_name not in namespace and config.underscore_attrs_are_private: private_attributes[ann_name] = PrivateAttr() + untouched_types = UNTOUCHED_TYPES + config.keep_untouched for var_name, value in namespace.items(): can_be_changed = var_name not in class_vars and not isinstance(value, untouched_types) if isinstance(value, ModelPrivateAttr): diff --git a/pydantic/schema.py b/pydantic/schema.py --- a/pydantic/schema.py +++ b/pydantic/schema.py @@ -188,7 +188,12 @@ def get_field_info_schema(field: ModelField) -> Tuple[Dict[str, Any], bool]: schema['description'] = field.field_info.description schema_overrides = True - if not field.required and not field.field_info.const and field.default is not None: + if ( + not field.required + and not field.field_info.const + and field.default is not None + and not is_callable_type(field.outer_type_) + ): schema['default'] = encode_default(field.default) schema_overrides = True
pydantic/pydantic
13a5c7d676167b415080de5e6e6a74bea095b239
diff --git a/tests/test_dataclasses.py b/tests/test_dataclasses.py --- a/tests/test_dataclasses.py +++ b/tests/test_dataclasses.py @@ -3,7 +3,7 @@ from collections.abc import Hashable from datetime import datetime from pathlib import Path -from typing import ClassVar, Dict, FrozenSet, List, Optional +from typing import Callable, ClassVar, Dict, FrozenSet, List, Optional import pytest @@ -801,6 +801,60 @@ class Config: e.item.name = 'pika2' +def test_pydantic_callable_field(): + """pydantic callable fields behaviour should be the same as stdlib dataclass""" + + def foo(arg1, arg2): + return arg1, arg2 + + def bar(x: int, y: float, z: str) -> bool: + return str(x + y) == z + + class PydanticModel(BaseModel): + required_callable: Callable + required_callable_2: Callable[[int, float, str], bool] + + default_callable: Callable = foo + default_callable_2: Callable[[int, float, str], bool] = bar + + @pydantic.dataclasses.dataclass + class PydanticDataclass: + required_callable: Callable + required_callable_2: Callable[[int, float, str], bool] + + default_callable: Callable = foo + default_callable_2: Callable[[int, float, str], bool] = bar + + @dataclasses.dataclass + class StdlibDataclass: + required_callable: Callable + required_callable_2: Callable[[int, float, str], bool] + + default_callable: Callable = foo + default_callable_2: Callable[[int, float, str], bool] = bar + + pyd_m = PydanticModel(required_callable=foo, required_callable_2=bar) + pyd_dc = PydanticDataclass(required_callable=foo, required_callable_2=bar) + std_dc = StdlibDataclass(required_callable=foo, required_callable_2=bar) + + assert ( + pyd_m.required_callable + is pyd_m.default_callable + is pyd_dc.required_callable + is pyd_dc.default_callable + is std_dc.required_callable + is std_dc.default_callable + ) + assert ( + pyd_m.required_callable_2 + is pyd_m.default_callable_2 + is pyd_dc.required_callable_2 + is pyd_dc.default_callable_2 + is std_dc.required_callable_2 + is std_dc.default_callable_2 + ) + + def test_pickle_overriden_builtin_dataclass(create_module): module = create_module( # language=Python diff --git a/tests/test_schema.py b/tests/test_schema.py --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -1006,10 +1006,18 @@ class Model(BaseModel): } [email protected]('annotation', [Callable, Callable[[int], int]]) -def test_callable_type(annotation): [email protected]( + 'type_,default_value', + ( + (Callable, ...), + (Callable, lambda x: x), + (Callable[[int], int], ...), + (Callable[[int], int], lambda x: x), + ), +) +def test_callable_type(type_, default_value): class Model(BaseModel): - callback: annotation + callback: type_ = default_value foo: int with pytest.warns(UserWarning):
TypeError during generation schema for model field (type Callable) with provided default value. ### 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.7.1 pydantic compiled: True install path: /home/***/.local/share/virtualenvs/lerdem-oY9IIzMI/lib/python3.6/site-packages/pydantic python version: 3.6.9 (default, Oct 8 2020, 12:12:24) [GCC 8.4.0] platform: Linux-5.0.0-32-generic-x86_64-with-LinuxMint-19.3-tricia optional deps. installed: [] ``` <!-- 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 >>> from typing import Callable >>> class Foo(BaseModel): ... # without default value, getting user warning ... callback: Callable[[], dict] ... >>> Foo.schema() __main__:1: UserWarning: Callable callback was excluded from schema since JSON schema has no equivalent type. {'title': 'Foo', 'type': 'object', 'properties': {}} >>> class FooDefault(BaseModel): ... callback: Callable[[], dict] = Field(default=lambda: {'some': 'data'}) >>> FooDefault.schema() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "pydantic/main.py", line 637, in pydantic.main.BaseModel.schema File "pydantic/schema.py", line 153, in pydantic.schema.model_schema File "pydantic/schema.py", line 523, in pydantic.schema.model_process_schema File "pydantic/schema.py", line 564, in pydantic.schema.model_type_schema File "pydantic/schema.py", line 215, in pydantic.schema.field_schema File "pydantic/schema.py", line 183, in pydantic.schema.get_field_info_schema File "pydantic/schema.py", line 846, in pydantic.schema.encode_default File "pydantic/json.py", line 65, in pydantic.json.pydantic_encoder TypeError: Object of type 'function' is not JSON serializable ``` One possible solution according for docs is to use custom [`Confing.json_encoders`](https://pydantic-docs.helpmanual.io/usage/exporting_models/#json_encoders). So i have tried: ```py >>> def hack(): ... pass >>> class FooDefault(BaseModel): ... callback: Callable[[], dict] = Field(default=lambda: {'some': 'data'}) ... class Config: ... json_encoders = { ... # i don't know how to make it right way ... type(hack): str, ... Callable: str ... } >>> FooDefault.schema() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "pydantic/main.py", line 637, in pydantic.main.BaseModel.schema File "pydantic/schema.py", line 153, in pydantic.schema.model_schema File "pydantic/schema.py", line 523, in pydantic.schema.model_process_schema File "pydantic/schema.py", line 564, in pydantic.schema.model_type_schema File "pydantic/schema.py", line 215, in pydantic.schema.field_schema File "pydantic/schema.py", line 183, in pydantic.schema.get_field_info_schema File "pydantic/schema.py", line 846, in pydantic.schema.encode_default File "pydantic/json.py", line 65, in pydantic.json.pydantic_encoder TypeError: Object of type 'function' is not JSON serializable ``` I think, that preferable behaviour is to show warnings in situation like that. And that should work without any custom `json_encoders`.
0.0
13a5c7d676167b415080de5e6e6a74bea095b239
[ "tests/test_dataclasses.py::test_pydantic_callable_field", "tests/test_schema.py::test_callable_type[type_1-<lambda>]", "tests/test_schema.py::test_callable_type[type_3-<lambda>]" ]
[ "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_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_pickle_overriden_builtin_dataclass", "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_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_2-default_value2]", "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-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[kwargs8-type_8]", "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_unenforced_constraints_schema[kwargs11-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_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_enums_with_same_name" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-11-05 23:01:00+00:00
mit
4,766
pydantic__pydantic-2114
diff --git a/pydantic/dataclasses.py b/pydantic/dataclasses.py --- a/pydantic/dataclasses.py +++ b/pydantic/dataclasses.py @@ -119,10 +119,23 @@ def _pydantic_post_init(self: 'Dataclass', *initvars: Any) -> None: # __post_init__ = _pydantic_post_init # ``` # with the exact same fields as the base dataclass + # and register it on module level to address pickle problem: + # https://github.com/samuelcolvin/pydantic/issues/2111 if is_builtin_dataclass(_cls): + uniq_class_name = f'_Pydantic_{_cls.__name__}_{id(_cls)}' _cls = type( - _cls.__name__, (_cls,), {'__annotations__': _cls.__annotations__, '__post_init__': _pydantic_post_init} + # for pretty output new class will have the name as original + _cls.__name__, + (_cls,), + { + '__annotations__': _cls.__annotations__, + '__post_init__': _pydantic_post_init, + # attrs for pickle to find this class + '__module__': __name__, + '__qualname__': uniq_class_name, + }, ) + globals()[uniq_class_name] = _cls else: _cls.__post_init__ = _pydantic_post_init cls: Type['Dataclass'] = dataclasses.dataclass( # type: ignore
pydantic/pydantic
31bc2435d7968fdf8d1f0c5c67f0f851c1bef54e
diff --git a/tests/test_dataclasses.py b/tests/test_dataclasses.py --- a/tests/test_dataclasses.py +++ b/tests/test_dataclasses.py @@ -1,4 +1,5 @@ import dataclasses +import pickle from collections.abc import Hashable from datetime import datetime from pathlib import Path @@ -733,7 +734,10 @@ class File: 'type': 'object', } }, - 'properties': {'filename': {'title': 'Filename', 'type': 'string'}, 'meta': {'$ref': '#/definitions/Meta'}}, + 'properties': { + 'filename': {'title': 'Filename', 'type': 'string'}, + 'meta': {'$ref': '#/definitions/Meta'}, + }, 'required': ['filename', 'meta'], 'title': 'File', 'type': 'object', @@ -795,3 +799,37 @@ class Config: e.other = 'bulbi2' with pytest.raises(dataclasses.FrozenInstanceError): e.item.name = 'pika2' + + +def test_pickle_overriden_builtin_dataclass(create_module): + module = create_module( + # language=Python + """\ +import dataclasses +import pydantic + + [email protected] +class BuiltInDataclassForPickle: + value: int + +class ModelForPickle(pydantic.BaseModel): + # pickle can only work with top level classes as it imports them + + dataclass: BuiltInDataclassForPickle + + class Config: + validate_assignment = True + """ + ) + obj = module.ModelForPickle(dataclass=module.BuiltInDataclassForPickle(value=5)) + + pickled_obj = pickle.dumps(obj) + restored_obj = pickle.loads(pickled_obj) + + assert restored_obj.dataclass.value == 5 + assert restored_obj == obj + + # ensure the restored dataclass is still a pydantic dataclass + with pytest.raises(ValidationError, match='value\n +value is not a valid integer'): + restored_obj.dataclass.value = 'value of a wrong type'
support for built-in `dataclass` breaks pickle ### 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.7.2 pydantic compiled: True install path: /Users/aimestereo/.pyenv/versions/3.7.6/envs/feed/lib/python3.7/site-packages/pydantic python version: 3.7.6 (default, Jan 30 2020, 16:07:03) [Clang 11.0.0 (clang-1100.0.33.17)] platform: Darwin-19.6.0-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: --> thanks to @PrettyWood 1.7 Introduced cool [support of built-in dataclass](https://github.com/samuelcolvin/pydantic/pull/1817). But in our project this broke pickle ```py import pickle import dataclasses import pydantic @dataclasses.dataclass class BuiltInDataclass: value: int class PydanticModel(pydantic.BaseModel): built_in_dataclass: BuiltInDataclass print(pickle.dumps( PydanticModel(built_in_dataclass=BuiltInDataclass(value=0)) )) ``` output: ``` --------------------------------------------------------------------------- PicklingError Traceback (most recent call last) <ipython-input-14-7d67a44cf353> in <module> 15 16 print(pickle.dumps( ---> 17 PydanticModel(built_in_dataclass=BuiltInDataclass(value=0)) 18 )) PicklingError: Can't pickle <class '__main__.BuiltInDataclass'>: it's not the same object as __main__.BuiltInDataclass ``` --- For better understanding here's an issue of pickle outside of pydantic context. This is an old pickle problem, when different classes have the same name, simple way to reproduce: ``` import pickle class A: pass # this is an analogy of how pydantic convert built-in dataclass B = type(A.__name__, (A,), {}) print(A) # <class '__main__.A'> print(B) # <class '__main__.A'> pickle.dumps(A) # b'\x80\x03c__main__\nA\nq\x00.' pickle.dumps(B) # error ``` output ``` --------------------------------------------------------------------------- PicklingError Traceback (most recent call last) <ipython-input-2-b97d2c67736c> in <module> 10 11 print(pickle.dumps(A)) ---> 12 print(pickle.dumps(B)) PicklingError: Can't pickle <class '__main__.A'>: it's not the same object as __main__.A ``` --- As a result we can't use this feature, we're stick to intermediate classes that converts buit-in dataclasses to pydantic: ``` class SerializedDataclass(pydantic.BaseModel): # copy/paste of all fields from built-in dataclass value: float ```
0.0
31bc2435d7968fdf8d1f0c5c67f0f851c1bef54e
[ "tests/test_dataclasses.py::test_pickle_overriden_builtin_dataclass" ]
[ "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_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" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2020-11-11 11:41:03+00:00
mit
4,767
pydantic__pydantic-2119
diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -406,7 +406,12 @@ def __setattr__(self, name, value): # noqa: C901 (ignore complexity) if errors: raise ValidationError(errors, self.__class__) - self.__dict__[name] = value + # update the whole __dict__ as other values than just `value` + # may be changed (e.g. with `root_validator`) + object_setattr(self, '__dict__', new_values) + else: + self.__dict__[name] = value + self.__fields_set__.add(name) def __getstate__(self) -> 'DictAny':
pydantic/pydantic
31bc2435d7968fdf8d1f0c5c67f0f851c1bef54e
Hi @art049 Yes you're right. Since #1971 has been solved, this is the expected behaviour but it seems we update only the current field and not all. I can make a quick fix if you want should take couple of minutes
diff --git a/tests/test_main.py b/tests/test_main.py --- a/tests/test_main.py +++ b/tests/test_main.py @@ -666,6 +666,28 @@ def current_lessequal_500(cls, values): ] +def test_root_validator_many_values_change(): + """It should run root_validator on assignment and update ALL concerned fields""" + + class Rectangle(BaseModel): + width: float + height: float + area: float = None + + class Config: + validate_assignment = True + + @root_validator + def set_area(cls, values): + values['area'] = values['width'] * values['height'] + return values + + r = Rectangle(width=1, height=1) + assert r.area == 1 + r.height = 5 + assert r.area == 5 + + def test_enum_values(): FooEnum = Enum('FooEnum', {'foo': 'foo', 'bar': 'bar'})
validate_assignment with side effect validators # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.7.2 pydantic compiled: True install path: /home/arthur/Documents/odmantic/.venv/lib/python3.8/site-packages/pydantic python version: 3.8.1 (default, Jan 5 2020, 23:12:00) [GCC 7.3.0] platform: Linux-4.17.14-041714-generic-x86_64-with-glibc2.27 optional deps. installed: ['typing-extensions'] ``` ```py from pydantic import root_validator, BaseModel class Rectangle(BaseModel): width: float height: float area: float = None class Config: validate_assignment = True @root_validator() def set_ts_now(cls, v): v["area"] = v["width"] * v["height"] return v r = Rectangle(width=1, height=1) assert r.area == 1 r.height = 5 assert r.area == 5 # AssertionError, r.area has not been modified ``` I don't know if it should be allowed to use validators this way or if it's a real bug. I'd be happy to try to implement a fix :smile:
0.0
31bc2435d7968fdf8d1f0c5c67f0f851c1bef54e
[ "tests/test_main.py::test_root_validator_many_values_change" ]
[ "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_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_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_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_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_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_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_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", "tests/test_main.py::test_model_export_dict_exclusion", "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" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2020-11-13 00:27:16+00:00
mit
4,768
pydantic__pydantic-2133
diff --git a/pydantic/fields.py b/pydantic/fields.py --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -346,7 +346,6 @@ def prepare(self) -> None: Note: this method is **not** idempotent (because _type_analysis is not idempotent), e.g. calling it it multiple times may modify the field and configure it incorrectly. """ - self._set_default_and_type() if self.type_.__class__ == ForwardRef: # self.type_ is currently a ForwardRef and there's nothing we can do now, @@ -448,14 +447,19 @@ def _type_analysis(self) -> None: # noqa: C901 (ignore complexity) return if issubclass(origin, Tuple): # type: ignore - self.shape = SHAPE_TUPLE - self.sub_fields = [] - for i, t in enumerate(get_args(self.type_)): - if t is Ellipsis: - self.type_ = get_args(self.type_)[0] - self.shape = SHAPE_TUPLE_ELLIPSIS - return - self.sub_fields.append(self._create_sub_type(t, f'{self.name}_{i}')) + # origin == Tuple without item type + if not get_args(self.type_): + self.type_ = Any + self.shape = SHAPE_TUPLE_ELLIPSIS + else: + self.shape = SHAPE_TUPLE + self.sub_fields = [] + for i, t in enumerate(get_args(self.type_)): + if t is Ellipsis: + self.type_ = get_args(self.type_)[0] + self.shape = SHAPE_TUPLE_ELLIPSIS + return + self.sub_fields.append(self._create_sub_type(t, f'{self.name}_{i}')) return if issubclass(origin, List): @@ -605,6 +609,8 @@ def _validate_sequence_like( # noqa: C901 (ignore complexity) e: errors_.PydanticTypeError if self.shape == SHAPE_LIST: e = errors_.ListError() + elif self.shape in (SHAPE_TUPLE, SHAPE_TUPLE_ELLIPSIS): + e = errors_.TupleError() elif self.shape == SHAPE_SET: e = errors_.SetError() elif self.shape == SHAPE_FROZENSET:
pydantic/pydantic
31bc2435d7968fdf8d1f0c5c67f0f851c1bef54e
diff --git a/tests/test_types.py b/tests/test_types.py --- a/tests/test_types.py +++ b/tests/test_types.py @@ -2309,21 +2309,24 @@ def test_generic_without_params(): class Model(BaseModel): generic_list: List generic_dict: Dict + generic_tuple: Tuple - m = Model(generic_list=[0, 'a'], generic_dict={0: 'a', 'a': 0}) - assert m.dict() == {'generic_list': [0, 'a'], 'generic_dict': {0: 'a', 'a': 0}} + m = Model(generic_list=[0, 'a'], generic_dict={0: 'a', 'a': 0}, generic_tuple=(1, 'q')) + assert m.dict() == {'generic_list': [0, 'a'], 'generic_dict': {0: 'a', 'a': 0}, 'generic_tuple': (1, 'q')} def test_generic_without_params_error(): class Model(BaseModel): generic_list: List generic_dict: Dict + generic_tuple: Tuple with pytest.raises(ValidationError) as exc_info: - Model(generic_list=0, generic_dict=0) + Model(generic_list=0, generic_dict=0, generic_tuple=0) assert exc_info.value.errors() == [ {'loc': ('generic_list',), 'msg': 'value is not a valid list', 'type': 'type_error.list'}, {'loc': ('generic_dict',), 'msg': 'value is not a valid dict', 'type': 'type_error.dict'}, + {'loc': ('generic_tuple',), 'msg': 'value is not a valid tuple', 'type': 'type_error.tuple'}, ]
Tuple field triggers error checking inheritance ### 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.7.2 pydantic compiled: True install path: /home/alexv/.local/share/virtualenvs/datacrystals-F4r2dbjD/lib/python3.8/site-packages/pydantic python version: 3.8.2 (default, Apr 27 2020, 15:53:34) [GCC 9.3.0] platform: Linux-5.4.0-7634-generic-x86_64-with-glibc2.29 optional deps. installed: ['typing-extensions'] ``` I didn't yet investigate what is happening here, but this looks like something that should be working... ```py from pydantic.dataclasses import dataclass import typing @dataclass class wrappingTuple: field: typing.Tuple print(wrappingTuple(field=(0,1)) ``` triggers : ``` Traceback (most recent call last): File "pydantic/validators.py", line 615, in pydantic.validators.find_validators TypeError: issubclass() arg 1 must be a class During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<input>", line 2, in <module> File "pydantic/dataclasses.py", line 216, in pydantic.dataclasses.dataclass File "pydantic/dataclasses.py", line 211, in pydantic.dataclasses.dataclass.wrap File "pydantic/dataclasses.py", line 147, in pydantic.dataclasses._process_class File "pydantic/main.py", line 925, in pydantic.main.create_model File "pydantic/main.py", line 262, in pydantic.main.ModelMetaclass.__new__ File "pydantic/fields.py", line 315, in pydantic.fields.ModelField.infer File "pydantic/fields.py", line 284, in pydantic.fields.ModelField.__init__ File "pydantic/fields.py", line 362, in pydantic.fields.ModelField.prepare File "pydantic/fields.py", line 538, in pydantic.fields.ModelField.populate_validators File "pydantic/validators.py", line 624, in find_validators RuntimeError: error checking inheritance of typing.Tuple (type: Tuple) ``` However this works fine : ```py from pydantic.dataclasses import dataclass import typing @dataclass class wrappingTuple: field: tuple print(wrappingTuple(field=(0,1)) ``` ``` wrappingTuple(field=(0, 1)) ``` and this as well : ```py from pydantic.dataclasses import dataclass import typing @dataclass class wrappingTuple: field: typing.List print(wrappingTuple(field=[0,1]) ``` ``` wrappingTuple(field=[0, 1]) ```
0.0
31bc2435d7968fdf8d1f0c5c67f0f851c1bef54e
[ "tests/test_types.py::test_generic_without_params", "tests/test_types.py::test_generic_without_params_error" ]
[ "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_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_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_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_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_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_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_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_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" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2020-11-18 21:10:52+00:00
mit
4,769
pydantic__pydantic-2143
diff --git a/pydantic/fields.py b/pydantic/fields.py --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -307,7 +307,7 @@ def infer( required: 'BoolUndefined' = Undefined if value is Required: required = True - value = None + value = Ellipsis elif value is not Undefined: required = False field_info.alias = field_info.alias or field_info_from_config.get('alias')
pydantic/pydantic
31bc2435d7968fdf8d1f0c5c67f0f851c1bef54e
https://github.com/samuelcolvin/pydantic/blob/31bc2435d7968fdf8d1f0c5c67f0f851c1bef54e/pydantic/main.py#L789 Alright, I haven't looked really closely, but here's my guess: `getattr` here can never fallback to `_missing`, since `ModelField.default` is always there and has a value of `None` unless set explicitly: https://github.com/samuelcolvin/pydantic/blob/31bc2435d7968fdf8d1f0c5c67f0f851c1bef54e/pydantic/fields.py#L255 UPD1: And here's where "bar" is created and gets the default value of `None`: https://github.com/samuelcolvin/pydantic/blob/31bc2435d7968fdf8d1f0c5c67f0f851c1bef54e/pydantic/fields.py#L308-L310 UPD2: Is it a good idea to check `field.field_info.default` instead of `field.default`? In this particular case it has a correct value of `Ellipsis`, and you could special-case it while serialising the model. Hello @leovp and thanks for reporting :) You're absolutely right! IMO the good fix would be to set `default = Ellipsis` when `required` Would you like to make a PR for this? If you want I can do it as well tonight for a `v1.7.3`. Please tell me. Cheers @PrettyWood It's 11PM where I live, so please go ahead :)
diff --git a/tests/test_dataclasses.py b/tests/test_dataclasses.py --- a/tests/test_dataclasses.py +++ b/tests/test_dataclasses.py @@ -406,7 +406,7 @@ class User: fields = user.__pydantic_model__.__fields__ assert fields['id'].required is True - assert fields['id'].default is None + assert fields['id'].default is Ellipsis assert fields['name'].required is False assert fields['name'].default == 'John Doe' @@ -425,7 +425,7 @@ class User: fields = user.__pydantic_model__.__fields__ assert fields['id'].required is True - assert fields['id'].default is None + assert fields['id'].default is Ellipsis assert fields['aliases'].required is False assert fields['aliases'].default == {'John': 'Joey'} diff --git a/tests/test_main.py b/tests/test_main.py --- a/tests/test_main.py +++ b/tests/test_main.py @@ -958,6 +958,35 @@ class Config: assert m.dict(exclude_unset=True, by_alias=True) == {'alias_a': 'a', 'c': 'c'} +def test_exclude_defaults(): + class Model(BaseModel): + mandatory: str + nullable_mandatory: Optional[str] = ... + facultative: str = 'x' + nullable_facultative: Optional[str] = None + + m = Model(mandatory='a', nullable_mandatory=None) + assert m.dict(exclude_defaults=True) == { + 'mandatory': 'a', + 'nullable_mandatory': None, + } + + m = Model(mandatory='a', nullable_mandatory=None, facultative='y', nullable_facultative=None) + assert m.dict(exclude_defaults=True) == { + 'mandatory': 'a', + 'nullable_mandatory': None, + 'facultative': 'y', + } + + m = Model(mandatory='a', nullable_mandatory=None, facultative='y', nullable_facultative='z') + assert m.dict(exclude_defaults=True) == { + 'mandatory': 'a', + 'nullable_mandatory': None, + 'facultative': 'y', + 'nullable_facultative': 'z', + } + + def test_dir_fields(): class MyModel(BaseModel): attribute_a: int
Required optional field has a default value of None after v1.7.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.7.2 pydantic compiled: False install path: /home/leovp/Projects/pydantic/pydantic python version: 3.6.12 (default, Sep 5 2020, 11:22:16) [GCC 7.5.0] platform: Linux-4.15.0-54-generic-x86_64-with-debian-buster-sid optional deps. installed: [] ``` <!-- 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 class Model(BaseModel): foo: int bar: Optional[int] = ... m = Model(foo=1, bar=None) # or Model(foo=1) Model.parse_obj(m.dict(exclude_defaults=True)) # fails on pydantic v1.7.0+ ``` It seems that `pydantic` thinks `bar` (a "required optional" field) has a default value of None and serializes the model without this key, which makes it non-deserializable. This was not the case on versions 1.5.x and 1.6.x, so I think it's a regression. (Or maybe it was never a guarantee). According to `git bisect` the potential regression was introduced in commit 4bc4230df6294c62667fc3779328019a28912147.
0.0
31bc2435d7968fdf8d1f0c5c67f0f851c1bef54e
[ "tests/test_dataclasses.py::test_fields", "tests/test_dataclasses.py::test_default_factory_field", "tests/test_main.py::test_exclude_defaults" ]
[ "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_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_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_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_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_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_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_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_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_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_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", "tests/test_main.py::test_model_export_dict_exclusion", "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" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_git_commit_hash" ], "has_test_patch": true, "is_lite": false }
2020-11-23 21:52:10+00:00
mit
4,770
pydantic__pydantic-2149
diff --git a/docs/build/schema_mapping.py b/docs/build/schema_mapping.py --- a/docs/build/schema_mapping.py +++ b/docs/build/schema_mapping.py @@ -11,6 +11,13 @@ from pathlib import Path table = [ + [ + 'None', + 'null', + '', + 'JSON Schema Core', + 'Same for `type(None)` or `Literal[None]`' + ], [ 'bool', 'boolean', diff --git a/pydantic/errors.py b/pydantic/errors.py --- a/pydantic/errors.py +++ b/pydantic/errors.py @@ -17,6 +17,7 @@ 'NoneIsNotAllowedError', 'NoneIsAllowedError', 'WrongConstantError', + 'NotNoneError', 'BoolError', 'BytesError', 'DictError', @@ -160,6 +161,11 @@ def __str__(self) -> str: return f'unexpected value; permitted: {permitted}' +class NotNoneError(PydanticTypeError): + code = 'not_none' + msg_template = 'value is not None' + + class BoolError(PydanticTypeError): msg_template = 'value could not be parsed to a boolean' diff --git a/pydantic/fields.py b/pydantic/fields.py --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -28,6 +28,7 @@ from .errors import NoneIsNotAllowedError from .types import Json, JsonWrapper from .typing import ( + NONE_TYPES, Callable, ForwardRef, NoArgAnyCallable, @@ -368,7 +369,7 @@ def _set_default_and_type(self) -> None: when we want to validate the default value i.e. when `validate_all` is set to True. """ if self.default_factory is not None: - if self.type_ is None: + if self.type_ is Undefined: raise errors_.ConfigError( f'you need to set the type of field {self.name!r} when using `default_factory`' ) @@ -377,11 +378,11 @@ def _set_default_and_type(self) -> None: default_value = self.get_default() - if default_value is not None and self.type_ is None: + if default_value is not None and self.type_ is Undefined: self.type_ = default_value.__class__ self.outer_type_ = self.type_ - if self.type_ is None: + if self.type_ is Undefined: raise errors_.ConfigError(f'unable to infer type for attribute "{self.name}"') if self.required is False and default_value is None: @@ -571,7 +572,10 @@ def validate( return v, errors if v is None: - if self.allow_none: + if self.type_ in NONE_TYPES: + # keep validating + pass + elif self.allow_none: if self.post_validators: return self._apply_validators(v, values, loc, cls, self.post_validators) else: @@ -753,12 +757,6 @@ def _apply_validators( return v, ErrorWrapper(exc, loc) return v, None - def include_in_schema(self) -> bool: - """ - False if this is a simple field just allowing None as used in Unions/Optional. - """ - return self.type_ != NoneType - def is_complex(self) -> bool: """ Whether the field is "complex" eg. env variables should be parsed as JSON. diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -285,7 +285,7 @@ def __new__(mcs, name, bases, namespace, **kwargs): # noqa C901 inferred = ModelField.infer( name=var_name, value=value, - annotation=annotations.get(var_name), + annotation=annotations.get(var_name, Undefined), class_validators=vg.get_validators(var_name), config=config, ) diff --git a/pydantic/schema.py b/pydantic/schema.py --- a/pydantic/schema.py +++ b/pydantic/schema.py @@ -57,7 +57,16 @@ conset, constr, ) -from .typing import ForwardRef, Literal, get_args, get_origin, is_callable_type, is_literal_type, literal_values +from .typing import ( + NONE_TYPES, + ForwardRef, + Literal, + get_args, + get_origin, + is_callable_type, + is_literal_type, + literal_values, +) from .utils import ROOT_KEY, get_model, lenient_issubclass, sequence_like if TYPE_CHECKING: @@ -640,7 +649,6 @@ def field_singleton_sub_fields_schema( """ definitions = {} nested_models: Set[str] = set() - sub_fields = [sf for sf in sub_fields if sf.include_in_schema()] if len(sub_fields) == 1: return field_type_schema( sub_fields[0], @@ -759,6 +767,8 @@ def field_singleton_schema( # noqa: C901 (ignore complexity) ) if field.type_ is Any or field.type_.__class__ == TypeVar: return {}, definitions, nested_models # no restrictions + if field.type_ in NONE_TYPES: + return {'type': 'null'}, definitions, nested_models 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] = {} diff --git a/pydantic/typing.py b/pydantic/typing.py --- a/pydantic/typing.py +++ b/pydantic/typing.py @@ -149,6 +149,7 @@ def get_args(tp: Type[Any]) -> Tuple[Any, ...]: 'AnyCallable', 'NoArgAnyCallable', 'NoneType', + 'NONE_TYPES', 'display_as_type', 'resolve_annotations', 'is_callable_type', @@ -176,6 +177,9 @@ def get_args(tp: Type[Any]) -> Tuple[Any, ...]: NoneType = None.__class__ +NONE_TYPES: Set[Any] = {None, NoneType} +if Literal: + NONE_TYPES.add(Literal[None]) def display_as_type(v: Type[Any]) -> str: diff --git a/pydantic/validators.py b/pydantic/validators.py --- a/pydantic/validators.py +++ b/pydantic/validators.py @@ -27,8 +27,10 @@ from . import errors from .datetime_parse import parse_date, parse_datetime, parse_duration, parse_time from .typing import ( + NONE_TYPES, AnyCallable, ForwardRef, + Literal, all_literal_values, display_as_type, get_class, @@ -511,6 +513,12 @@ def any_class_validator(v: Any) -> Type[T]: raise errors.ClassError() +def none_validator(v: Any) -> 'Literal[None]': + if v is None: + return v + raise errors.NotNoneError() + + def pattern_validator(v: Any) -> Pattern[str]: if isinstance(v, Pattern): return v @@ -589,6 +597,9 @@ def find_validators( # noqa: C901 (ignore complexity) type_type = type_.__class__ if type_type == ForwardRef or type_type == TypeVar: return + if type_ in NONE_TYPES: + yield none_validator + return if type_ is Pattern: yield pattern_validator return
pydantic/pydantic
de0657e4a5495de9378db9fe15a17334c2b0fae5
I think we could have a `NoneType` which enforces a value to be `None`. But I think if we made `foo: None` a valid way of enforcing a value is None it would make a lot of logic more complicated and result in lots of easy traps for people to fall into. I agree that we should not allow `foo: None` as a type constraint, but we could allow `foo: type(None)` or `foo: pydantic.typing.NoneType`. This would be effectively equivalent to `Literal[None]`. Mypy, along with other type checkers, already treat `foo: None` as equivalent to `foo: Literal[None]` or `foo: NoneType`. My proposal is that Pydantic match this behaviour, even though it would require some extra logic for the sake of consistency with the rest of the ecosystem. `foo: type(None)` makes Mypy fail with `error: Invalid type comment or annotation. Suggestion: use type[...] instead of type(...)`, so while Pydantic should probably allow it at runtime we'd have to recommend assigning `type(None)` to a variable and using that in annotations. According to https://www.python.org/dev/peps/pep-0484/#using-none, `None` should be considered equivalent to `type(None)`, so this is definitely a bug.
diff --git a/tests/test_types.py b/tests/test_types.py --- a/tests/test_types.py +++ b/tests/test_types.py @@ -69,17 +69,13 @@ errors, validator, ) +from pydantic.typing import Literal, NoneType try: import email_validator except ImportError: email_validator = None -try: - import typing_extensions -except ImportError: - typing_extensions = None - class ConBytesModel(BaseModel): v: conbytes(max_length=10) = b'foobar' @@ -2396,10 +2392,10 @@ class Model(BaseModel): ] [email protected](not typing_extensions, reason='typing_extensions not installed') [email protected](not Literal, reason='typing_extensions not installed') def test_literal_single(): class Model(BaseModel): - a: typing_extensions.Literal['a'] + a: Literal['a'] Model(a='a') with pytest.raises(ValidationError) as exc_info: @@ -2414,10 +2410,10 @@ class Model(BaseModel): ] [email protected](not typing_extensions, reason='typing_extensions not installed') [email protected](not Literal, reason='typing_extensions not installed') def test_literal_multiple(): class Model(BaseModel): - a_or_b: typing_extensions.Literal['a', 'b'] + a_or_b: Literal['a', 'b'] Model(a_or_b='a') Model(a_or_b='b') @@ -2609,3 +2605,59 @@ class Model(BaseModel): v: Deque[int] assert Model(v=deque((1, 2, 3))).json() == '{"v": [1, 2, 3]}' + + +none_value_type_cases = (None, type(None), NoneType) +if Literal: + none_value_type_cases += (Literal[None],) + + [email protected]('value_type', none_value_type_cases) +def test_none(value_type): + class Model(BaseModel): + my_none: value_type + my_none_list: List[value_type] + my_none_dict: Dict[str, value_type] + my_json_none: Json[value_type] + + Model( + my_none=None, + my_none_list=[None] * 3, + my_none_dict={'a': None, 'b': None}, + my_json_none='null', + ) + + assert Model.schema() == { + 'title': 'Model', + 'type': 'object', + 'properties': { + 'my_none': {'title': 'My None', 'type': 'null'}, + 'my_none_list': { + 'title': 'My None List', + 'type': 'array', + 'items': {'type': 'null'}, + }, + 'my_none_dict': { + 'title': 'My None Dict', + 'type': 'object', + 'additionalProperties': {'type': 'null'}, + }, + 'my_json_none': {'title': 'My Json None', 'type': 'null'}, + }, + 'required': ['my_none', 'my_none_list', 'my_none_dict', 'my_json_none'], + } + + with pytest.raises(ValidationError) as exc_info: + Model( + my_none='qwe', + my_none_list=[1, None, 'qwe'], + my_none_dict={'a': 1, 'b': None}, + my_json_none='"a"', + ) + assert exc_info.value.errors() == [ + {'loc': ('my_none',), 'msg': 'value is not None', 'type': 'type_error.not_none'}, + {'loc': ('my_none_list', 0), 'msg': 'value is not None', 'type': 'type_error.not_none'}, + {'loc': ('my_none_list', 2), 'msg': 'value is not None', 'type': 'type_error.not_none'}, + {'loc': ('my_none_dict', 'a'), 'msg': 'value is not None', 'type': 'type_error.not_none'}, + {'loc': ('my_json_none',), 'msg': 'value is not None', 'type': 'type_error.not_none'}, + ]
Pydantic does not seem to have a validator for `NoneType` I encountered this while working on #2017: ```py from typing import List from pydantic import BaseModel, Json class JsonDemo(BaseModel): # I'd expect this to work like typing.List[None], but at definition-time it raises # RuntimeError: error checking inheritance of None (type: NoneType) none: Json[None] JsonDemo(none="null") class JsonWorkaround(BaseModel): # The workaround of using type(None) also fails at definition-time, raising # RuntimeError: no validator found for <class 'NoneType'>, see `arbitrary_types_allowed` in Config # The same error is apparent for List[None], so I think it's a more general bug json_null: Json[type(None)] list_of_none: List[None] ``` I would expect both `Json[None]` and `List[None]` to work, accepting in respectively `"null"` or a list (or sequence) where all the elements are `None` - casting need not be supported because `None` is a singleton.
0.0
de0657e4a5495de9378db9fe15a17334c2b0fae5
[ "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_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_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_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_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_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_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_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" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-11-28 21:51:35+00:00
mit
4,771
pydantic__pydantic-2167
diff --git a/pydantic/fields.py b/pydantic/fields.py --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -307,7 +307,7 @@ def infer( required: 'BoolUndefined' = Undefined if value is Required: required = True - value = Ellipsis + value = None elif value is not Undefined: required = False field_info.alias = field_info.alias or field_info_from_config.get('alias') diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -788,12 +788,12 @@ def _iter( value_include = ValueItems(self, include) if include else None for field_key, v in self.__dict__.items(): - if ( - (allowed_keys is not None and field_key not in allowed_keys) - or (exclude_none and v is None) - or (exclude_defaults and getattr(self.__fields__.get(field_key), 'default', _missing) == v) - ): + if (allowed_keys is not None and field_key not in allowed_keys) or (exclude_none and v is None): continue + if exclude_defaults: + model_field = self.__fields__.get(field_key) + if not getattr(model_field, 'required', True) and getattr(model_field, 'default', _missing) == v: + continue if by_alias and field_key in self.__fields__: dict_key = self.__fields__[field_key].alias else:
pydantic/pydantic
de0657e4a5495de9378db9fe15a17334c2b0fae5
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 @@ -182,3 +182,15 @@ class Model(BaseModel): assert model.__fields__.keys() == {'a', 'b'} assert model2.__fields__.keys() == {'a', 'c'} assert model3.__fields__.keys() == {'a', 'b', 'd'} + + +def test_dynamic_and_static(): + class A(BaseModel): + x: int + y: float + z: str + + DynamicA = create_model('A', x=(int, ...), y=(float, ...), z=(str, ...)) + + for field_name in ('x', 'y', 'z'): + assert A.__fields__[field_name].default == DynamicA.__fields__[field_name].default diff --git a/tests/test_dataclasses.py b/tests/test_dataclasses.py --- a/tests/test_dataclasses.py +++ b/tests/test_dataclasses.py @@ -407,7 +407,7 @@ class User: fields = user.__pydantic_model__.__fields__ assert fields['id'].required is True - assert fields['id'].default is Ellipsis + assert fields['id'].default is None assert fields['name'].required is False assert fields['name'].default == 'John Doe' @@ -426,7 +426,7 @@ class User: fields = user.__pydantic_model__.__fields__ assert fields['id'].required is True - assert fields['id'].default is Ellipsis + assert fields['id'].default is None assert fields['aliases'].required is False assert fields['aliases'].default == {'John': 'Joey'}
Required field default value inconsistent (None vs. Ellipsis) between statically and dynamically created models with v1.7.3 ### 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.7.3 pydantic compiled: True install path: /usr/local/lib/python3.8/site-packages/pydantic python version: 3.8.6 (default, Nov 25 2020, 02:47:44) [GCC 8.3.0] platform: Linux-5.6.0-1033-oem-x86_64-with-glibc2.2.5 optional deps. installed: [] ``` <!-- 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 Type, Dict import pydantic.utils from pydantic import BaseModel, create_model from pydantic.fields import ModelField, UndefinedType class A(BaseModel): x: int y: float z: str def dynamic_model(): return create_model("A", x=(int, ...), y=(float, ...), z=(str, ...)) DYNAMIC_MODEL = dynamic_model() def get_field_name_to_pydantic_field(model_type: Type[BaseModel]) -> Dict[str, ModelField]: return {field.name: field for field in model_type.__fields__.values()} def assert_model_fields(mf1, mf2): assert mf1.type_ is mf2.type_ assert mf1.name == mf2.name assert mf1.default == mf2.default assert mf1.required == mf2.required if isinstance(mf1.field_info.default, UndefinedType): assert isinstance(mf2.field_info.default, UndefinedType) else: assert mf1.field_info.default == mf2.field_info.default assert mf1.field_info.const == mf2.field_info.const assert mf1.field_info.extra == mf2.field_info.extra def test_statically_and_dynamically_created_equivalent_models(): print(f"\n{pydantic.utils.version_info()}") print("\nCreated statically:") for n, mf in get_field_name_to_pydantic_field(A).items(): print(n, mf, mf.default) print("\nCreated dynamically:") for n, mf in get_field_name_to_pydantic_field(DYNAMIC_MODEL).items(): print(n, mf, mf.default) for field_name in A.__fields__: assert_model_fields(A.__fields__[field_name], DYNAMIC_MODEL.__fields__[field_name]) ``` This bug _might_ be related to https://github.com/samuelcolvin/pydantic/issues/2142 and https://github.com/samuelcolvin/pydantic/commit/9ae40a209f929e421736a69d093d01749861c772 . It seems `pydantic` sets the default value of a required field of a statically created model as `None`. This was the case until `v1.7.2` for the required fields of dynamically created models. However with the `v1.7.3` there seems to be an inconsistent behaviour where the default value for the required fields of dynamically created models are set to be `Ellipsis`. I'm not aware whether this was intentional, or consistent behaviour between statically and dynamically created models is sought after but I wanted to point that out in case it is a regression. Here's a dockerized version of the tests: https://github.com/emreay-/pydantic-default-value-inconsistency-test The output for `pydantic==1.7.2` (warnings are pytest cache warnings): ``` =============================================================================================== test session starts =============================================================================================== platform linux -- Python 3.8.6, pytest-6.1.2, py-1.9.0, pluggy-0.13.1 rootdir: / collected 1 item pydantic_default_issue.py pydantic version: 1.7.2 pydantic compiled: True install path: /usr/local/lib/python3.8/site-packages/pydantic python version: 3.8.6 (default, Nov 25 2020, 02:47:44) [GCC 8.3.0] platform: Linux-5.6.0-1033-oem-x86_64-with-glibc2.2.5 optional deps. installed: [] Created statically: x name='x' type=int required=True None y name='y' type=float required=True None z name='z' type=str required=True None Created dynamically: x name='x' type=int required=True None y name='y' type=float required=True None z name='z' type=str required=True None . ========================================================================================== 1 passed, 2 warnings in 0.05s ========================================================================================== ``` The output for `pydantic==1.7.3` (warnings are pytest cache warnings): ``` =============================================================================================== test session starts =============================================================================================== platform linux -- Python 3.8.6, pytest-6.1.2, py-1.9.0, pluggy-0.13.1 rootdir: / collected 1 item pydantic_default_issue.py pydantic version: 1.7.3 pydantic compiled: True install path: /usr/local/lib/python3.8/site-packages/pydantic python version: 3.8.6 (default, Nov 25 2020, 02:47:44) [GCC 8.3.0] platform: Linux-5.6.0-1033-oem-x86_64-with-glibc2.2.5 optional deps. installed: [] Created statically: x name='x' type=int required=True None y name='y' type=float required=True None z name='z' type=str required=True None Created dynamically: x name='x' type=int required=True Ellipsis y name='y' type=float required=True Ellipsis z name='z' type=str required=True Ellipsis F ==================================================================================================== FAILURES ===================================================================================================== ____________________________________________________________________________ test_statically_and_dynamically_created_equivalent_models ____________________________________________________________________________ def test_statically_and_dynamically_created_equivalent_models(): print(f"\n{pydantic.utils.version_info()}") print("\nCreated statically:") for n, mf in get_field_name_to_pydantic_field(A).items(): print(n, mf, mf.default) print("\nCreated dynamically:") for n, mf in get_field_name_to_pydantic_field(DYNAMIC_MODEL).items(): print(n, mf, mf.default) for field_name in A.__fields__: > assert_model_fields(A.__fields__[field_name], DYNAMIC_MODEL.__fields__[field_name]) pydantic_default_issue.py:51: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ mf1 = ModelField(name='x', type=int, required=True), mf2 = ModelField(name='x', type=int, required=True) def assert_model_fields(mf1, mf2): assert mf1.type_ is mf2.type_ assert mf1.name == mf2.name > assert mf1.default == mf2.default E AssertionError: assert None == Ellipsis E + where None = ModelField(name='x', type=int, required=True).default E + and Ellipsis = ModelField(name='x', type=int, required=True).default pydantic_default_issue.py:28: AssertionError ============================================================================================= short test summary info ============================================================================================= FAILED pydantic_default_issue.py::test_statically_and_dynamically_created_equivalent_models - AssertionError: assert None == Ellipsis ========================================================================================== 1 failed, 3 warnings in 0.07s ========================================================================================== ```
0.0
de0657e4a5495de9378db9fe15a17334c2b0fae5
[ "tests/test_create_model.py::test_dynamic_and_static", "tests/test_dataclasses.py::test_fields", "tests/test_dataclasses.py::test_default_factory_field" ]
[ "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_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_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_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_pickle_overriden_builtin_dataclass" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2020-12-02 00:25:49+00:00
mit
4,772
pydantic__pydantic-2169
diff --git a/pydantic/networks.py b/pydantic/networks.py --- a/pydantic/networks.py +++ b/pydantic/networks.py @@ -61,7 +61,7 @@ def url_regex() -> Pattern[str]: r'(?P<domain>[^\s/:?#]+)' # domain, validation occurs later r')?' r'(?::(?P<port>\d+))?' # port - r'(?P<path>/[^\s?]*)?' # path + r'(?P<path>/[^\s?#]*)?' # path r'(?:\?(?P<query>[^\s#]+))?' # query r'(?:#(?P<fragment>\S+))?', # fragment re.IGNORECASE,
pydantic/pydantic
de0657e4a5495de9378db9fe15a17334c2b0fae5
diff --git a/tests/test_networks.py b/tests/test_networks.py --- a/tests/test_networks.py +++ b/tests/test_networks.py @@ -199,6 +199,15 @@ def test_at_in_path(): assert url.path == '/@handle' +def test_fragment_without_query(): + url = validate_url('https://pydantic-docs.helpmanual.io/usage/types/#constrained-types') + assert url.scheme == 'https' + assert url.host == 'pydantic-docs.helpmanual.io' + assert url.path == '/usage/types/' + assert url.query is None + assert url.fragment == 'constrained-types' + + @pytest.mark.parametrize( 'value', [
AnyUrl does not recognize fragment without query 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.7.3 pydantic compiled: True install path: /Users/andwhite/Projects/lipy-sso_trunk/build/lipy-sso/environments/development-venv/lib/python3.7/site-packages/pydantic python version: 3.7.7 (default, Mar 10 2020, 16:11:21) [Clang 11.0.0 (clang-1100.0.33.12)] platform: Darwin-19.6.0-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: --> RFC3986 indicates that a URI with a fragment but not a query is valid, but pydantic does not parse this correctly, instead treating the fragment as part of the path: ```py from pydantic import AnyUrl, BaseModel class Model(BaseModel): v: AnyUrl def test_url_fragment_without_query(): url = Model(v='https://pydantic-docs.helpmanual.io/usage/types/#constrained-types').v assert url.query is None assert url.fragment == 'constrainted-types' ``` Pytest output: ``` =========================================== test session starts =========================================== platform darwin -- Python 3.7.7, pytest-5.3.5, py-1.8.1, pluggy-0.13.1 hypothesis profile 'default' -> database=DirectoryBasedExampleDatabase('/Users/andwhite/Projects/lipy-sso_trunk/lipy-sso/.hypothesis/examples') rootdir: /Users/andwhite/Projects/lipy-sso_trunk/lipy-sso, inifile: setup.cfg plugins: xdist-1.29.0, requests-mock-1.8.0, html-2.0.1, forked-0.2, lipy-config-base-21.0.8, hypothesis-4.40.0, metadata-1.8.0, cov-2.8.1, lipy-sso-2.1.0 collected 1 item repro.py F [100%] ================================================ FAILURES ================================================= _____________________________________ test_url_fragment_without_query _____________________________________ def test_url_fragment_without_query(): url = Model(v='https://pydantic-docs.helpmanual.io/usage/types/#constrained-types').v assert url.query is None > assert url.fragment == 'constrainted-types' E AssertionError: assert None == 'constrainted-types' E + where None = AnyUrl('https://pydantic-docs.helpmanual.io/usage/types/#constrained-types', scheme='https', host='pydantic-docs.helpmanual.io', tld='io', host_type='domain', path='/usage/types/#constrained-types').fragment repro.py:11: AssertionError ============================================ 1 failed in 0.13s ============================================ ```
0.0
de0657e4a5495de9378db9fe15a17334c2b0fae5
[ "tests/test_networks.py::test_fragment_without_query" ]
[ "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+psycopg2://postgres:postgres@localhost:5432/hatch]", "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_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_parts", "tests/test_networks.py::test_url_repr", "tests/test_networks.py::test_ipv4_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_at_in_path", "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_postgres_dsns", "tests/test_networks.py::test_redis_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_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_test_patch": true, "is_lite": false }
2020-12-02 08:10:40+00:00
mit
4,773
pydantic__pydantic-2170
diff --git a/pydantic/schema.py b/pydantic/schema.py --- a/pydantic/schema.py +++ b/pydantic/schema.py @@ -404,7 +404,7 @@ def get_flat_models_from_models(models: Sequence[Type['BaseModel']]) -> TypeMode def get_long_model_name(model: TypeModelOrEnum) -> str: - return f'{model.__module__}__{model.__name__}'.replace('.', '__') + return f'{model.__module__}__{model.__qualname__}'.replace('.', '__') def field_type_schema(
pydantic/pydantic
13a5c7d676167b415080de5e6e6a74bea095b239
Hi @ArcArcaman and thanks for reporting! I feel like this issue has already been discussed and if I'm not mistaken [there is already a fix](https://github.com/samuelcolvin/pydantic/pull/2170) 😉 Maybe you can have a look to check if it indeed solves your problem. Happy holidays ❄️ Oh okay, thanks @PrettyWood! Yeah, it seems like it will solve my issue if the fix is merged. Sorry for the duplication, can't find it myself 😄 Happy holidays to you too ⛄
diff --git a/tests/test_schema.py b/tests/test_schema.py --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -2099,6 +2099,44 @@ class Model(BaseModel): } +def test_multiple_models_with_same_name(create_module): + module = create_module( + # language=Python + """ +from pydantic import BaseModel + + +class ModelOne(BaseModel): + class NestedModel(BaseModel): + a: float + + nested: NestedModel + + +class ModelTwo(BaseModel): + class NestedModel(BaseModel): + b: float + + nested: NestedModel + + +class NestedModel(BaseModel): + c: float + """ + ) + + models = [module.ModelOne, module.ModelTwo, module.NestedModel] + model_names = set(schema(models)['definitions'].keys()) + expected_model_names = { + 'ModelOne', + 'ModelTwo', + f'{module.__name__}__ModelOne__NestedModel', + f'{module.__name__}__ModelTwo__NestedModel', + f'{module.__name__}__NestedModel', + } + assert model_names == expected_model_names + + def test_multiple_enums_with_same_name(create_module): module_1 = create_module( # language=Python
KeyError when having same Inner Class name in different Outer Class ### 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.5.1 pydantic compiled: True install path: C:\Users\Dell\AppData\Local\Programs\Python\Python37\Lib\site-packages\pydantic python version: 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC v.1916 64 bit (AMD64)] platform: Windows-10-10.0.18362-SP0 optional deps. installed: ['typing-extensions'] ``` --- First of all, pydantic is awesome and super useful! Kudos to all the contributors! However, an error occurred when I was accessing the `/openapi.json` endpoint when I was testing out my FastAPI server. The response models are located in the models.py file which looks like this. ```py # models.py from pydantic import BaseModel from typing import List class AModel(BaseModel): class _InnerClass(BaseModel): error_code: str = "012345" errors: List[_InnerClass] = _InnerClass() class BModel(BaseModel): class _InnerClass(BaseModel): error_code: str = "123456" errors: List[_InnerClass] = _InnerClass() ``` The FastAPI server file looks like this. ```py # main.pyimport models from fastapi import FastAPI app = FastAPI() @app.get("/A", response_model=models.AModel) async def ARoute(): return models.AModel() @app.get("/B", response_model=models.BModel) async def BRoute(): return models.BModel() ``` When I run the command `uvicorn main:app` and accessed the route `/openapi.json` the following traceback is returned: ```shell Traceback (most recent call last): File "c:\users\dell\appdata\local\programs\python\python37\lib\site-packages\uvicorn\protocols\http\h11_impl.py", line 384, in run_asgi result = await app(self.scope, self.receive, self.send) File "c:\users\dell\appdata\local\programs\python\python37\lib\site-packages\uvicorn\middleware\proxy_headers.py", line 45, in __call__ return await self.app(scope, receive, send) File "c:\users\dell\appdata\local\programs\python\python37\lib\site-packages\fastapi\applications.py", line 190, in __call__ await super().__call__(scope, receive, send) File "c:\users\dell\appdata\local\programs\python\python37\lib\site-packages\starlette\applications.py", line 111, in __call__ await self.middleware_stack(scope, receive, send) File "c:\users\dell\appdata\local\programs\python\python37\lib\site-packages\starlette\middleware\errors.py", line 181, in __call__ raise exc from None File "c:\users\dell\appdata\local\programs\python\python37\lib\site-packages\starlette\middleware\errors.py", line 159, in __call__ await self.app(scope, receive, _send) File "c:\users\dell\appdata\local\programs\python\python37\lib\site-packages\starlette\exceptions.py", line 82, in __call__ raise exc from None File "c:\users\dell\appdata\local\programs\python\python37\lib\site-packages\starlette\exceptions.py", line 71, in __call__ await self.app(scope, receive, sender) File "c:\users\dell\appdata\local\programs\python\python37\lib\site-packages\starlette\routing.py", line 566, in __call__ await route.handle(scope, receive, send) File "c:\users\dell\appdata\local\programs\python\python37\lib\site-packages\starlette\routing.py", line 227, in handle await self.app(scope, receive, send) File "c:\users\dell\appdata\local\programs\python\python37\lib\site-packages\starlette\routing.py", line 41, in app response = await func(request) File "c:\users\dell\appdata\local\programs\python\python37\lib\site-packages\fastapi\applications.py", line 143, in openapi return JSONResponse(self.openapi()) File "c:\users\dell\appdata\local\programs\python\python37\lib\site-packages\fastapi\applications.py", line 128, in openapi servers=self.servers, File "c:\users\dell\appdata\local\programs\python\python37\lib\site-packages\fastapi\openapi\utils.py", line 350, in get_openapi flat_models=flat_models, model_name_map=model_name_map # type: ignore File "c:\users\dell\appdata\local\programs\python\python37\lib\site-packages\fastapi\utils.py", line 26, in get_model_definitions model, model_name_map=model_name_map, ref_prefix=REF_PREFIX # type: ignore File "pydantic\schema.py", line 455, in pydantic.schema.model_process_schema File "pydantic\schema.py", line 491, in pydantic.schema.model_type_schema File "pydantic\schema.py", line 185, in pydantic.schema.field_schema File "pydantic\schema.py", line 372, in pydantic.schema.field_type_schema File "pydantic\schema.py", line 614, in pydantic.schema.field_singleton_schema File "pydantic\schema.py", line 539, in pydantic.schema.field_singleton_sub_fields_schema File "pydantic\schema.py", line 412, in pydantic.schema.field_type_schema File "pydantic\schema.py", line 665, in pydantic.schema.field_singleton_schema KeyError: <class 'models.AModel._InnerClass'> ``` I temporarily solved the issue by editing the `get_long_model_name` function in [file](https://github.com/samuelcolvin/pydantic/blob/master/pydantic/schema.py) of my local copy to use model.\_\_qualname\_\_ (only for python 3.3+) instead of model.\_\_name\_\_: ```py ... def get_long_model_name(model: Type['BaseModel']) -> str: return f'{model.__module__}__{model.__qualname__}'.replace('.', '__') ... ```
0.0
13a5c7d676167b415080de5e6e6a74bea095b239
[ "tests/test_schema.py::test_multiple_models_with_same_name" ]
[ "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_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[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_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-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[kwargs8-type_8]", "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_unenforced_constraints_schema[kwargs11-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_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_enums_with_same_name" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2020-12-02 08:57:18+00:00
mit
4,774
pydantic__pydantic-2176
diff --git a/docs/examples/validation_decorator_field.py b/docs/examples/validation_decorator_field.py new file mode 100644 --- /dev/null +++ b/docs/examples/validation_decorator_field.py @@ -0,0 +1,22 @@ +from datetime import datetime +from pydantic import validate_arguments, Field, ValidationError +from pydantic.typing import Annotated + + +@validate_arguments +def how_many(num: Annotated[int, Field(gt=10)]): + return num + + +try: + how_many(1) +except ValidationError as e: + print(e) + + +@validate_arguments +def when(dt: datetime = Field(default_factory=datetime.now)): + return dt + + +print(type(when())) diff --git a/pydantic/decorator.py b/pydantic/decorator.py --- a/pydantic/decorator.py +++ b/pydantic/decorator.py @@ -184,7 +184,7 @@ def build_values(self, args: Tuple[Any, ...], kwargs: Dict[str, Any]) -> Dict[st return values def execute(self, m: BaseModel) -> Any: - d = {k: v for k, v in m._iter() if k in m.__fields_set__} + d = {k: v for k, v in m._iter() if k in m.__fields_set__ or m.__fields__[k].default_factory} var_kwargs = d.pop(self.v_kwargs_name, {}) if self.v_args_name in d:
pydantic/pydantic
fc18f8ef3490c5f0940de12268fb45e6ac9642d1
This is not currently possible. It won't be added immediately, but I'd definitely consider adding something like this in future. The way I had previously thought it would work, would be to add a model as an argument to `validate_arguments`, so it would be something like: ```py from datetime import datetime from pydantic import BaseModel, validate_arguments, Field class FooModel(BaseModel): dt: datetime = Field(default_factory=datetime.now) @validate_arguments(model=FooModel) def foo(dt: datetime): print(dt) ``` Then `validate_arguments` is just checking that `FooModel` matches the arguments of `foo()`. Your `Field` approach would be slightly shorter, but might upset mypy. I'd be open to considering both. OK, thanks. I will keep this issue open if necessary. I didn't even realise that Field wasn't supported in `validate_arguments` (didn't read the docs properly), so I didn't go looking for an issue until I tried to use it for a default argument. I've submitted a PR that fixes this particular case and doesn't break any of the other tests, but I've probably missed something so I'd welcome someone else's opinion on this. Also, mypy seems happy with this, it doesn't complain about the default value, and if you pass a value of a different type it will catch it For reference, the way I am using this at the moment: ```python class Line(BaseModel): key: Any = Field(..., description="An identifier for what to move") start: float = Field(..., description="Centre point of the first point of the line") stop: float = Field(..., description="Centre point of the last point of the line") num: int = Field(..., ge=1, description="Number of points to produce") @classmethod @validate_arguments def bounded( cls, key=key, lower: float = Field(..., description="Lower bound of the first point of the line"), upper: float = Field(..., description="Upper bound of the last point of the line"), num: int = num, ): half_step = (upper - lower) / num / 2 return cls(key=key, start=lower+half_step, stop=upper-half_step, num=num) ... ``` I then use the Field info to make a JSON schema of the classes, and create a GraphQL query of both class constructors and alternative classmethod constructors The re-use of the descriptions from Field definitions is a useful pattern
diff --git a/tests/test_decorator.py b/tests/test_decorator.py --- a/tests/test_decorator.py +++ b/tests/test_decorator.py @@ -3,12 +3,14 @@ import sys from pathlib import Path from typing import List +from unittest.mock import ANY import pytest -from pydantic import BaseModel, ValidationError, validate_arguments +from pydantic import BaseModel, Field, ValidationError, validate_arguments from pydantic.decorator import ValidatedFunction from pydantic.errors import ConfigError +from pydantic.typing import Annotated skip_pre_38 = pytest.mark.skipif(sys.version_info < (3, 8), reason='testing >= 3.8 behaviour only') @@ -142,6 +144,24 @@ def foo(a, b, *args, d=3, **kwargs): assert foo(1, 2, kwargs=4, e=5) == "a=1, b=2, args=(), d=3, kwargs={'kwargs': 4, 'e': 5}" +def test_field_can_provide_factory() -> None: + @validate_arguments + def foo(a: int, b: int = Field(default_factory=lambda: 99), *args: int) -> int: + """mypy is happy with this""" + return a + b + sum(args) + + assert foo(3) == 102 + assert foo(1, 2, 3) == 6 + + [email protected](not Annotated, reason='typing_extensions not installed') +def test_annotated_field_can_provide_factory() -> None: + @validate_arguments + def foo2(a: int, b: Annotated[int, Field(default_factory=lambda: 99)] = ANY, *args: int) -> int: + """mypy reports Incompatible default for argument "b" if we don't supply ANY as default""" + return a + b + sum(args) + + @skip_pre_38 def test_positional_only(create_module): module = create_module(
Can Field been used as function default argument value? # Feature Request Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.5a1 pydantic compiled: True install path: /home/xxx/.conda/envs/xxx/lib/python3.7/site-packages/pydantic python version: 3.7.4 (default, Aug 13 2019, 20:35:49) [GCC 7.3.0] platform: Linux-4.18.0-80.el8.x86_64-x86_64-with-centos-8.0.1905-Core optional deps. installed: ['typing-extensions', 'email-validator'] ``` Hi, I am trying the function decorator validate_arguments. Is it possible use Field as the default argument value like this? ```py from datetime import datetime from pydantic import validate_arguments, Field @validate_arguments def foo(dt: datetime = Field(default_factory=datetime.now)): print(dt) ```
0.0
fc18f8ef3490c5f0940de12268fb45e6ac9642d1
[ "tests/test_decorator.py::test_field_can_provide_factory" ]
[ "tests/test_decorator.py::test_args", "tests/test_decorator.py::test_wrap", "tests/test_decorator.py::test_kwargs", "tests/test_decorator.py::test_untyped", "tests/test_decorator.py::test_var_args_kwargs[True]", "tests/test_decorator.py::test_var_args_kwargs[False]", "tests/test_decorator.py::test_annotated_field_can_provide_factory", "tests/test_decorator.py::test_positional_only", "tests/test_decorator.py::test_args_name", "tests/test_decorator.py::test_v_args", "tests/test_decorator.py::test_async", "tests/test_decorator.py::test_string_annotation", "tests/test_decorator.py::test_item_method", "tests/test_decorator.py::test_class_method", "tests/test_decorator.py::test_config_title", "tests/test_decorator.py::test_config_title_cls", "tests/test_decorator.py::test_config_fields", "tests/test_decorator.py::test_config_arbitrary_types_allowed", "tests/test_decorator.py::test_validate" ]
{ "failed_lite_validators": [ "has_added_files" ], "has_test_patch": true, "is_lite": false }
2020-12-04 15:51:10+00:00
mit
4,775
pydantic__pydantic-2179
diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -16,7 +16,6 @@ List, Mapping, Optional, - Set, Tuple, Type, TypeVar, @@ -216,8 +215,9 @@ def __new__(mcs, name, bases, namespace, **kwargs): # noqa C901 pre_root_validators, post_root_validators = [], [] private_attributes: Dict[str, ModelPrivateAttr] = {} - slots: Set[str] = namespace.get('__slots__', ()) + slots: SetStr = namespace.get('__slots__', ()) slots = {slots} if isinstance(slots, str) else set(slots) + class_vars: SetStr = set() for base in reversed(bases): if _is_base_model_class_defined and issubclass(base, BaseModel) and base != BaseModel: @@ -227,6 +227,7 @@ def __new__(mcs, name, bases, namespace, **kwargs): # noqa C901 pre_root_validators += base.__pre_root_validators__ post_root_validators += base.__post_root_validators__ private_attributes.update(base.__private_attributes__) + class_vars.update(base.__class_vars__) config = inherit_config(namespace.get('Config'), config) validators = inherit_validators(extract_validators(namespace), validators) @@ -242,7 +243,6 @@ def __new__(mcs, name, bases, namespace, **kwargs): # noqa C901 prepare_config(config, name) - class_vars = set() if (namespace.get('__module__'), namespace.get('__qualname__')) != ('pydantic.main', 'BaseModel'): annotations = resolve_annotations(namespace.get('__annotations__', {}), namespace.get('__module__', None)) untouched_types = UNTOUCHED_TYPES + config.keep_untouched @@ -318,6 +318,7 @@ def __new__(mcs, name, bases, namespace, **kwargs): # noqa C901 '__custom_root_type__': _custom_root_type, '__private_attributes__': private_attributes, '__slots__': slots | private_attributes.keys(), + '__class_vars__': class_vars, **{n: v for n, v in namespace.items() if n not in exclude_from_namespace}, } @@ -344,6 +345,7 @@ class BaseModel(Representation, metaclass=ModelMetaclass): __custom_root_type__: bool = False __signature__: 'Signature' __private_attributes__: Dict[str, Any] + __class_vars__: SetStr __fields_set__: SetStr = set() Config = BaseConfig
pydantic/pydantic
de0657e4a5495de9378db9fe15a17334c2b0fae5
diff --git a/tests/test_main.py b/tests/test_main.py --- a/tests/test_main.py +++ b/tests/test_main.py @@ -908,6 +908,12 @@ class MyModel(BaseModel): assert list(MyModel.__fields__.keys()) == ['c'] + class MyOtherModel(MyModel): + a = '' + b = 2 + + assert list(MyOtherModel.__fields__.keys()) == ['c'] + def test_fields_set(): class MyModel(BaseModel):
ClassVar inheritance ### 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 feature/change is needed * [x] After submitting this, I commit to one of: * Look through open issues and helped at least one other person * Hit the "watch" button on this repo to receive notifications and I commit to help at least 2 people that ask questions in the future * Implement a Pull Request for a confirmed bug <!-- Sorry to sound so draconian, but every second saved replying to issues is time spend improving pydantic :-) --> # Feature Request Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.7 pydantic compiled: False install path: [...]/pydantic python version: 3.9.0 (default, Oct 8 2020, 06:18:59) [Clang 7.1.0 (tags/RELEASE_710/final)] platform: macOS-10.14.6-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 feature hasn't been asked for before, or already implemented. --> <!-- Where possible please include a self-contained code snippet describing your feature request: --> Currently, it is possible to annotate an attribute as being a class variable and it will be excluded from the model: ```py from typing import ClassVar from pydantic import BaseModel class Foo(BaseModel): class_var_to_be_redefined_on_children: ClassVar[str] = "value" class Bar(Foo): class_var_to_be_redefined_on_children = "some other value" ``` However, when inheriitng from a model with a `ClassVar`, overwriting the class variable produces an error: ``` Traceback (most recent call last): File "test.py", line 10, in <module> class Bar(Foo): File "pydantic/main.py", line 284, in __new__ validate_field_name(bases, var_name) File "utils.py", line 144, in validate_field_name raise NameError( NameError: Field name "class_var_to_be_redefined_on_children" shadows a BaseModel attribute; use a different field name with "alias='class_var_to_be_redefined_on_children'". ``` What appears to be happening here is that Pydantic assumes that `class_var_to_be_redefined_on_children` is a Pydantic field but errors out because there is a class attribute with the same name. I would prefer not to re-annotate subclass class variables with `ClassVar[T]`. I believe the following should also be interpret as a `ClassVar`, especially in conjunction with generic models (an uninitialised `ClassVar`): ```py from typing import ClassVar from pydantic import BaseModel class Foo(BaseModel): class_var_to_be_defined_on_children: ClassVar[str] class Bar(Foo): class_var_to_be_defined_on_children = "some other value" ``` ClassVar inheritance ### 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 feature/change is needed * [x] After submitting this, I commit to one of: * Look through open issues and helped at least one other person * Hit the "watch" button on this repo to receive notifications and I commit to help at least 2 people that ask questions in the future * Implement a Pull Request for a confirmed bug <!-- Sorry to sound so draconian, but every second saved replying to issues is time spend improving pydantic :-) --> # Feature Request Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.7 pydantic compiled: False install path: [...]/pydantic python version: 3.9.0 (default, Oct 8 2020, 06:18:59) [Clang 7.1.0 (tags/RELEASE_710/final)] platform: macOS-10.14.6-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 feature hasn't been asked for before, or already implemented. --> <!-- Where possible please include a self-contained code snippet describing your feature request: --> Currently, it is possible to annotate an attribute as being a class variable and it will be excluded from the model: ```py from typing import ClassVar from pydantic import BaseModel class Foo(BaseModel): class_var_to_be_redefined_on_children: ClassVar[str] = "value" class Bar(Foo): class_var_to_be_redefined_on_children = "some other value" ``` However, when inheriitng from a model with a `ClassVar`, overwriting the class variable produces an error: ``` Traceback (most recent call last): File "test.py", line 10, in <module> class Bar(Foo): File "pydantic/main.py", line 284, in __new__ validate_field_name(bases, var_name) File "utils.py", line 144, in validate_field_name raise NameError( NameError: Field name "class_var_to_be_redefined_on_children" shadows a BaseModel attribute; use a different field name with "alias='class_var_to_be_redefined_on_children'". ``` What appears to be happening here is that Pydantic assumes that `class_var_to_be_redefined_on_children` is a Pydantic field but errors out because there is a class attribute with the same name. I would prefer not to re-annotate subclass class variables with `ClassVar[T]`. I believe the following should also be interpret as a `ClassVar`, especially in conjunction with generic models (an uninitialised `ClassVar`): ```py from typing import ClassVar from pydantic import BaseModel class Foo(BaseModel): class_var_to_be_defined_on_children: ClassVar[str] class Bar(Foo): class_var_to_be_defined_on_children = "some other value" ```
0.0
de0657e4a5495de9378db9fe15a17334c2b0fae5
[ "tests/test_main.py::test_class_var" ]
[ "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_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_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_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_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_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_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", "tests/test_main.py::test_model_export_dict_exclusion", "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" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-12-06 19:10:42+00:00
mit
4,776
pydantic__pydantic-2181
diff --git a/pydantic/validators.py b/pydantic/validators.py --- a/pydantic/validators.py +++ b/pydantic/validators.py @@ -440,12 +440,17 @@ def int_enum_validator(v: Any) -> IntEnum: def make_literal_validator(type_: Any) -> Callable[[Any], Any]: permitted_choices = all_literal_values(type_) - allowed_choices_set = set(permitted_choices) + + # 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: - if v not in allowed_choices_set: + try: + return allowed_choices[v] + except KeyError: raise errors.WrongConstantError(given=v, permitted=permitted_choices) - return v return literal_validator
pydantic/pydantic
de0657e4a5495de9378db9fe15a17334c2b0fae5
Hi @yobiscus I feel like the issue is just related to the check done in literal where `'fiz' in {<Bar.FIZ: 'fiz'>}` is `True`. We could maybe do something like ```diff def make_literal_validator(type_: Any) -> Callable[[Any], Any]: permitted_choices = all_literal_values(type_) - allowed_choices_set = set(permitted_choices) def literal_validator(v: Any) -> Any: - if v not in allowed_choices_set: + for x in permitted_choices: + if x == v: + return x + else: raise errors.WrongConstantError(given=v, permitted=permitted_choices) - return v return literal_validator ``` to return the original value in `Literal` instead of the passed one but that would cost a bit of performance. There may be a better solution that's just the first one that came in mind. I see, thanks. This now makes sense given the logic. Now that I've had time to digest this some more, I feel like this is a bug in Pydantic (especially because the field is identified by mypy as an enum field rather than a string). Do you think any other types are subject to this issue? My guess is that this behaviour is unusual and specific to Enums because `"fiz" == Bar.FIZ` evaluates to `True` even though `isinstance("fiz", Bar)` evaluates to `False`. I would be happy to look more closely at a solution for this problem, but I am worried about breaking backwards compatibility in a 1.X release, so I'm also wondering what the recommended direction is for this issue.
diff --git a/tests/test_validators.py b/tests/test_validators.py --- a/tests/test_validators.py +++ b/tests/test_validators.py @@ -1,5 +1,6 @@ from collections import deque from datetime import datetime +from enum import Enum from itertools import product from typing import Dict, List, Optional, Tuple @@ -1135,6 +1136,28 @@ class Model(BaseModel): ] [email protected](not Literal, reason='typing_extensions not installed') +def test_literal_validator_str_enum(): + class Bar(str, Enum): + FIZ = 'fiz' + FUZ = 'fuz' + + class Foo(BaseModel): + bar: Bar + barfiz: Literal[Bar.FIZ] + fizfuz: Literal[Bar.FIZ, Bar.FUZ] + + my_foo = Foo.parse_obj({'bar': 'fiz', 'barfiz': 'fiz', 'fizfuz': 'fiz'}) + assert my_foo.bar is Bar.FIZ + assert my_foo.barfiz is Bar.FIZ + assert my_foo.fizfuz is Bar.FIZ + + my_foo = Foo.parse_obj({'bar': 'fiz', 'barfiz': 'fiz', 'fizfuz': 'fuz'}) + assert my_foo.bar is Bar.FIZ + assert my_foo.barfiz is Bar.FIZ + assert my_foo.fizfuz is Bar.FUZ + + @pytest.mark.skipif(not Literal, reason='typing_extensions not installed') def test_nested_literal_validator(): L1 = Literal['foo']
Literal enum fields are stored as mix-in type instead of enum field when using parse_raw or parse_json ### 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 feature/change is needed * [X] After submitting this, I commit to one of: * Look through open issues and helped at least one other person * Hit the "watch" button on this repo to receive notifications and I commit to help at least 2 people that ask questions in the future * Implement a Pull Request for a confirmed bug # Feature Request Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.7.1 pydantic compiled: True install path: /home/user/project/.venv/lib/python3.8/site-packages/pydantic python version: 3.8.5 (default, Jul 28 2020, 12:59:40) [GCC 9.3.0] platform: Linux-5.4.0-53-generic-x86_64-with-glibc2.29 optional deps. installed: ['typing-extensions'] ``` ```py import enum from typing import Literal from pydantic import BaseModel class Bar(str, enum.Enum): FIZ = "fiz" FUZ = "fuz" class Foo(BaseModel): bar: Bar barfiz: Literal[Bar.FIZ] Foo.parse_raw('{"bar": "fiz", "barfiz": "fiz"}') Foo.parse_obj({"bar": "fiz", "barfiz": "fiz"}) # both return: Foo(bar=<Bar.FIZ: 'fiz'>, barfiz='fiz') # expected: Foo(bar=<Bar.FIZ: 'fiz'>, barfiz=<Bar.FIZ: 'fiz'>) ``` I was expecting that the Pydantic would store `Bar.FIZ` for the `Literal[Bar.FIZ]` field above, as opposed to storing a `str` type (the enum's mix-in type. Mypy flags `Literal[Bar.FIZ]` above as an enum field, so accessing `value` on the `barfiz` attribute, for example, is perfectly fine by Mypy's rules, but breaks during runtime. I realize that mypy's support for Literal enum fields is relatively new, but they have interesting properties that I am looking to make use of (I would love to see this work with [discriminated union types](https://github.com/samuelcolvin/pydantic/issues/619), for example). Would you consider adding a Config field to enable this behaviour? Should this be flagged as a bug instead and targetted for a 2.0 release? Possibly related bugs: * https://github.com/samuelcolvin/pydantic/issues/1086 * https://github.com/samuelcolvin/pydantic/issues/1747
0.0
de0657e4a5495de9378db9fe15a17334c2b0fae5
[ "tests/test_validators.py::test_literal_validator_str_enum" ]
[ "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_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_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_nested_literal_validator", "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" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2020-12-07 09:16:26+00:00
mit
4,777
pydantic__pydantic-2183
diff --git a/docs/examples/types_constrained.py b/docs/examples/types_constrained.py --- a/docs/examples/types_constrained.py +++ b/docs/examples/types_constrained.py @@ -22,9 +22,11 @@ class Model(BaseModel): + lower_bytes: conbytes(to_lower=True) short_bytes: conbytes(min_length=2, max_length=10) strip_bytes: conbytes(strip_whitespace=True) + lower_str: constr(to_lower=True) short_str: constr(min_length=2, max_length=10) regex_str: constr(regex=r'^apple (pie|tart|sandwich)$') strip_str: constr(strip_whitespace=True) diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -106,6 +106,7 @@ class Extra(str, Enum): class BaseConfig: title = None + anystr_lower = False anystr_strip_whitespace = False min_anystr_length = None max_anystr_length = None diff --git a/pydantic/types.py b/pydantic/types.py --- a/pydantic/types.py +++ b/pydantic/types.py @@ -30,6 +30,7 @@ from .validators import ( bytes_validator, constr_length_validator, + constr_lower, constr_strip_whitespace, decimal_validator, float_validator, @@ -138,6 +139,7 @@ def _registered(typ: Union[Type[T], 'ConstrainedNumberMeta']) -> Union[Type[T], class ConstrainedBytes(bytes): strip_whitespace = False + to_lower = False min_length: OptionalInt = None max_length: OptionalInt = None strict: bool = False @@ -150,6 +152,7 @@ def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None: def __get_validators__(cls) -> 'CallableGenerator': yield strict_bytes_validator if cls.strict else bytes_validator yield constr_strip_whitespace + yield constr_lower yield constr_length_validator @@ -157,9 +160,11 @@ class StrictBytes(ConstrainedBytes): strict = True -def conbytes(*, strip_whitespace: bool = False, min_length: int = None, max_length: int = None) -> Type[bytes]: +def conbytes( + *, strip_whitespace: bool = False, to_lower: bool = False, min_length: int = None, max_length: int = None +) -> Type[bytes]: # use kwargs then define conf in a dict to aid with IDE type hinting - namespace = dict(strip_whitespace=strip_whitespace, min_length=min_length, max_length=max_length) + namespace = dict(strip_whitespace=strip_whitespace, to_lower=to_lower, min_length=min_length, max_length=max_length) return _registered(type('ConstrainedBytesValue', (ConstrainedBytes,), namespace)) @@ -246,6 +251,7 @@ def conset(item_type: Type[T], *, min_items: int = None, max_items: int = None) class ConstrainedStr(str): strip_whitespace = False + to_lower = False min_length: OptionalInt = None max_length: OptionalInt = None curtail_length: OptionalInt = None @@ -262,6 +268,7 @@ def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None: def __get_validators__(cls) -> 'CallableGenerator': yield strict_str_validator if cls.strict else str_validator yield constr_strip_whitespace + yield constr_lower yield constr_length_validator yield cls.validate @@ -280,6 +287,7 @@ def validate(cls, value: Union[str]) -> Union[str]: def constr( *, strip_whitespace: bool = False, + to_lower: bool = False, strict: bool = False, min_length: int = None, max_length: int = None, @@ -289,6 +297,7 @@ def constr( # use kwargs then define conf in a dict to aid with IDE type hinting namespace = dict( strip_whitespace=strip_whitespace, + to_lower=to_lower, strict=strict, min_length=min_length, max_length=max_length, diff --git a/pydantic/validators.py b/pydantic/validators.py --- a/pydantic/validators.py +++ b/pydantic/validators.py @@ -201,6 +201,10 @@ def anystr_strip_whitespace(v: 'StrBytes') -> 'StrBytes': return v.strip() +def anystr_lower(v: 'StrBytes') -> 'StrBytes': + return v.lower() + + def ordered_dict_validator(v: Any) -> 'AnyOrderedDict': if isinstance(v, OrderedDict): return v @@ -479,6 +483,13 @@ def constr_strip_whitespace(v: 'StrBytes', field: 'ModelField', config: 'BaseCon return v +def constr_lower(v: 'StrBytes', field: 'ModelField', config: 'BaseConfig') -> 'StrBytes': + lower = field.type_.to_lower or config.anystr_lower + if lower: + v = v.lower() + return v + + def validate_json(v: Any, config: 'BaseConfig') -> Any: if v is None: # pass None through to other validators @@ -555,6 +566,7 @@ def check(self, config: Type['BaseConfig']) -> bool: [ str_validator, IfConfig(anystr_strip_whitespace, 'anystr_strip_whitespace'), + IfConfig(anystr_lower, 'anystr_lower'), IfConfig(anystr_length_validator, 'min_anystr_length', 'max_anystr_length'), ], ), @@ -563,6 +575,7 @@ def check(self, config: Type['BaseConfig']) -> bool: [ bytes_validator, IfConfig(anystr_strip_whitespace, 'anystr_strip_whitespace'), + IfConfig(anystr_lower, 'anystr_lower'), IfConfig(anystr_length_validator, 'min_anystr_length', 'max_anystr_length'), ], ),
pydantic/pydantic
688107ec8e66f8da3bd1f97be6093a3cfab06a22
diff --git a/tests/test_types.py b/tests/test_types.py --- a/tests/test_types.py +++ b/tests/test_types.py @@ -108,6 +108,22 @@ def test_constrained_bytes_too_long(): ] +def test_constrained_bytes_lower_enabled(): + class Model(BaseModel): + v: conbytes(to_lower=True) + + m = Model(v=b'ABCD') + assert m.v == b'abcd' + + +def test_constrained_bytes_lower_disabled(): + class Model(BaseModel): + v: conbytes(to_lower=False) + + m = Model(v=b'ABCD') + assert m.v == b'ABCD' + + def test_constrained_list_good(): class ConListModelMax(BaseModel): v: conlist(int) = [] @@ -442,6 +458,22 @@ def test_constrained_str_too_long(): ] +def test_constrained_str_lower_enabled(): + class Model(BaseModel): + v: constr(to_lower=True) + + m = Model(v='ABCD') + assert m.v == 'abcd' + + +def test_constrained_str_lower_disabled(): + class Model(BaseModel): + v: constr(to_lower=False) + + m = Model(v='ABCD') + assert m.v == 'ABCD' + + def test_module_import(): class PyObjectModel(BaseModel): module: PyObject = 'os.path' @@ -1517,6 +1549,34 @@ class Config: assert m.bytes_check == b' 456 ' +def test_anystr_lower_enabled(): + class Model(BaseModel): + str_check: str + bytes_check: bytes + + class Config: + anystr_lower = True + + m = Model(str_check='ABCDefG', bytes_check=b'abCD1Fg') + + assert m.str_check == 'abcdefg' + assert m.bytes_check == b'abcd1fg' + + +def test_anystr_lower_disabled(): + class Model(BaseModel): + str_check: str + bytes_check: bytes + + class Config: + anystr_lower = False + + m = Model(str_check='ABCDefG', bytes_check=b'abCD1Fg') + + assert m.str_check == 'ABCDefG' + assert m.bytes_check == b'abCD1Fg' + + @pytest.mark.parametrize( 'type_,value,result', [
Adding "anystr_lower" to config # Feature Request Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.6.1 pydantic compiled: True install path: *** python version: 3.8.0 (v3.8.0:fa919fdf25, Oct 14 2019, 10:23:27) [Clang 6.0 (clang-600.0.57)] platform: macOS-10.15.7-x86_64-i386-64bit optional deps. installed: ['typing-extensions', 'email-validator'] ``` Just like there is "anystr_strip_whitespace" in the config, which runs .strip() on any string value, I would like to add "anystr_lower" which would run .lower() on any string value. I just find myself use .lower() on the strings in many validators in places in my code, so I thought it would be useful to add it to the config, I assume that was the use-case of "anystr_strip_whitespace" as well. If this is fine I'll gladly implement it myself, looks like it's a small change.
0.0
688107ec8e66f8da3bd1f97be6093a3cfab06a22
[ "tests/test_types.py::test_constrained_bytes_lower_enabled", "tests/test_types.py::test_constrained_bytes_lower_disabled", "tests/test_types.py::test_constrained_str_lower_enabled", "tests/test_types.py::test_constrained_str_lower_disabled", "tests/test_types.py::test_anystr_lower_enabled" ]
[ "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_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_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_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_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_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_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]" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-12-07 13:46:41+00:00
mit
4,778
pydantic__pydantic-2193
diff --git a/docs/examples/model_config_change_globally_custom.py b/docs/examples/model_config_change_globally_custom.py new file mode 100644 --- /dev/null +++ b/docs/examples/model_config_change_globally_custom.py @@ -0,0 +1,14 @@ +from pydantic import BaseModel as PydanticBaseModel + + +class BaseModel(PydanticBaseModel): + class Config: + arbitrary_types_allowed = True + + +class MyClass: + """A random class""" + + +class Model(BaseModel): + x: MyClass diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -128,6 +128,9 @@ class BaseConfig: json_encoders: Dict[Type[Any], AnyCallable] = {} underscore_attrs_are_private: bool = False + # Whether or not inherited models as fields should be reconstructed as base model + copy_on_model_validation: bool = True + @classmethod def get_field_info(cls, name: str) -> Dict[str, Any]: fields_value = cls.fields.get(name) @@ -669,7 +672,7 @@ def validate(cls: Type['Model'], value: Any) -> 'Model': if isinstance(value, dict): return cls(**value) elif isinstance(value, cls): - return value.copy() + return value.copy() if cls.__config__.copy_on_model_validation else value elif cls.__config__.orm_mode: return cls.from_orm(value) elif cls.__custom_root_type__:
pydantic/pydantic
a1ac464371bb9ac642f6e9b531cb787e2a8142c6
Hello @umesh-timalsina This is a known "issue", which may or may not be changed in v2. It reminds me of #265, which could help you. I'm currently not with my computer sorry Hello @PrettyWood. Thanks for the response. I will check the issue out.
diff --git a/tests/test_main.py b/tests/test_main.py --- a/tests/test_main.py +++ b/tests/test_main.py @@ -1425,3 +1425,50 @@ class M(BaseModel): a: int get_type_hints(M.__config__) + + +def test_inherited_model_field_copy(): + """It should copy models used as fields by default""" + + class Image(BaseModel): + path: str + + def __hash__(self): + return id(self) + + class Item(BaseModel): + images: List[Image] + + image_1 = Image(path='my_image1.png') + image_2 = Image(path='my_image2.png') + + item = Item(images={image_1, image_2}) + assert image_1 in item.images + + assert id(image_1) != id(item.images[0]) + assert id(image_2) != id(item.images[1]) + + +def test_inherited_model_field_untouched(): + """It should not copy models used as fields if explicitly asked""" + + class Image(BaseModel): + path: str + + def __hash__(self): + return id(self) + + class Config: + copy_on_model_validation = False + + class Item(BaseModel): + images: List[Image] + + image_1 = Image(path='my_image1.png') + image_2 = Image(path='my_image2.png') + + item = Item(images={image_1, image_2}) + assert image_1 in item.images + + assert id(image_1) == id(item.images[0]) + assert id(image_2) == id(item.images[1])
Nested basemodel contain different instances of child models in a collection than origially provided. # Question I wanted to use an ID based hashing for `BaseModel` instances. It appears to be the case that nested base models create new objects in a hashable collection like `set` or a mutable collection like `List`. Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.6.1 pydantic compiled: True install path: /home/umesh/personal/pydantic/pydantic python version: 3.7.8 | packaged by conda-forge | (default, Jul 31 2020, 02:25:08) [GCC 7.5.0] platform: Linux-5.0.0-32-generic-x86_64-with-debian-buster-sid optional deps. installed: ['typing-extensions', 'email-validator', 'devtools'] ``` In this snippet (grabbed from FastAPI examples). Class `Item` has a list of `Images`, which adhere to equality based on `id `. It appears to be the case that instance variable `images` of `Item` contain images are different from the ones originally provided from the constructor. Is there a way to skirt that? ```py from pydantic import BaseModel from typing import List, Set, Optional class Image(BaseModel): url: str name: str def __hash__(self): return id(self) def __eq__(self, other): return self is other class Item(BaseModel): name: str description: Optional[str] = None price: float tax: Optional[float] = None tags: Set[str] = [] images: Optional[List[Image]] = None image_1 = Image(url='https://s3.amazon-aws.com/dakl/kals', name='profile_pic_1.png') image_2 = Image(url='https://s3.amazon-aws.com/dakl/kals', name='profile_pic_1.png') item = Item(name='my_item1', price=0.050, images={image_1, image_2}) print(image_1 in item.images) print(id(image_1), id(item.images[0]), id(image_2), id(item.images[1])) ``` Output: ``` 139644562343408 139644562344208 139644562343328 139644562344368 ```
0.0
a1ac464371bb9ac642f6e9b531cb787e2a8142c6
[ "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_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_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_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_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_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", "tests/test_main.py::test_model_export_dict_exclusion", "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_inherited_model_field_copy" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_media", "has_added_files" ], "has_test_patch": true, "is_lite": false }
2020-12-10 21:43:22+00:00
mit
4,779
pydantic__pydantic-2196
diff --git a/pydantic/fields.py b/pydantic/fields.py --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -97,10 +97,25 @@ class FieldInfo(Representation): 'max_items', 'min_length', 'max_length', + 'allow_mutation', 'regex', 'extra', ) + __field_constraints__ = { # field constraints with the default value + 'min_length': None, + 'max_length': None, + 'regex': None, + 'gt': None, + 'lt': None, + 'ge': None, + 'le': None, + 'multiple_of': None, + 'min_items': None, + 'max_items': None, + 'allow_mutation': True, + } + def __init__(self, default: Any = Undefined, **kwargs: Any) -> None: self.default = default self.default_factory = kwargs.pop('default_factory', None) @@ -118,9 +133,22 @@ def __init__(self, default: Any = Undefined, **kwargs: Any) -> 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.allow_mutation = kwargs.pop('allow_mutation', True) self.regex = kwargs.pop('regex', None) self.extra = kwargs + def __repr_args__(self) -> 'ReprArgs': + attrs = ((s, getattr(self, s)) for s in self.__slots__) + return [(a, v) for a, v in attrs if v != self.__field_constraints__.get(a, None)] + + def get_constraints(self) -> Set[str]: + """ + Gets the constraints set on the field by comparing the constraint value with its default value + + :return: the constraints set on field_info + """ + return {attr for attr, default in self.__field_constraints__.items() if getattr(self, attr) != default} + def _validate(self) -> None: if self.default not in (Undefined, Ellipsis) and self.default_factory is not None: raise ValueError('cannot specify both default and default_factory') @@ -143,6 +171,7 @@ def Field( max_items: int = None, min_length: int = None, max_length: int = None, + allow_mutation: bool = True, regex: str = None, **extra: Any, ) -> Any: @@ -172,6 +201,8 @@ def Field( 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 allow_mutation: a boolean which defaults to True. When False, the field raises a TypeError if the field is + assigned on an instance. The BaseModel Config must set validate_assignment to True :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 @@ -192,6 +223,7 @@ def Field( max_items=max_items, min_length=min_length, max_length=max_length, + allow_mutation=allow_mutation, regex=regex, **extra, ) @@ -351,7 +383,7 @@ def infer( value = None elif value is not Undefined: required = False - annotation = get_annotation_from_field_info(annotation, field_info, name) + annotation = get_annotation_from_field_info(annotation, field_info, name, config.validate_assignment) return cls( name=name, type_=annotation, diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -425,6 +425,8 @@ def __setattr__(self, name, value): # noqa: C901 (ignore complexity) # - make sure validators are called without the current value for this field inside `values` # - keep other values (e.g. submodels) untouched (using `BaseModel.dict()` will change them into dicts) # - keep the order of the fields + if not known_field.field_info.allow_mutation: + raise TypeError(f'"{known_field.name}" has allow_mutation set to False and cannot be assigned') dict_without_original_value = {k: v for k, v in self.__dict__.items() if k != name} value, error_ = known_field.validate(value, dict_without_original_value, loc=name, cls=self.__class__) if error_: diff --git a/pydantic/schema.py b/pydantic/schema.py --- a/pydantic/schema.py +++ b/pydantic/schema.py @@ -876,32 +876,47 @@ def encode_default(dft: Any) -> Any: _map_types_constraint: Dict[Any, Callable[..., type]] = {int: conint, float: confloat, Decimal: condecimal} -_field_constraints = { - 'min_length', - 'max_length', - 'regex', - 'gt', - 'lt', - 'ge', - 'le', - 'multiple_of', - 'min_items', - 'max_items', -} - - -def get_annotation_from_field_info(annotation: Any, field_info: FieldInfo, field_name: str) -> Type[Any]: # noqa: C901 + + +def get_annotation_from_field_info( + annotation: Any, field_info: FieldInfo, field_name: str, validate_assignment: bool = False +) -> Type[Any]: """ 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 + :param validate_assignment: default False, flag for BaseModel Config value of validate_assignment :return: the same ``annotation`` if unmodified or a new annotation with validation in place """ - constraints = {f for f in _field_constraints if getattr(field_info, f) is not None} - if not constraints: - return annotation + constraints = field_info.get_constraints() + + used_constraints: Set[str] = set() + if constraints: + annotation, used_constraints = get_annotation_with_constraints(annotation, field_info) + + if validate_assignment: + used_constraints.add('allow_mutation') + + 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 annotation + + +def get_annotation_with_constraints(annotation: Any, field_info: FieldInfo) -> Tuple[Type[Any], Set[str]]: # noqa: C901 + """ + Get an annotation with used constraints 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 + :return: the same ``annotation`` if unmodified or a new annotation along with the used constraints. + """ used_constraints: Set[str] = set() def go(type_: Any) -> Type[Any]: @@ -975,15 +990,7 @@ def constraint_func(**kwargs: Any) -> Type[Any]: 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 + return ans, used_constraints def normalize_name(name: str) -> str:
pydantic/pydantic
b742c6f527f32fd0c6eb96f0a35f9e632a3af6bd
diff --git a/tests/test_main.py b/tests/test_main.py --- a/tests/test_main.py +++ b/tests/test_main.py @@ -1487,6 +1487,25 @@ class M(BaseModel): get_type_hints(M.__config__) +def test_allow_mutation_field(): + """assigning a allow_mutation=False field should raise a TypeError""" + + class Entry(BaseModel): + id: float = Field(allow_mutation=False) + val: float + + class Config: + validate_assignment = True + + r = Entry(id=1, val=100) + assert r.val == 100 + r.val = 101 + assert r.val == 101 + assert r.id == 1 + with pytest.raises(TypeError, match='"id" has allow_mutation set to False and cannot be assigned'): + r.id = 2 + + def test_inherited_model_field_copy(): """It should copy models used as fields by default""" diff --git a/tests/test_schema.py b/tests/test_schema.py --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -1431,6 +1431,7 @@ class Foo(BaseModel): ({'max_length': 5}, int), ({'min_length': 2}, float), ({'max_length': 5}, Decimal), + ({'allow_mutation': False}, bool), ({'regex': '^foo$'}, int), ({'gt': 2}, str), ({'lt': 5}, bytes),
Introduce a allow_mutation Field constraint ### 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 feature/change is needed * [x] After submitting this, I commit to one of: * Look through open issues and helped at least one other person * Hit the "watch" button on this repo to receive notifications and I commit to help at least 2 people that ask questions in the future * Implement a Pull Request for a confirmed bug <!-- Sorry to sound so draconian, but every second saved replying to issues is time spend improving pydantic :-) --> # Feature Request I found mentions of a readOnly parameter on the deprecated Schema class but it was not carried over to Field. Others are using validators to enforce readonly on assignment, but it's a common enough feature that pydantic could provide it natively. I am not able to use validators to create a readonly Field because I have validators that need to be run on initialization. Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.7.2 pydantic compiled: False install path: /Users/scootna/projects/pydantic/pydantic python version: 3.8.2 (default, Sep 24 2020, 19:37:08) [Clang 12.0.0 (clang-1200.0.32.21)] platform: macOS-10.15.7-x86_64-i386-64bit optional deps. installed: ['typing-extensions', 'email-validator', 'devtools'] ``` <!-- 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 feature hasn't been asked for before, or already implemented. --> <!-- Where possible please include a self-contained code snippet describing your feature request: --> ```py from pydantic import BaseModel, Field class Entry(BaseModel): id: float = Field(allow_mutation=False) val: float class Config: validate_assignment = True r = Entry(id=1, val=100) r.id = 2 # raise error when assigning to read_only field ... ```
0.0
b742c6f527f32fd0c6eb96f0a35f9e632a3af6bd
[ "tests/test_main.py::test_allow_mutation_field", "tests/test_schema.py::test_unenforced_constraints_schema[kwargs3-bool]" ]
[ "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_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_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_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_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", "tests/test_main.py::test_model_export_dict_exclusion", "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_inherited_model_field_copy", "tests/test_main.py::test_inherited_model_field_untouched", "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_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[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_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" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2020-12-12 18:05:12+00:00
mit
4,780
pydantic__pydantic-2214
diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -34,7 +34,15 @@ from .parse import Protocol, load_file, load_str_bytes from .schema import default_ref_template, model_schema from .types import PyObject, StrBytes -from .typing import AnyCallable, ForwardRef, get_origin, is_classvar, resolve_annotations, update_field_forward_refs +from .typing import ( + AnyCallable, + ForwardRef, + get_args, + get_origin, + is_classvar, + resolve_annotations, + update_field_forward_refs, +) from .utils import ( ROOT_KEY, ClassAttribute, @@ -253,10 +261,13 @@ def __new__(mcs, name, bases, namespace, **kwargs): # noqa C901 elif is_valid_field(ann_name): validate_field_name(bases, ann_name) value = namespace.get(ann_name, Undefined) + allowed_types = get_args(ann_type) if get_origin(ann_type) is Union else (ann_type,) if ( isinstance(value, untouched_types) and ann_type != PyObject - and not lenient_issubclass(get_origin(ann_type), Type) + and not any( + lenient_issubclass(get_origin(allowed_type), Type) for allowed_type in allowed_types + ) ): continue fields[ann_name] = inferred = ModelField.infer(
pydantic/pydantic
3496a473c73156fb02edf7dd8a1b1617a76a1b60
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 @@ -2,7 +2,7 @@ from collections.abc import Hashable from decimal import Decimal from enum import Enum -from typing import Any, Dict, FrozenSet, Generic, List, Optional, Set, Tuple, Type, TypeVar, Union +from typing import Any, Dict, FrozenSet, Generic, List, Optional, Sequence, Set, Tuple, Type, TypeVar, Union import pytest @@ -1122,8 +1122,11 @@ class Model(BaseModel): d: FooBar = FooBar e: Type[FooBar] f: Type[FooBar] = FooBar + g: Sequence[Type[FooBar]] = [FooBar] + h: Union[Type[FooBar], Sequence[Type[FooBar]]] = FooBar + i: Union[Type[FooBar], Sequence[Type[FooBar]]] = [FooBar] - assert Model.__fields__.keys() == {'b', 'c', 'e', 'f'} + assert Model.__fields__.keys() == {'b', 'c', 'e', 'f', 'g', 'h', 'i'} def test_assign_type():
Pydantic "Not Recognizing" Field in BaseModel with Default Value of 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 # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.7.3 pydantic compiled: True python version: 3.8.2 (default, Mar 13 2020, 10:14:16) [GCC 9.3.0] platform: Linux-4.19.128-microsoft-standard-x86_64-with-glibc2.29 optional deps. installed: ['typing-extensions'] ``` ```py import pydantic from typing import Type, Sequence, Union class T: pass class Model(pydantic.BaseModel): t: Union[Type[T], Sequence[Type[T]]] = T @pydantic.validator("t", always=True) def make_tuple(cls, v): if isinstance(v, Sequence): return tuple(v) return v, # ConfigError: Validators defined with incorrect fields: make_tuple (use check_fields=False if you're inheriting from the model and intended this) ``` **_Note:_** If the field is marked optional and the default value is set to `None`, the code works without issue. ```py import pydantic from typing import Type, Sequence, Union, Optional class T: pass class Model(pydantic.BaseModel): t: Optional[Union[Type[T], Sequence[Type[T]]]] = None @pydantic.validator("t", always=True) def make_tuple(cls, v): if not v: return T, elif isinstance(v, Sequence): return tuple(v) return v, Model() # Model(t=(<class '__main__.T'>,)) ``` Perhaps I am missing something obvious in my sleep-deprived stupor?
0.0
3496a473c73156fb02edf7dd8a1b1617a76a1b60
[ "tests/test_edge_cases.py::test_type_on_annotation" ]
[ "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_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_values_attr_deprecation", "tests/test_edge_cases.py::test_init_inspection", "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_fields_deprecated", "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_side_effect", "tests/test_edge_cases.py::test_default_factory_validator_child" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2020-12-22 09:54:13+00:00
mit
4,781
pydantic__pydantic-2216
diff --git a/docs/examples/annotated_types_named_tuple.py b/docs/examples/annotated_types_named_tuple.py new file mode 100644 --- /dev/null +++ b/docs/examples/annotated_types_named_tuple.py @@ -0,0 +1,20 @@ +from typing import NamedTuple + +from pydantic import BaseModel, ValidationError + + +class Point(NamedTuple): + x: int + y: int + + +class Model(BaseModel): + p: Point + + +print(Model(p=('1', '2'))) + +try: + Model(p=('1.3', '2')) +except ValidationError as e: + print(e) diff --git a/docs/examples/annotated_types_typed_dict.py b/docs/examples/annotated_types_typed_dict.py new file mode 100644 --- /dev/null +++ b/docs/examples/annotated_types_typed_dict.py @@ -0,0 +1,45 @@ +from typing import TypedDict + +from pydantic import BaseModel, Extra, ValidationError + + +# `total=False` means keys are non-required +class UserIdentity(TypedDict, total=False): + name: str + surname: str + + +class User(TypedDict): + identity: UserIdentity + age: int + + +class Model(BaseModel): + u: User + + class Config: + extra = Extra.forbid + + +print(Model(u={'identity': {'name': 'Smith', 'surname': 'John'}, 'age': '37'})) + +print(Model(u={'identity': {'name': None, 'surname': 'John'}, 'age': '37'})) + +print(Model(u={'identity': {}, 'age': '37'})) + + +try: + Model(u={'identity': {'name': ['Smith'], 'surname': 'John'}, 'age': '24'}) +except ValidationError as e: + print(e) + +try: + Model( + u={ + 'identity': {'name': 'Smith', 'surname': 'John'}, + 'age': '37', + 'email': '[email protected]', + } + ) +except ValidationError as e: + print(e) diff --git a/docs/examples/models_from_typeddict.py b/docs/examples/models_from_typeddict.py new file mode 100644 --- /dev/null +++ b/docs/examples/models_from_typeddict.py @@ -0,0 +1,21 @@ +from typing import TypedDict + +from pydantic import ValidationError, create_model_from_typeddict + + +class User(TypedDict): + name: str + id: int + + +class Config: + extra = 'forbid' + + +UserM = create_model_from_typeddict(User, __config__=Config) +print(repr(UserM(name=123, id='3'))) + +try: + UserM(name=123, id='3', other='no') +except ValidationError as e: + print(e) diff --git a/pydantic/__init__.py b/pydantic/__init__.py --- a/pydantic/__init__.py +++ b/pydantic/__init__.py @@ -1,5 +1,6 @@ # flake8: noqa from . import dataclasses +from .annotated_types import create_model_from_namedtuple, create_model_from_typeddict from .class_validators import root_validator, validator from .decorator import validate_arguments from .env_settings import BaseSettings @@ -16,6 +17,9 @@ # WARNING __all__ from .errors is not included here, it will be removed as an export here in v2 # please use "from pydantic.errors import ..." instead __all__ = [ + # annotated types utils + 'create_model_from_namedtuple', + 'create_model_from_typeddict', # dataclasses 'dataclasses', # class_validators diff --git a/pydantic/annotated_types.py b/pydantic/annotated_types.py new file mode 100644 --- /dev/null +++ b/pydantic/annotated_types.py @@ -0,0 +1,59 @@ +from typing import TYPE_CHECKING, Any, Dict, FrozenSet, NamedTuple, Type + +from .fields import Required +from .main import BaseModel, create_model + +if TYPE_CHECKING: + + class TypedDict(Dict[str, Any]): + __annotations__: Dict[str, Type[Any]] + __total__: bool + __required_keys__: FrozenSet[str] + __optional_keys__: FrozenSet[str] + + +def create_model_from_typeddict(typeddict_cls: Type['TypedDict'], **kwargs: Any) -> Type['BaseModel']: + """ + Create a `BaseModel` based on the fields of a `TypedDict`. + Since `typing.TypedDict` in Python 3.8 does not store runtime information about optional keys, + we warn the user if that's the case (see https://bugs.python.org/issue38834). + """ + field_definitions: Dict[str, Any] + + # Best case scenario: with python 3.9+ or when `TypedDict` is imported from `typing_extensions` + if hasattr(typeddict_cls, '__required_keys__'): + field_definitions = { + field_name: (field_type, Required if field_name in typeddict_cls.__required_keys__ else None) + for field_name, field_type in typeddict_cls.__annotations__.items() + } + else: + import warnings + + warnings.warn( + 'You should use `typing_extensions.TypedDict` instead of `typing.TypedDict` for better support! ' + 'Without it, there is no way to differentiate required and optional fields when subclassed. ' + 'Fields will therefore be considered all required or all optional depending on class totality.', + UserWarning, + ) + default_value = Required if typeddict_cls.__total__ else None + field_definitions = { + field_name: (field_type, default_value) for field_name, field_type in typeddict_cls.__annotations__.items() + } + + return create_model(typeddict_cls.__name__, **kwargs, **field_definitions) + + +def create_model_from_namedtuple(namedtuple_cls: Type['NamedTuple'], **kwargs: Any) -> Type['BaseModel']: + """ + Create a `BaseModel` based on the fields of a named tuple. + A named tuple can be created with `typing.NamedTuple` and declared annotations + but also with `collections.namedtuple`, in this case we consider all fields + to have type `Any`. + """ + namedtuple_annotations: Dict[str, Type[Any]] = getattr( + namedtuple_cls, '__annotations__', {k: Any for k in namedtuple_cls._fields} + ) + field_definitions: Dict[str, Any] = { + field_name: (field_type, Required) for field_name, field_type in namedtuple_annotations.items() + } + return create_model(namedtuple_cls.__name__, **kwargs, **field_definitions) diff --git a/pydantic/fields.py b/pydantic/fields.py --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -38,6 +38,7 @@ get_origin, is_literal_type, is_new_type, + is_typeddict, new_type_supertype, ) from .utils import PyObjectStr, Representation, lenient_issubclass, sequence_like, smart_deepcopy @@ -416,6 +417,8 @@ def _type_analysis(self) -> None: # noqa: C901 (ignore complexity) return elif is_literal_type(self.type_): return + elif is_typeddict(self.type_): + return origin = get_origin(self.type_) if origin is None: diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -34,7 +34,15 @@ from .parse import Protocol, load_file, load_str_bytes from .schema import default_ref_template, model_schema from .types import PyObject, StrBytes -from .typing import AnyCallable, get_args, get_origin, is_classvar, resolve_annotations, update_field_forward_refs +from .typing import ( + AnyCallable, + get_args, + get_origin, + is_classvar, + is_namedtuple, + resolve_annotations, + update_field_forward_refs, +) from .utils import ( ROOT_KEY, ClassAttribute, @@ -732,7 +740,7 @@ def _get_value( } elif sequence_like(v): - return v.__class__( + seq_args = ( cls._get_value( v_, to_dict=to_dict, @@ -748,6 +756,8 @@ def _get_value( and (not value_include or value_include.is_included(i)) ) + return v.__class__(*seq_args) if is_namedtuple(v.__class__) else v.__class__(seq_args) + elif isinstance(v, Enum) and getattr(cls.Config, 'use_enum_values', False): return v.value diff --git a/pydantic/schema.py b/pydantic/schema.py --- a/pydantic/schema.py +++ b/pydantic/schema.py @@ -65,6 +65,7 @@ get_origin, is_callable_type, is_literal_type, + is_namedtuple, literal_values, ) from .utils import ROOT_KEY, get_model, lenient_issubclass, sequence_like @@ -795,7 +796,17 @@ def field_singleton_schema( # noqa: C901 (ignore complexity) f_schema, schema_overrides = get_field_info_schema(field) f_schema.update(get_schema_ref(enum_name, ref_prefix, ref_template, schema_overrides)) definitions[enum_name] = enum_process_schema(field_type) - else: + elif is_namedtuple(field_type): + sub_schema, *_ = model_process_schema( + field_type.__pydantic_model__, + by_alias=by_alias, + model_name_map=model_name_map, + ref_prefix=ref_prefix, + ref_template=ref_template, + known_models=known_models, + ) + f_schema.update({'type': 'array', 'items': list(sub_schema['properties'].values())}) + elif not hasattr(field_type, '__pydantic_model__'): add_field_type_to_schema(field_type, f_schema) modify_schema = getattr(field_type, '__modify_schema__', None) diff --git a/pydantic/typing.py b/pydantic/typing.py --- a/pydantic/typing.py +++ b/pydantic/typing.py @@ -188,6 +188,8 @@ def get_args(tp: Type[Any]) -> Tuple[Any, ...]: 'is_literal_type', 'literal_values', 'Literal', + 'is_namedtuple', + 'is_typeddict', 'is_new_type', 'new_type_supertype', 'is_classvar', @@ -298,6 +300,26 @@ def all_literal_values(type_: Type[Any]) -> Tuple[Any, ...]: return tuple(x for value in values for x in all_literal_values(value)) +def is_namedtuple(type_: Type[Any]) -> bool: + """ + Check if a given class is a named tuple. + It can be either a `typing.NamedTuple` or `collections.namedtuple` + """ + from .utils import lenient_issubclass + + return lenient_issubclass(type_, tuple) and hasattr(type_, '_fields') + + +def is_typeddict(type_: Type[Any]) -> bool: + """ + Check if a given class is a typed dict (from `typing` or `typing_extensions`) + In 3.10, there will be a public method (https://docs.python.org/3.10/library/typing.html#typing.is_typeddict) + """ + from .utils import lenient_issubclass + + return lenient_issubclass(type_, dict) and hasattr(type_, '__total__') + + test_type = NewType('test_type', str) diff --git a/pydantic/validators.py b/pydantic/validators.py --- a/pydantic/validators.py +++ b/pydantic/validators.py @@ -15,6 +15,7 @@ FrozenSet, Generator, List, + NamedTuple, Pattern, Set, Tuple, @@ -36,10 +37,13 @@ get_class, is_callable_type, is_literal_type, + is_namedtuple, + is_typeddict, ) from .utils import almost_equal_floats, lenient_issubclass, sequence_like if TYPE_CHECKING: + from .annotated_types import TypedDict from .fields import ModelField from .main import BaseConfig from .types import ConstrainedDecimal, ConstrainedFloat, ConstrainedInt @@ -536,6 +540,42 @@ def pattern_validator(v: Any) -> Pattern[str]: raise errors.PatternError() +NamedTupleT = TypeVar('NamedTupleT', bound=NamedTuple) + + +def make_namedtuple_validator(namedtuple_cls: Type[NamedTupleT]) -> Callable[[Tuple[Any, ...]], NamedTupleT]: + from .annotated_types import create_model_from_namedtuple + + NamedTupleModel = create_model_from_namedtuple(namedtuple_cls) + namedtuple_cls.__pydantic_model__ = NamedTupleModel # type: ignore[attr-defined] + + def namedtuple_validator(values: Tuple[Any, ...]) -> NamedTupleT: + annotations = NamedTupleModel.__annotations__ + + if len(values) > len(annotations): + raise errors.ListMaxLengthError(limit_value=len(annotations)) + + dict_values: Dict[str, Any] = dict(zip(annotations, values)) + validated_dict_values: Dict[str, Any] = dict(NamedTupleModel(**dict_values)) + return namedtuple_cls(**validated_dict_values) + + return namedtuple_validator + + +def make_typeddict_validator( + typeddict_cls: Type['TypedDict'], config: Type['BaseConfig'] +) -> Callable[[Any], Dict[str, Any]]: + from .annotated_types import create_model_from_typeddict + + TypedDictModel = create_model_from_typeddict(typeddict_cls, __config__=config) + typeddict_cls.__pydantic_model__ = TypedDictModel # type: ignore[attr-defined] + + def typeddict_validator(values: 'TypedDict') -> Dict[str, Any]: + return TypedDictModel.parse_obj(values).dict(exclude_unset=True) + + return typeddict_validator + + class IfConfig: def __init__(self, validator: AnyCallable, *config_attr_names: str) -> None: self.validator = validator @@ -626,6 +666,13 @@ def find_validators( # noqa: C901 (ignore complexity) if type_ is IntEnum: yield int_enum_validator return + if is_namedtuple(type_): + yield tuple_validator + yield make_namedtuple_validator(type_) + return + if is_typeddict(type_): + yield make_typeddict_validator(type_, config) + return class_ = get_class(type_) if class_ is not None:
pydantic/pydantic
13a5c7d676167b415080de5e6e6a74bea095b239
afaik `TypedDict` is supported by pydantic, see #760. Anything that does work will be flakey, will not perform proper validation and could break at any time. I think best to explicitly raise an error whenever a `TypedDict` is used, saying >`TypedDict` is not yet supported, see #760 I think `TypedDict` fields were usable with pydantic==1.4, but, as far as I can tell, the above `TypeError` does occur in pydantic>=1.5. I think you're right, though, and it probably is best to raise an explicit error when `TypedDict` is used as a model field until `TypedDict` is fully supported. I confirm `TypedDict` were usable with pydantic 1.4 There's no logic for validating `TypedDict`, so while you might have been able to use them, I very much doubt it was a good idea. We should either support them fully or raise a sensible exception explaining that they don't work. This is an issue about raising a better error, #760 is about supporting them fully. I'm aware that no logic validation is currently performed by _pydantic_ and it is fine with me. > We should either support them fully or raise a sensible exception explaining that they don't work. There is also the option of treating them as `Dict[Any, Any]` for validation (they are dict at run-time after all). That way, one could still get proper _mypy_ warnings during development and pydantic validation would just reduce to `isinstance(variable, dict)` v1.4 behaved like this: ``` In []: from typing import TypedDict In []: from pydantic import BaseModel In []: class MyDict(TypedDict): ...: a: int In []: class A(BaseModel): ...: d: MyDict In []: A(d={}) Out[]: A(d={}) In []: A(d=12) --------------------------------------------------------------------------- ValidationError: 1 validation error for A d value is not a valid dict (type=type_error.dict) ``` > There's no logic for validating TypedDict Actually TypedDict does contain validation instructions ``` >>> from typing import TypedDict >>> class Person(TypedDict): ... name: str ... age: int >>> Person.__annotations__ {'name': <class 'str'>, 'age': <class 'int'>} ``` So technically Pydantic should be able to validate dictionaries that are type hinted with `TypedDicts` Yes, it's possible, now someone just needs to go and implement the feature. 😄 I currently have a working solution for this which does validation based on the TypedDict annotations as suggested. I'm currently writing test cases and will post an update when I've got full coverage. My solution is here, but there are parts of it that I think could probably be done better: [https://github.com/kpberry/pydantic/commits/typed-dict-support](url) 1. `TypedDict` does not support `issubclass` checks (which was the initial issue in this thread), so in order to check if a type is a subtype of `TypedDict` in `ModelField._type_analysis`, it seems like we need to check if it is a subclass of `TypedDict`'s metaclass. Unfortunately, `_TypedDictMeta` is protected in both the typing and typing_extensions module, so the mypy check won't allow it to be imported (probably for good reason). For now, I check `self.type_.__class__.__name__ == '_TypedDictMeta'`, but I think there must be a better way to do this. 2. I'm not sure what the best spot is in `ModelField._type_analysis` to do the `TypedDict` subclass check. I put it before the origin checks to avoid the issue at the top of this thread, but there might be a better spot for it. 3. I added each `TypedDict` value type to `self.sub_fields` in `ModelField._type_analysis`, since it fit the pattern for validating `Tuple`s, etc. However, since each value corresponds to a specific named key, I had to add a `key_name` attribute to `ModelField` with the key name in order to implement `ModelField._validate_typeddict`. I'm not sure if it's a good idea to add new attributes to `ModelField` for this, especially considering that it's a relatively niche feature. Would appreciate feedback/suggestions before trying to make a pull request. Edit: Forgot to mention, all tests are passing and all lines that I added should be covered. Edit 2: I noticed that there's an optional `total` parameter to `TypedDict`, so I added support and tests for that.
diff --git a/tests/test_annotated_types.py b/tests/test_annotated_types.py new file mode 100644 --- /dev/null +++ b/tests/test_annotated_types.py @@ -0,0 +1,278 @@ +""" +Tests for annotated types that _pydantic_ can validate like +- NamedTuple +- TypedDict +""" +import json +import sys +from collections import namedtuple +from typing import List, NamedTuple, Tuple + +if sys.version_info < (3, 9): + try: + from typing import TypedDict as LegacyTypedDict + except ImportError: + LegacyTypedDict = None + + try: + from typing_extensions import TypedDict + except ImportError: + TypedDict = None +else: + from typing import TypedDict + + LegacyTypedDict = None + +import pytest + +from pydantic import BaseModel, ValidationError + + +def test_namedtuple(): + Position = namedtuple('Pos', 'x y') + + class Event(NamedTuple): + a: int + b: int + c: int + d: str + + class Model(BaseModel): + pos: Position + events: List[Event] + + model = Model(pos=('1', 2), events=[[b'1', '2', 3, 'qwe']]) + assert isinstance(model.pos, Position) + assert isinstance(model.events[0], Event) + assert model.pos.x == '1' + assert model.pos == Position('1', 2) + assert model.events[0] == Event(1, 2, 3, 'qwe') + assert repr(model) == "Model(pos=Pos(x='1', y=2), events=[Event(a=1, b=2, c=3, d='qwe')])" + assert model.json() == json.dumps(model.dict()) == '{"pos": ["1", 2], "events": [[1, 2, 3, "qwe"]]}' + + with pytest.raises(ValidationError) as exc_info: + Model(pos=('1', 2), events=[['qwe', '2', 3, 'qwe']]) + assert exc_info.value.errors() == [ + { + 'loc': ('events', 0, 'a'), + 'msg': 'value is not a valid integer', + 'type': 'type_error.integer', + } + ] + + +def test_namedtuple_schema(): + class Position1(NamedTuple): + x: int + y: int + + Position2 = namedtuple('Position2', 'x y') + + class Model(BaseModel): + pos1: Position1 + pos2: Position2 + pos3: Tuple[int, int] + + assert Model.schema() == { + 'title': 'Model', + 'type': 'object', + 'properties': { + 'pos1': { + 'title': 'Pos1', + 'type': 'array', + 'items': [ + {'title': 'X', 'type': 'integer'}, + {'title': 'Y', 'type': 'integer'}, + ], + }, + 'pos2': { + 'title': 'Pos2', + 'type': 'array', + 'items': [ + {'title': 'X'}, + {'title': 'Y'}, + ], + }, + 'pos3': { + 'title': 'Pos3', + 'type': 'array', + 'items': [ + {'type': 'integer'}, + {'type': 'integer'}, + ], + }, + }, + 'required': ['pos1', 'pos2', 'pos3'], + } + + +def test_namedtuple_right_length(): + class Point(NamedTuple): + x: int + y: int + + class Model(BaseModel): + p: Point + + assert isinstance(Model(p=(1, 2)), Model) + + with pytest.raises(ValidationError) as exc_info: + Model(p=(1, 2, 3)) + assert exc_info.value.errors() == [ + { + 'loc': ('p',), + 'msg': 'ensure this value has at most 2 items', + 'type': 'value_error.list.max_items', + 'ctx': {'limit_value': 2}, + } + ] + + [email protected](not TypedDict, reason='typing_extensions not installed') +def test_typeddict(): + class TD(TypedDict): + a: int + b: int + c: int + d: str + + class Model(BaseModel): + td: TD + + m = Model(td={'a': '3', 'b': b'1', 'c': 4, 'd': 'qwe'}) + assert m.td == {'a': 3, 'b': 1, 'c': 4, 'd': 'qwe'} + + with pytest.raises(ValidationError) as exc_info: + Model(td={'a': [1], 'b': 2, 'c': 3, 'd': 'qwe'}) + assert exc_info.value.errors() == [ + { + 'loc': ('td', 'a'), + 'msg': 'value is not a valid integer', + 'type': 'type_error.integer', + } + ] + + [email protected](not TypedDict, reason='typing_extensions not installed') +def test_typeddict_non_total(): + class FullMovie(TypedDict, total=True): + name: str + year: int + + class Model(BaseModel): + movie: FullMovie + + with pytest.raises(ValidationError) as exc_info: + Model(movie={'year': '2002'}) + assert exc_info.value.errors() == [ + { + 'loc': ('movie', 'name'), + 'msg': 'field required', + 'type': 'value_error.missing', + } + ] + + class PartialMovie(TypedDict, total=False): + name: str + year: int + + class Model(BaseModel): + movie: PartialMovie + + m = Model(movie={'year': '2002'}) + assert m.movie == {'year': 2002} + + [email protected](not TypedDict, reason='typing_extensions not installed') +def test_partial_new_typeddict(): + class OptionalUser(TypedDict, total=False): + name: str + + class User(OptionalUser): + id: int + + class Model(BaseModel): + user: User + + m = Model(user={'id': 1}) + assert m.user == {'id': 1} + + [email protected](not LegacyTypedDict, reason='python 3.9+ is used or typing_extensions is installed') +def test_partial_legacy_typeddict(): + class OptionalUser(LegacyTypedDict, total=False): + name: str + + class User(OptionalUser): + id: int + + with pytest.warns( + UserWarning, + match='You should use `typing_extensions.TypedDict` instead of `typing.TypedDict` for better support!', + ): + + class Model(BaseModel): + user: User + + with pytest.raises(ValidationError) as exc_info: + Model(user={'id': 1}) + assert exc_info.value.errors() == [ + { + 'loc': ('user', 'name'), + 'msg': 'field required', + 'type': 'value_error.missing', + } + ] + + [email protected](not TypedDict, reason='typing_extensions not installed') +def test_typeddict_extra(): + class User(TypedDict): + name: str + age: int + + class Model(BaseModel): + u: User + + class Config: + extra = 'forbid' + + with pytest.raises(ValidationError) as exc_info: + Model(u={'name': 'pika', 'age': 7, 'rank': 1}) + assert exc_info.value.errors() == [ + {'loc': ('u', 'rank'), 'msg': 'extra fields not permitted', 'type': 'value_error.extra'}, + ] + + [email protected](not TypedDict, reason='typing_extensions not installed') +def test_typeddict_schema(): + class Data(BaseModel): + a: int + + class DataTD(TypedDict): + a: int + + class Model(BaseModel): + data: Data + data_td: DataTD + + assert Model.schema() == { + 'title': 'Model', + 'type': 'object', + 'properties': {'data': {'$ref': '#/definitions/Data'}, 'data_td': {'$ref': '#/definitions/DataTD'}}, + 'required': ['data', 'data_td'], + 'definitions': { + 'Data': { + 'type': 'object', + 'title': 'Data', + 'properties': {'a': {'title': 'A', 'type': 'integer'}}, + 'required': ['a'], + }, + 'DataTD': { + 'type': 'object', + 'title': 'DataTD', + 'properties': {'a': {'title': 'A', 'type': 'integer'}}, + 'required': ['a'], + }, + }, + } diff --git a/tests/test_typing.py b/tests/test_typing.py new file mode 100644 --- /dev/null +++ b/tests/test_typing.py @@ -0,0 +1,56 @@ +from collections import namedtuple +from typing import NamedTuple + +import pytest + +from pydantic.typing import is_namedtuple, is_typeddict + +try: + from typing import TypedDict as typing_TypedDict +except ImportError: + typing_TypedDict = None + +try: + from typing_extensions import TypedDict as typing_extensions_TypedDict +except ImportError: + typing_extensions_TypedDict = None + + +try: + from mypy_extensions import TypedDict as mypy_extensions_TypedDict +except ImportError: + mypy_extensions_TypedDict = None + +ALL_TYPEDDICT_KINDS = (typing_TypedDict, typing_extensions_TypedDict, mypy_extensions_TypedDict) + + +def test_is_namedtuple(): + class Employee(NamedTuple): + name: str + id: int = 3 + + assert is_namedtuple(namedtuple('Point', 'x y')) is True + assert is_namedtuple(Employee) is True + assert is_namedtuple(NamedTuple('Employee', [('name', str), ('id', int)])) is True + + class Other(tuple): + name: str + id: int + + assert is_namedtuple(Other) is False + + [email protected]('TypedDict', (t for t in ALL_TYPEDDICT_KINDS if t is not None)) +def test_is_typeddict_typing(TypedDict): + class Employee(TypedDict): + name: str + id: int + + assert is_typeddict(Employee) is True + assert is_typeddict(TypedDict('Employee', {'name': str, 'id': int})) is True + + class Other(dict): + name: str + id: int + + assert is_typeddict(Other) is False
"TypeError: TypedDict does not support instance and class checks" for TypedDict field # Bug Models with TypedDict fields currently result in an error when they are instantiated, due to the fact that TypedDict does not support isinstance/issubclass checks. ```py from typing import TypedDict from pydantic import BaseModel TD = TypedDict('TD', {'a': int}) class ExampleModel(BaseModel): td: TD m = ExampleModel(td={'a': 1}) # output: # Traceback (most recent call last): # ... # File "pydantic/main.py", line 246, in pydantic.main.ModelMetaclass.__new__ # File "pydantic/fields.py", line 310, in pydantic.fields.ModelField.infer # File "pydantic/fields.py", line 272, in pydantic.fields.ModelField.__init__ # File "pydantic/fields.py", line 364, in pydantic.fields.ModelField.prepare # File "pydantic/fields.py", line 405, in pydantic.fields.ModelField._type_analysis # File "/usr/lib/python3.8/typing.py", line 1728, in _check_fails # raise TypeError('TypedDict does not support instance and class checks') # TypeError: TypedDict does not support instance and class checks ``` Previously, models could have TypedDict fields without any problems. This error seems to have been introduced in commit #1266. Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.5.1 pydantic compiled: False install path: /home/kpberry/Downloads/pydantic/pydantic python version: 3.8.2 (default, Mar 13 2020, 10:14:16) [GCC 9.3.0] platform: Linux-5.4.0-26-generic-x86_64-with-glibc2.29 optional deps. installed: ['typing-extensions', 'email-validator', 'devtools'] ```
0.0
13a5c7d676167b415080de5e6e6a74bea095b239
[ "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_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_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_typeddict_typing[TypedDict2]" ]
[]
{ "failed_lite_validators": [ "has_added_files", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2020-12-22 18:54:12+00:00
mit
4,782
pydantic__pydantic-2220
diff --git a/pydantic/dataclasses.py b/pydantic/dataclasses.py --- a/pydantic/dataclasses.py +++ b/pydantic/dataclasses.py @@ -5,6 +5,7 @@ from .errors import DataclassTypeError from .fields import Required from .main import create_model, validate_model +from .typing import resolve_annotations from .utils import ClassAttribute if TYPE_CHECKING: @@ -128,7 +129,7 @@ def _pydantic_post_init(self: 'Dataclass', *initvars: Any) -> None: _cls.__name__, (_cls,), { - '__annotations__': _cls.__annotations__, + '__annotations__': resolve_annotations(_cls.__annotations__, _cls.__module__), '__post_init__': _pydantic_post_init, # attrs for pickle to find this class '__module__': __name__,
pydantic/pydantic
13a5c7d676167b415080de5e6e6a74bea095b239
Hello @laevilgenius I can't reproduce with your example. See https://repl.it/@EricJ1/pydantic-issue-1668. Could you please give us more information on how to reproduce the bug please? @PrettyWood it fails only when `from __future__ import annotations` is present: https://repl.it/repls/WaterySlimDehardwarization. I can duplicate this bug in a single file ```py from __future__ import annotations from dataclasses import dataclass from typing import Literal from pydantic import BaseModel @dataclass class Base: literal: Literal[1, 2] class What(BaseModel): base: Base What(base=Base(literal=1)) ``` I guess this is using stdlib dataclasses though Hello guys Sorry I forgot to come back on this issue. So yes the issue is related to [this](https://docs.python.org/3/library/typing.html#typing.TYPE_CHECKING) > If from __future__ import annotations is used in Python 3.7 or later, annotations are not evaluated at function definition time. Instead, they are stored as strings in __annotations__, This makes it unnecessary to use quotes around the annotation. (see PEP 563). So it's not really a bug but more a feature to support new behaviour of annotations. And I reckon we'll probably need to dig into it quite soon!
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 @@ -4,6 +4,7 @@ import pytest from pydantic import BaseModel, ConfigError, ValidationError +from pydantic.typing import Literal skip_pre_37 = pytest.mark.skipif(sys.version_info < (3, 7), reason='testing >= 3.7 behaviour only') @@ -480,6 +481,32 @@ def module(): assert instance.sub.dict() == {'foo': 'bar'} +@skip_pre_37 [email protected](not Literal, reason='typing_extensions not installed') +def test_resolve_forward_ref_dataclass(create_module): + module = create_module( + # language=Python + """ +from __future__ import annotations + +from dataclasses import dataclass + +from pydantic import BaseModel +from pydantic.typing import Literal + +@dataclass +class Base: + literal: Literal[1, 2] + +class What(BaseModel): + base: Base + """ + ) + + m = module.What(base=module.Base(literal=1)) + assert m.base.literal == 1 + + def test_nested_forward_ref(): class NestedTuple(BaseModel): x: Tuple[int, Optional['NestedTuple']] # noqa: F821
Inherited dataclasses don't resolve forward refs # Bug ``` pydantic version: 1.5.1 python version: 3.8.2 ``` a.py: ```py from __future__ import annotations from uuid import UUID from pydantic.dataclasses import dataclass @dataclass class A: uuid: UUID # workaround # def __post_init__(self): # self.__pydantic_model__.update_forward_refs(**globals()) ``` b.py: ```py from __future__ import annotations from uuid import uuid4 from pydantic.dataclasses import dataclass from a import A @dataclass class B(A): pass B(uuid=uuid4()) ``` `B(uuid=uuid4())` throws `field "uuid" not yet prepared so type is still a ForwardRef, you might need to call B.update_forward_refs()`.
0.0
13a5c7d676167b415080de5e6e6a74bea095b239
[ "tests/test_forward_ref.py::test_resolve_forward_ref_dataclass" ]
[ "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_nested_forward_ref" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2020-12-24 10:57:30+00:00
mit
4,783
pydantic__pydantic-2221
diff --git a/pydantic/fields.py b/pydantic/fields.py --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -25,7 +25,7 @@ from . import errors as errors_ from .class_validators import Validator, make_generic_validator, prep_validators from .error_wrappers import ErrorWrapper -from .errors import NoneIsNotAllowedError +from .errors import ConfigError, NoneIsNotAllowedError from .types import Json, JsonWrapper from .typing import ( NONE_TYPES, @@ -565,6 +565,13 @@ def validate( self, v: Any, values: Dict[str, Any], *, loc: 'LocStr', cls: Optional['ModelOrDc'] = None ) -> 'ValidateReturn': + if self.type_.__class__ is ForwardRef: + 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().' + ) + errors: Optional['ErrorList'] if self.pre_validators: v, errors = self._apply_validators(v, values, loc, cls, self.pre_validators) diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -34,15 +34,7 @@ from .parse import Protocol, load_file, load_str_bytes from .schema import default_ref_template, model_schema from .types import PyObject, StrBytes -from .typing import ( - AnyCallable, - ForwardRef, - get_args, - get_origin, - is_classvar, - resolve_annotations, - update_field_forward_refs, -) +from .typing import AnyCallable, get_args, get_origin, is_classvar, resolve_annotations, update_field_forward_refs from .utils import ( ROOT_KEY, ClassAttribute, @@ -968,12 +960,6 @@ def validate_model( # noqa: C901 (ignore complexity) return {}, set(), ValidationError([ErrorWrapper(exc, loc=ROOT_KEY)], cls_) for name, field in model.__fields__.items(): - if field.type_.__class__ == ForwardRef: - raise ConfigError( - f'field "{field.name}" not yet prepared so type is still a ForwardRef, ' - f'you might need to call {cls_.__name__}.update_forward_refs().' - ) - value = input_data.get(field.alias, _missing) using_name = False if value is _missing and config.allow_population_by_field_name and field.alt_alias:
pydantic/pydantic
8d7e0b86f395cfacf98e2df7b5edc72a1a82e5f7
yes, very likely related to `Optional[]`. What happens if you used `List['NestedTuple']`? Looks like it fails in the same way. This test passes: ```python from typing import List, Tuple from pydantic import BaseModel def test_parse_nested_tuple(): class NestedTuple(BaseModel): x: Tuple[int, List["NestedTuple"]] obj = NestedTuple.parse_obj({'x': ('1', [{'x': ('2', [{'x': ('3', [])}])}])}) assert obj.dict() == {'x': (1, [{'x': ('2', [{'x': ('3', [])}])}])} # Note above: the 2 and 3 did not get parsed into ints !! NestedTuple.update_forward_refs() obj = NestedTuple.parse_obj({'x': ('1', [{'x': ('2', [{'x': ('3', [])}])}])}) assert obj.dict() == {'x': (1, [{'x': (2, [{'x': (3, [])}])}])} ``` Looks like a problem of checking `ForwardRef`. `ForwardRef` is now checked only in `validate_model` but not in `ModelField.validate`, so an error is raised only when `ModelField.type_` is calculated `ForwardRef`. But this doesn't happen to `Tuple`. Which means the following test passes ``` class NestedTuple(BaseModel): x: Tuple["NestedTuple"] obj = NestedTuple.parse_obj({'x': (AnyObject, )}) assert obj.x[0] is AnyObject ``` Maybe we can move the checking into `ModelField` to solve this?
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 @@ -1,8 +1,9 @@ import sys +from typing import Optional, Tuple import pytest -from pydantic import ConfigError, ValidationError +from pydantic import BaseModel, ConfigError, ValidationError skip_pre_37 = pytest.mark.skipif(sys.version_info < (3, 7), reason='testing >= 3.7 behaviour only') @@ -477,3 +478,19 @@ def module(): Main = pydantic.create_model('Main', sub=('Sub', ...), __module__=__name__) instance = Main(sub={}) assert instance.sub.dict() == {'foo': 'bar'} + + +def test_nested_forward_ref(): + class NestedTuple(BaseModel): + x: Tuple[int, Optional['NestedTuple']] # noqa: F821 + + with pytest.raises(ConfigError) as exc_info: + NestedTuple.parse_obj({'x': ('1', {'x': ('2', {'x': ('3', None)})})}) + assert str(exc_info.value) == ( + 'field "x_1" not yet prepared so type is still a ForwardRef, ' + 'you might need to call NestedTuple.update_forward_refs().' + ) + + 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)})})}
Some recursive models do not require `update_forward_refs` and silently behave incorrectly # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.4 pydantic compiled: False install path: /Users/dmontague/Programming/oss/pydantic/pydantic python version: 3.7.4 (default, Oct 17 2019, 23:32:33) [Clang 11.0.0 (clang-1100.0.33.8)] platform: Darwin-19.0.0-x86_64-i386-64bit optional deps. installed: ['typing-extensions', 'email-validator', 'devtools'] ``` This test passes on master, but it should not: ```py from typing import Optional, Tuple from pydantic import BaseModel def test_parse_nested_tuple(): class NestedTuple(BaseModel): x: Tuple[int, Optional["NestedTuple"]] obj = NestedTuple.parse_obj({'x': ('1', {'x': ('2', {'x': ('3', None)})})}) assert obj.dict() == {'x': (1, {'x': ('2', {'x': ('3', None)})})} # Note above: the 2 and 3 did not get parsed into ints !! 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)})})} ``` Presumably we should either get an error at some point prior to the `NestedRootTuple.update_forward_refs()` call, or the two calls to `obj.dict()` should generate the same output. I'm guessing this is related to the field being `Optional`, but I'm not sure. I discovered it while working on #1200 .
0.0
8d7e0b86f395cfacf98e2df7b5edc72a1a82e5f7
[ "tests/test_forward_ref.py::test_nested_forward_ref" ]
[ "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" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-12-24 14:17:51+00:00
mit
4,784
pydantic__pydantic-2226
diff --git a/pydantic/schema.py b/pydantic/schema.py --- a/pydantic/schema.py +++ b/pydantic/schema.py @@ -781,7 +781,7 @@ def field_singleton_schema( # noqa: C901 (ignore complexity) f_schema['const'] = literal_value if lenient_issubclass(field_type, Enum): - enum_name = normalize_name(field_type.__name__) + enum_name = model_name_map[field_type] f_schema, schema_overrides = get_field_info_schema(field) f_schema.update(get_schema_ref(enum_name, ref_prefix, ref_template, schema_overrides)) definitions[enum_name] = enum_process_schema(field_type)
pydantic/pydantic
3496a473c73156fb02edf7dd8a1b1617a76a1b60
diff --git a/tests/test_schema.py b/tests/test_schema.py --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -2097,3 +2097,55 @@ class Model(BaseModel): 'properties': {'a': {'title': 'A', 'type': 'string'}}, 'required': ['a'], } + + +def test_multiple_enums_with_same_name(create_module): + module_1 = create_module( + # language=Python + """ +from enum import Enum + +from pydantic import BaseModel + + +class MyEnum(str, Enum): + a = 'a' + b = 'b' + c = 'c' + + +class MyModel(BaseModel): + my_enum_1: MyEnum + """ + ) + + module_2 = create_module( + # language=Python + """ +from enum import Enum + +from pydantic import BaseModel + + +class MyEnum(str, Enum): + d = 'd' + e = 'e' + f = 'f' + + +class MyModel(BaseModel): + my_enum_2: MyEnum + """ + ) + + class Model(BaseModel): + my_model_1: module_1.MyModel + my_model_2: module_2.MyModel + + assert len(Model.schema()['definitions']) == 4 + assert set(Model.schema()['definitions']) == { + f'{module_1.__name__}__MyEnum', + f'{module_1.__name__}__MyModel', + f'{module_2.__name__}__MyEnum', + f'{module_2.__name__}__MyModel', + }
Regression in OpenAPI schema generation with multiple Enums having the same name but different enum members # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.6.1 pydantic compiled: True install path: /Users/philipp/Downloads/env/lib/python3.7/site-packages/pydantic python version: 3.7.6 (default, Dec 30 2019, 19:38:28) [Clang 11.0.0 (clang-1100.0.33.16)] platform: Darwin-19.3.0-x86_64-i386-64bit optional deps. installed: [] ``` At first, thank you all for this incredible piece of software! As of #1432 enums are included as separate models and and are referenced in all locations. In the case of multiple enums with the same name but different enum members, located in different modules, only one of these enums is included in the OpenAPI schema. File `other.py`: ```py from enum import Enum from pydantic import BaseModel class SomeEnum(str, Enum): d = "d" e = "e" f = "f" class SomeOtherModel(BaseModel): some_enum: SomeEnum ``` File `main.py`: ```py from enum import Enum from pydantic import BaseModel from other import SomeOtherModel class SomeEnum(str, Enum): a = "a" b = "b" c = "c" class MainModel(BaseModel): some_enum: SomeEnum some_other_model: SomeOtherModel if __name__ == "__main__": print(MainModel.schema_json()) ``` Executing `main.py` produces the following schema: ``` { "title": "MainModel", "type": "object", "properties": { "some_enum": { "$ref": "#/definitions/SomeEnum" }, "some_other_model": { "$ref": "#/definitions/SomeOtherModel" } }, "required": [ "some_enum", "some_other_model" ], "definitions": { "SomeEnum": { "title": "SomeEnum", "description": "An enumeration.", "enum": [ "d", "e", "f" ], "type": "string" }, "SomeOtherModel": { "title": "SomeOtherModel", "type": "object", "properties": { "some_enum": { "$ref": "#/definitions/SomeEnum" } }, "required": [ "some_enum" ] } } } ``` Only the Enum from `other.py` is included and the schema now contains invalid supported enum values for `MainModel.some_enum`. Before #1432 this works as expected because the enum values are included as-is. Ideally `pydantic` should handle this case by prefixing different enums with the same name in the OpenAPI schema. I've applied a workaround to my application code by changing the name of conflicting enums but I only detected this new behaviour by having a CI Pipeline step that checks for breaking OpenAPI changes.
0.0
3496a473c73156fb02edf7dd8a1b1617a76a1b60
[ "tests/test_schema.py::test_multiple_enums_with_same_name" ]
[ "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_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[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_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-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[kwargs8-type_8]", "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_unenforced_constraints_schema[kwargs11-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_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" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2020-12-29 14:17:06+00:00
mit
4,785
pydantic__pydantic-2228
diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -259,6 +259,11 @@ def __new__(mcs, name, bases, namespace, **kwargs): # noqa C901 prepare_config(config, name) + untouched_types = ANNOTATED_FIELD_UNTOUCHED_TYPES + + def is_untouched(v: Any) -> bool: + return isinstance(v, untouched_types) or v.__class__.__name__ == 'cython_function_or_method' + if (namespace.get('__module__'), namespace.get('__qualname__')) != ('pydantic.main', 'BaseModel'): annotations = resolve_annotations(namespace.get('__annotations__', {}), namespace.get('__module__', None)) # annotation only fields need to come first in fields @@ -270,7 +275,7 @@ def __new__(mcs, name, bases, namespace, **kwargs): # noqa C901 value = namespace.get(ann_name, Undefined) allowed_types = get_args(ann_type) if get_origin(ann_type) is Union else (ann_type,) if ( - isinstance(value, ANNOTATED_FIELD_UNTOUCHED_TYPES) + is_untouched(value) and ann_type != PyObject and not any( lenient_issubclass(get_origin(allowed_type), Type) for allowed_type in allowed_types @@ -289,7 +294,7 @@ def __new__(mcs, name, bases, namespace, **kwargs): # noqa C901 untouched_types = UNTOUCHED_TYPES + config.keep_untouched for var_name, value in namespace.items(): - can_be_changed = var_name not in class_vars and not isinstance(value, untouched_types) + can_be_changed = var_name not in class_vars and not is_untouched(value) if isinstance(value, ModelPrivateAttr): if not is_valid_private_name(var_name): raise NameError(
pydantic/pydantic
78934db63169bf6bc661b2c63f61f996bea5deff
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 @@ -20,6 +20,11 @@ ) from pydantic.fields import Field, Schema +try: + import cython +except ImportError: + cython = None + def test_str_bytes(): class Model(BaseModel): @@ -1745,3 +1750,26 @@ class Child(Parent): pass assert Child(foo=['a', 'b']).foo == ['a-1', 'b-1'] + + [email protected](cython is None, reason='cython not installed') +def test_cython_function_untouched(): + Model = cython.inline( + # language=Python + """ +from pydantic import BaseModel + +class Model(BaseModel): + a = 0.0 + b = 10 + + def get_double_a(self) -> float: + return self.a + self.b + +return Model +""" + ) + model = Model(a=10.2) + assert model.a == 10.2 + assert model.b == 10 + return model.get_double_a() == 20.2
Impl. of BaseModel with method crashes when Cythonized # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.6.1 pydantic compiled: True install path: /Users/mordaren/Source/pydantic/pydantic python version: 3.7.7 (default, Mar 10 2020, 15:43:27) [Clang 10.0.0 (clang-1000.11.45.5)] platform: Darwin-17.2.0-x86_64-i386-64bit optional deps. installed: ['typing-extensions', 'email-validator', 'devtools'] ``` Here's a minimal example: main.py: ```py from pydantic import BaseModel class MyModel(BaseModel): x: float = 123 def x2(self): return self.x**2 def main(): model = MyModel(x=10) print("x^2 = ", model.x2()) ``` setup.py: ``` from setuptools import setup from Cython.Build import cythonize setup( name='testapp', ext_modules=cythonize("main.py"), ) ``` Cythonize the script using the following command (mac OS): ``` python setup.py build_ext --inplace``` When trying to import main, the following crash occurs (ensure that you're importing the actual Cythonized file): ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> File "main.py", line 5, in init main class MyModel(BaseModel): File "pydantic/main.py", line 285, in pydantic.main.ModelMetaclass.__new__ File "pydantic/fields.py", line 309, in pydantic.fields.ModelField.infer File "pydantic/fields.py", line 271, in pydantic.fields.ModelField.__init__ File "pydantic/fields.py", line 351, in pydantic.fields.ModelField.prepare File "pydantic/fields.py", line 529, in pydantic.fields.ModelField.populate_validators File "pydantic/validators.py", line 593, in find_validators RuntimeError: no validator found for <class 'cython_function_or_method'>, see `arbitrary_types_allowed` in Config ```
0.0
78934db63169bf6bc661b2c63f61f996bea5deff
[ "tests/test_edge_cases.py::test_cython_function_untouched" ]
[ "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_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_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_fields_deprecated", "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_side_effect", "tests/test_edge_cases.py::test_default_factory_validator_child" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2020-12-30 18:17:42+00:00
mit
4,786
pydantic__pydantic-2238
diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -509,12 +509,18 @@ def json( return self.__config__.json_dumps(data, default=encoder, **dumps_kwargs) @classmethod - def parse_obj(cls: Type['Model'], obj: Any) -> 'Model': + def _enforce_dict_if_root(cls, obj: Any) -> Any: 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): + return {ROOT_KEY: obj} + else: + return obj + + @classmethod + def parse_obj(cls: Type['Model'], obj: Any) -> 'Model': + obj = cls._enforce_dict_if_root(obj) + if not isinstance(obj, dict): try: obj = dict(obj) except (TypeError, ValueError) as e: @@ -662,14 +668,13 @@ def __get_validators__(cls) -> 'CallableGenerator': @classmethod def validate(cls: Type['Model'], value: Any) -> 'Model': + value = cls._enforce_dict_if_root(value) if isinstance(value, dict): return cls(**value) elif isinstance(value, cls): return value.copy() elif cls.__config__.orm_mode: return cls.from_orm(value) - elif cls.__custom_root_type__: - return cls.parse_obj(value) else: try: value_as_dict = dict(value)
pydantic/pydantic
13a5c7d676167b415080de5e6e6a74bea095b239
Hello @sohama4 You're right `__root__` is only supported [at parent level](https://github.com/samuelcolvin/pydantic/blob/master/pydantic/main.py#L505) and is not handled properly for nested models. To support this we could add this logic directly - in `BaseModel.validate` but it wouldn't work with `construct` for example - in `BaseModel.__init__` but it would cost a bit of running time I run the benchmark and it doesn't seem to have any effect on the performance so the [latter solution](https://github.com/PrettyWood/pydantic/commit/ba6d3b4d0cfe5227223c12ae2336fb1f2566bcf2) could be a good solution. @samuelcolvin WDYT? If you want to try it out already @sohama4 I would go with something like this ```python import json from typing import Any, Dict, List from pydantic import BaseModel as PydanticBaseModel from pydantic.utils import ROOT_KEY class BaseModel(PydanticBaseModel): def __init__(__pydantic_self__, **data: Any) -> None: if __pydantic_self__.__custom_root_type__ and data.keys() != {ROOT_KEY}: data = {ROOT_KEY: data} super().__init__(**data) ... ``` Hope it helps! @PrettyWood - thank you for the response, I will try it out soon, and will close this out ASAP. I think the docs must mention this behavior, so I left a comment on the PR you linked. Similar issue with respect to `.from_orm()`. Solution advised by @PrettyWood doesn't work for this case since `validate_model` is called before constructor. Worked this around like this: ```python class BaseCustomRootModel(BaseModel): @classmethod def from_orm(cls, obj: Any): if cls.__custom_root_type__: class Wrapper: __slots__ = ('__root__',) def __init__(self, obj): self.__root__ = obj return super().from_orm(Wrapper(obj)) return super().from_orm(obj) ``` ``` pydantic version: 1.7.3 pydantic compiled: False install path: /home/user/.local/share/virtualenvs/project-hash/lib/python3.6/site-packages/pydantic python version: 3.6.8 (default, Feb 11 2019, 08:59:55) [GCC 8.2.1 20181127] platform: Linux-5.9.11-zen2-1-zen-x86_64-with-arch optional deps. installed: ['email-validator'] ``` @scorpp What about [this solution](https://github.com/samuelcolvin/pydantic/issues/1193#issuecomment-753652412)? It should work with everything above + orm if I'm not mistaken So something like this ```python from pydantic import BaseModel as PydanticBaseModel class BaseModel(PydanticBaseModel): @classmethod def validate(cls, value): if cls.__custom_root_type__: return cls.parse_obj(value) return super().validate(value) ``` @PrettyWood no, this doesn't work. in `BaseModel.from_orm` in `main.py:570` `m = cls.__new__(cls)` returns a model with no `__root__` set. and then the call to `validate_model` on next line fails. Also your option with overriding `validate` turn execution to different path - `parse_obj` instead of `from_orm`. Meaning that nested ORM models won't work anyway, since `parse_obj` will not accept regular objects. I think that my solution (or alike) should be incorporated into `from_orm` of the `BaseModel`. Similarly to `parse_obj`. Ah yes sorry I wrote that on my phone yesterday night and should have paid more attention on the `from_orm` implementation. I guess the fix is trivial if you can directly change the code like https://github.com/samuelcolvin/pydantic/pull/2237 WDYT @scorpp ?
diff --git a/tests/test_main.py b/tests/test_main.py --- a/tests/test_main.py +++ b/tests/test_main.py @@ -1120,6 +1120,60 @@ class MyModel(BaseModel): ] +def test_parse_obj_nested_root(): + class Pokemon(BaseModel): + name: str + level: int + + class Pokemons(BaseModel): + __root__: List[Pokemon] + + class Player(BaseModel): + rank: int + pokemons: Pokemons + + class Players(BaseModel): + __root__: Dict[str, Player] + + class Tournament(BaseModel): + players: Players + city: str + + payload = { + 'players': { + 'Jane': { + 'rank': 1, + 'pokemons': [ + { + 'name': 'Pikachu', + 'level': 100, + }, + { + 'name': 'Bulbasaur', + 'level': 13, + }, + ], + }, + 'Tarzan': { + 'rank': 2, + 'pokemons': [ + { + 'name': 'Jigglypuff', + 'level': 7, + }, + ], + }, + }, + 'city': 'Qwerty', + } + + tournament = Tournament.parse_obj(payload) + assert tournament.city == 'Qwerty' + assert len(tournament.players.__root__) == 2 + assert len(tournament.players.__root__['Jane'].pokemons.__root__) == 2 + assert tournament.players.__root__['Jane'].pokemons.__root__[0].name == 'Pikachu' + + def test_untouched_types(): from pydantic import BaseModel
Cannot parse nested object with custom root 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 couldn't find an answer * [x] After submitting this, I commit to one of: * Look through open issues and helped at least one other person * Hit the "watch" button on this repo to receive notifications and I commit to help at least 2 people that ask questions in the future * Implement a Pull Request for a confirmed bug <!-- Sorry to sound so draconian, but every second saved replying to issues is time spend improving pydantic :-) --> # Question 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.7.2 pydantic compiled: True install path: <path>/venv/lib/python3.7/site-packages/pydantic python version: 3.7.7 (default, Nov 3 2020, 00:02:20) [Clang 12.0.0 (clang-1200.0.32.21)] platform: Darwin-19.6.0-x86_64-i386-64bit optional deps. installed: [] ``` Hello, thank you for the library - I have used it in production across multiple applications now! I am trying to parse a JSON with a nested JSON needing a custom root type of `Dict` - but get an error as shown in the snippet. I tried to check thru old bugs and the fixes for them like https://github.com/samuelcolvin/pydantic/pull/1253 and https://github.com/samuelcolvin/pydantic/issues/1773 and verified that all fixes are already in the version of the code I have pulled, but still don't see the behavior fixed. Can someone help point what I'm doing wrong? Thanks! ```py import pydantic import json class Player(BaseModel): player: str number: int pos: str class Lineup(BaseModel): coach: str startXI: List[Player] substitutes: List[Player] class Lineups(BaseModel): __root__: Dict[str, Lineup] class LineupsResponse(BaseModel): results: int lineUps: Lineups class LineupsApiResponse(BaseModel): api: LineupsResponse if __name__ == "__main__": text = '{"api":{"results":2,"lineUps":{"ManchesterCity":{"coach":"Guardiola","coach_id":4,"formation":"4-3-3","startXI":[{"team_id":50,"player_id":617,"player":"Ederson","number":31,"pos":"G"}],"substitutes":[{"team_id":50,"player_id":50828,"player":"ZackSteffen","number":13,"pos":"G"}]},"Liverpool":{"coach":"J.Klopp","coach_id":1,"formation":"4-2-2-2","startXI":[{"team_id":40,"player_id":280,"player":"Alisson","number":1,"pos":"G"}],"substitutes":[{"team_id":40,"player_id":18812,"player":"Adrián","number":13,"pos":"G"},{"team_id":40,"player_id":127472,"player":"NathanielPhillips","number":47,"pos":"D"},{"team_id":40,"player_id":293,"player":"CurtisJones","number":17,"pos":"M"}]}}}}' try: response: LineupsApiResponse = LineupsApiResponse.parse_obj(json.loads(text)) except Exception as e: print(e) try: response2: LineupsApiResponse = LineupsApiResponse.parse_raw(text) except Exception as e: print(e) ``` Output: ``` 1 validation error for LineupsApiResponse api -> lineUps -> __root__ field required (type=value_error.missing) 1 validation error for LineupsApiResponse api -> lineUps -> __root__ field required (type=value_error.missing) ```
0.0
13a5c7d676167b415080de5e6e6a74bea095b239
[ "tests/test_main.py::test_parse_obj_nested_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_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_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_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_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_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", "tests/test_main.py::test_model_export_dict_exclusion", "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" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2021-01-05 11:46:24+00:00
mit
4,787
pydantic__pydantic-2252
diff --git a/pydantic/decorator.py b/pydantic/decorator.py --- a/pydantic/decorator.py +++ b/pydantic/decorator.py @@ -161,8 +161,9 @@ def build_values(self, args: Tuple[Any, ...], kwargs: Dict[str, Any]) -> Dict[st var_kwargs = {} wrong_positional_args = [] + non_var_fields = set(self.model.__fields__) - {self.v_args_name, self.v_kwargs_name} for k, v in kwargs.items(): - if k in self.model.__fields__: + if k in non_var_fields: if k in self.positional_only_args: wrong_positional_args.append(k) values[k] = v @@ -177,9 +178,7 @@ def build_values(self, args: Tuple[Any, ...], kwargs: Dict[str, Any]) -> Dict[st def execute(self, m: BaseModel) -> Any: d = {k: v for k, v in m._iter() if k in m.__fields_set__} - kwargs = d.pop(self.v_kwargs_name, None) - if kwargs: - d.update(kwargs) + var_kwargs = d.pop(self.v_kwargs_name, {}) if self.v_args_name in d: args_: List[Any] = [] @@ -193,7 +192,7 @@ def execute(self, m: BaseModel) -> Any: in_kwargs = True else: args_.append(value) - return self.raw_function(*args_, **kwargs) + return self.raw_function(*args_, **kwargs, **var_kwargs) elif self.positional_only_args: args_ = [] kwargs = {} @@ -202,9 +201,9 @@ def execute(self, m: BaseModel) -> Any: args_.append(value) else: kwargs[name] = value - return self.raw_function(*args_, **kwargs) + return self.raw_function(*args_, **kwargs, **var_kwargs) else: - return self.raw_function(**d) + return self.raw_function(**d, **var_kwargs) def create_model(self, fields: Dict[str, Any], takes_args: bool, takes_kwargs: bool, config: 'ConfigType') -> None: pos_args = len(self.arg_mapping)
pydantic/pydantic
13a5c7d676167b415080de5e6e6a74bea095b239
diff --git a/tests/test_decorator.py b/tests/test_decorator.py --- a/tests/test_decorator.py +++ b/tests/test_decorator.py @@ -110,15 +110,22 @@ def foo(a, b, c='x', *, d='y'): assert foo(1, {'x': 2}, c='3', d='4') == "1, {'x': 2}, 3, 4" -def test_var_args_kwargs(): - @validate_arguments [email protected]('validated', (True, False)) +def test_var_args_kwargs(validated): def foo(a, b, *args, d=3, **kwargs): return f'a={a!r}, b={b!r}, args={args!r}, d={d!r}, kwargs={kwargs!r}' + if validated: + foo = validate_arguments(foo) + assert foo(1, 2) == 'a=1, b=2, args=(), d=3, kwargs={}' assert foo(1, 2, 3, d=4) == 'a=1, b=2, args=(3,), d=4, kwargs={}' assert foo(*[1, 2, 3], d=4) == 'a=1, b=2, args=(3,), d=4, kwargs={}' + assert foo(1, 2, args=(10, 11)) == "a=1, b=2, args=(), d=3, kwargs={'args': (10, 11)}" + assert foo(1, 2, 3, args=(10, 11)) == "a=1, b=2, args=(3,), d=3, kwargs={'args': (10, 11)}" assert foo(1, 2, 3, e=10) == "a=1, b=2, args=(3,), d=3, kwargs={'e': 10}" + assert foo(1, 2, kwargs=4) == "a=1, b=2, args=(), d=3, kwargs={'kwargs': 4}" + assert foo(1, 2, kwargs=4, e=5) == "a=1, b=2, args=(), d=3, kwargs={'kwargs': 4, 'e': 5}" @skip_pre_38
`validate_arguments` does not assign `**kwargs` correctly ### 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.7.3 pydantic compiled: False install path: /home/anthony/experiments/pydantic/pydantic python version: 3.8.5 (default, Aug 23 2020, 18:40:40) [GCC 10.1.0] platform: Linux-5.10.2-2-MANJARO-x86_64-with-glibc2.29 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 validate_arguments @validate_arguments def foo(**kwargs): print(f"{kwargs=}") def bar(**kwargs): print(f"{kwargs=}") >>> foo(kwargs=1, b=2) kwargs={'b': 2} >>> bar(kwargs=1, b=2) kwargs={'kwargs': 1, 'b': 2} ``` Kwargs doesn't get assigned as per native python implementation. It looks like the field gets overwritten, as we're checking all input kwargs against all fields, including the special var_kwarg field. https://github.com/samuelcolvin/pydantic/blob/8bad7bc91105616dfcc23ce1d68fba12f328a2a3/pydantic/decorator.py#L166 Should be as simple as `set(self.model.__fields__) - {self.v_kwargs_name}` to resolve, will prepare a patch now.
0.0
13a5c7d676167b415080de5e6e6a74bea095b239
[ "tests/test_decorator.py::test_var_args_kwargs[True]" ]
[ "tests/test_decorator.py::test_args", "tests/test_decorator.py::test_wrap", "tests/test_decorator.py::test_kwargs", "tests/test_decorator.py::test_untyped", "tests/test_decorator.py::test_var_args_kwargs[False]", "tests/test_decorator.py::test_positional_only", "tests/test_decorator.py::test_args_name", "tests/test_decorator.py::test_v_args", "tests/test_decorator.py::test_async", "tests/test_decorator.py::test_string_annotation", "tests/test_decorator.py::test_item_method", "tests/test_decorator.py::test_class_method", "tests/test_decorator.py::test_config_title", "tests/test_decorator.py::test_config_title_cls", "tests/test_decorator.py::test_config_fields", "tests/test_decorator.py::test_config_arbitrary_types_allowed", "tests/test_decorator.py::test_validate" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-01-10 18:23:40+00:00
mit
4,788
pydantic__pydantic-2262
diff --git a/pydantic/schema.py b/pydantic/schema.py --- a/pydantic/schema.py +++ b/pydantic/schema.py @@ -11,6 +11,7 @@ Callable, Dict, FrozenSet, + Generic, Iterable, List, Optional, @@ -27,6 +28,7 @@ from .fields import ( SHAPE_FROZENSET, + SHAPE_GENERIC, SHAPE_ITERABLE, SHAPE_LIST, SHAPE_MAPPING, @@ -481,7 +483,7 @@ def field_type_schema( sub_schema = sub_schema[0] # type: ignore f_schema = {'type': 'array', 'items': sub_schema} else: - assert field.shape == SHAPE_SINGLETON, field.shape + assert field.shape in {SHAPE_SINGLETON, SHAPE_GENERIC}, field.shape f_schema, f_definitions, f_nested_models = field_singleton_schema( field, by_alias=by_alias, @@ -496,7 +498,11 @@ def field_type_schema( # check field type to avoid repeated calls to the same __modify_schema__ method if field.type_ != field.outer_type_: - modify_schema = getattr(field.outer_type_, '__modify_schema__', None) + if field.shape == SHAPE_GENERIC: + field_type = field.type_ + else: + field_type = field.outer_type_ + modify_schema = getattr(field_type, '__modify_schema__', None) if modify_schema: modify_schema(f_schema) return f_schema, definitions, nested_models @@ -828,6 +834,11 @@ def field_singleton_schema( # noqa: C901 (ignore complexity) schema_ref = get_schema_ref(model_name, ref_prefix, ref_template, schema_overrides) return schema_ref, definitions, nested_models + # For generics with no args + args = get_args(field_type) + if args is not None and not args and Generic in field_type.__bases__: + return f_schema, definitions, nested_models + raise ValueError(f'Value not declarable with JSON Schema, field: {field}') diff --git a/pydantic/typing.py b/pydantic/typing.py --- a/pydantic/typing.py +++ b/pydantic/typing.py @@ -92,7 +92,7 @@ def evaluate_forwardref(type_: ForwardRef, globalns: Any, localns: Any) -> Any: if sys.version_info < (3, 7): def get_args(t: Type[Any]) -> Tuple[Any, ...]: - """Simplest get_args compatability layer possible. + """Simplest get_args compatibility layer possible. The Python 3.6 typing module does not have `_GenericAlias` so this won't work for everything. In particular this will not @@ -106,7 +106,7 @@ def get_args(t: Type[Any]) -> Tuple[Any, ...]: from typing import _GenericAlias def get_args(t: Type[Any]) -> Tuple[Any, ...]: - """Compatability version of get_args for python 3.7. + """Compatibility version of get_args for python 3.7. Mostly compatible with the python 3.8 `typing` module version and able to handle almost all use cases.
pydantic/pydantic
13a5c7d676167b415080de5e6e6a74bea095b239
Looks to me like generating schema for generic fields just hasn't been implemented yet. Happy to review and accept a PR to implement this.
diff --git a/tests/test_schema.py b/tests/test_schema.py --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -7,7 +7,21 @@ from enum import Enum, IntEnum from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network from pathlib import Path -from typing import Any, Callable, Dict, FrozenSet, Iterable, List, NewType, Optional, Set, Tuple, Union +from typing import ( + Any, + Callable, + Dict, + FrozenSet, + Generic, + Iterable, + List, + NewType, + Optional, + Set, + Tuple, + TypeVar, + Union, +) from uuid import UUID import pytest @@ -2149,3 +2163,58 @@ class Model(BaseModel): f'{module_2.__name__}__MyEnum', f'{module_2.__name__}__MyModel', } + + [email protected]( + sys.version_info < (3, 7), reason='schema generation for generic fields is not available in python < 3.7' +) +def test_schema_for_generic_field(): + T = TypeVar('T') + + class GenModel(Generic[T]): + def __init__(self, data: Any): + self.data = data + + @classmethod + def __get_validators__(cls): + yield cls.validate + + @classmethod + def validate(cls, v: Any): + return v + + class Model(BaseModel): + data: GenModel[str] + data1: GenModel + + assert Model.schema() == { + 'title': 'Model', + 'type': 'object', + 'properties': { + 'data': {'title': 'Data', 'type': 'string'}, + 'data1': { + 'title': 'Data1', + }, + }, + 'required': ['data', 'data1'], + } + + class GenModelModified(GenModel, Generic[T]): + @classmethod + def __modify_schema__(cls, field_schema): + field_schema.pop('type', None) + field_schema.update(anyOf=[{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]) + + class ModelModified(BaseModel): + data: GenModelModified[str] + data1: GenModelModified + + assert ModelModified.schema() == { + 'title': 'ModelModified', + 'type': 'object', + 'properties': { + 'data': {'title': 'Data', 'anyOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}, + 'data1': {'title': 'Data1', 'anyOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}, + }, + 'required': ['data', 'data1'], + }
BaseModel.schema() fails when using generic types # Bug ## Version Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.5.1 pydantic compiled: True install path: C:\Users\adrian\miniconda3\envs\sangl-butler\Lib\site-packages\pydantic python version: 3.8.1 (default, Mar 2 2020, 13:06:26) [MSC v.1916 64 bit (AMD64)] platform: Windows-10-10.0.18362-SP0 optional deps. installed: ['typing-extensions', 'email-validator'] ``` ## Description Hi there! I want to write a generic type, that behaves like the type it extends, but injects fields into the model with ``__modify_schema__``. So my approach was to use a generic class to use it like that: ```py from pydantic import BaseModel class MyModel(BaseModel): my_field: FieldThatModifiesModel[str] = "Default value" ```` The field should completely behave like the type var. However, when I use a generic type in my model, I can't retrieve the model anymore. See the code below (taken from the docs): ## Example ```py from pydantic import BaseModel, ValidationError from pydantic.fields import ModelField from typing import TypeVar, Generic AgedType = TypeVar('AgedType') QualityType = TypeVar('QualityType') # This is not a pydantic model, it's an arbitrary generic class class TastingModel(Generic[AgedType, QualityType]): def __init__(self, name: str, aged: AgedType, quality: QualityType): self.name = name self.aged = aged self.quality = quality @classmethod def __get_validators__(cls): yield cls.validate @classmethod # You don't need to add the "ModelField", but it will help your # editor give you completion and catch errors def validate(cls, v, field: ModelField): if not isinstance(v, cls): # The value is not even a TastingModel raise TypeError('Invalid value') if not field.sub_fields: # Generic parameters were not provided so we don't try to validate # them and just return the value as is return v aged_f = field.sub_fields[0] quality_f = field.sub_fields[1] errors = [] # Here we don't need the validated value, but we want the errors valid_value, error = aged_f.validate(v.aged, {}, loc='aged') if error: errors.append(error) # Here we don't need the validated value, but we want the errors valid_value, error = quality_f.validate(v.quality, {}, loc='quality') if error: errors.append(error) if errors: raise ValidationError(errors, cls) # Validation passed without errors, return the same instance received return v class Model(BaseModel): # for wine, "aged" is an int with years, "quality" is a float wine: TastingModel[int, float] # for cheese, "aged" is a bool, "quality" is a str cheese: TastingModel[bool, str] # for thing, "aged" is a Any, "quality" is Any thing: TastingModel print(Model.schema()) """ Traceback (most recent call last): File ".../generic_type.py", line 54, in <module> print(Model.schema()) File "pydantic\main.py", line 556, in pydantic.main.BaseModel.schema File "pydantic\schema.py", line 132, in pydantic.schema.model_schema File "pydantic\schema.py", line 455, in pydantic.schema.model_process_schema File "pydantic\schema.py", line 491, in pydantic.schema.model_type_schema File "pydantic\schema.py", line 185, in pydantic.schema.field_schema File "pydantic\schema.py", line 411, in pydantic.schema.field_type_schema AssertionError: 10 """ ```
0.0
13a5c7d676167b415080de5e6e6a74bea095b239
[ "tests/test_schema.py::test_schema_for_generic_field" ]
[ "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_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[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_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-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[kwargs8-type_8]", "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_unenforced_constraints_schema[kwargs11-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_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_enums_with_same_name" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-01-14 08:20:46+00:00
mit
4,789
pydantic__pydantic-2265
diff --git a/pydantic/env_settings.py b/pydantic/env_settings.py --- a/pydantic/env_settings.py +++ b/pydantic/env_settings.py @@ -197,7 +197,9 @@ def __call__(self, settings: BaseSettings) -> Dict[str, Any]: secrets_path = Path(self.secrets_dir).expanduser() if not secrets_path.exists(): - raise SettingsError(f'directory "{secrets_path}" does not exist') + warnings.warn(f'directory "{secrets_path}" does not exist') + return secrets + if not secrets_path.is_dir(): raise SettingsError(f'secrets_dir must reference a directory, not a {path_type(secrets_path)}')
pydantic/pydantic
2a87f7954a593b5b2756caed6abb76f06eee1271
diff --git a/tests/test_settings.py b/tests/test_settings.py --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -835,12 +835,10 @@ class Config: @pytest.mark.skipif(sys.platform.startswith('win'), reason='windows paths break regex') def test_secrets_missing_location(tmp_path): class Settings(BaseSettings): - foo: str - class Config: secrets_dir = tmp_path / 'does_not_exist' - with pytest.raises(SettingsError, match=f'directory "{tmp_path}/does_not_exist" does not exist'): + with pytest.warns(UserWarning, match=f'directory "{tmp_path}/does_not_exist" does not exist'): Settings()
secrets_dir configuration setting raises an error when the directory doesn't exist ### 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.7.3 pydantic compiled: True install path: ~/.pyenv/versions/3.8.5/envs/fetcher/lib/python3.8/site-packages/pydantic python version: 3.8.5 (default, Sep 4 2020, 14:39:18) [GCC 9.3.0] platform: Linux-5.8.0-7630-generic-x86_64-with-glibc2.29 optional deps. installed: ['typing-extensions', 'devtools'] ``` I have declared a settings model that can read values from the environment, a `.env` file, or from Docker secrets as follows. ```py import pydantic class Settings(BaseSettings): password: SecretStr = Field(..., env="APP_PASSWORD") class Config: """Configure settings values discovery locations.""" env_file = ".env" secrets_dir = "/run/secrets" ``` [As per the documentation](https://pydantic-docs.helpmanual.io/usage/settings/#field-value-priority), checking for a value from a secret is the fourth attempt pydantic makes. However, when I just work in my development environment where the directory `/run/secrets` doesn't exist, instantiating the model raises an error. ``` pydantic.env_settings.SettingsError: directory "/run/secrets" does not exist ``` This is annoying because it happens even though I have the values in a `.env` file. Thus I have to circumvent this by using `Settings(_secrets_dir=".")` which would mean that I need a special case for my dev environment. I think, when values are provided to the instance, or from the environment, or from `.env` first, it shouldn't matter whether the `secrets_dir` exists or not.
0.0
2a87f7954a593b5b2756caed6abb76f06eee1271
[ "tests/test_settings.py::test_secrets_missing_location" ]
[ "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_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_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_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-01-15 11:45:31+00:00
mit
4,790
pydantic__pydantic-2282
diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -584,10 +584,15 @@ def construct(cls: Type['Model'], _fields_set: Optional['SetStr'] = None, **valu """ 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. + Behaves as if `Config.extra = 'allow'` was set since it adds all passed values """ m = cls.__new__(cls) - # default field values - fields_values = {name: field.get_default() for name, field in cls.__fields__.items() if not field.required} + fields_values: Dict[str, Any] = {} + for name, field in cls.__fields__.items(): + if name in values: + fields_values[name] = values[name] + elif not field.required: + fields_values[name] = field.get_default() fields_values.update(values) object_setattr(m, '__dict__', fields_values) if _fields_set is None:
pydantic/pydantic
13a5c7d676167b415080de5e6e6a74bea095b239
diff --git a/tests/test_construction.py b/tests/test_construction.py --- a/tests/test_construction.py +++ b/tests/test_construction.py @@ -35,6 +35,28 @@ def test_construct_fields_set(): assert m.dict() == {'a': 3, 'b': -1} +def test_construct_allow_extra(): + """construct() should allow extra fields""" + + class Foo(BaseModel): + x: int + + assert Foo.construct(x=1, y=2).dict() == {'x': 1, 'y': 2} + + +def test_construct_keep_order(): + class Foo(BaseModel): + a: int + b: int = 42 + c: float + + instance = Foo(a=1, b=321, c=3.14) + instance_construct = Foo.construct(**instance.dict()) + assert instance == instance_construct + assert instance.dict() == instance_construct.dict() + assert instance.json() == instance_construct.json() + + def test_large_any_str(): class Model(BaseModel): a: bytes
BaseModel.construct(): Incorrect field order with default values ### 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.7.3 pydantic compiled: True install path: C:\Users\JonasTK\miniconda3\envs\testenv\Lib\site-packages\pydantic python version: 3.8.5 (default, Sep 3 2020, 21:29:08) [MSC v.1916 64 bit (AMD64)] platform: Windows-10-10.0.19041-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: --> I know this is (sort of) showcased in the docs, but I still think it is a problem that .construct() does not give correct field order when there are fields with default values. Most of the time this is not a problem: comparing instances and .dict() outputs do not depend on the field order. But for JSON export, it does matter. Shouldn't the JSON export from an instance generated via .construct() with pre-validated input be identical to the JSON export of a properly validated instance? ```py from pydantic import BaseModel class Foo(BaseModel): a: int b: int = 42 c: float instance = Foo(a=1, c=3.14) # Correct field order instance_construct = Foo.construct(**instance.dict()) # Incorrect field order print(instance) # Output: a=1 b=42 c=3.14 print(instance_construct) # Output: b=42 a=1 c=3.14 print(instance.json()) # Output: {"a": 1, "b": 42, "c": 3.14} print(instance_construct.json()) # Output: {"b": 42, "a": 1, "c": 3.14} assert instance == instance_construct # No Error assert instance.dict() == instance_construct.dict() # No Error assert instance.json() == instance_construct.json() # AssertionError ```
0.0
13a5c7d676167b415080de5e6e6a74bea095b239
[ "tests/test_construction.py::test_construct_keep_order" ]
[ "tests/test_construction.py::test_simple_construct", "tests/test_construction.py::test_construct_misuse", "tests/test_construction.py::test_construct_fields_set", "tests/test_construction.py::test_construct_allow_extra", "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_construction.py::test_shallow_copy_modify", "tests/test_construction.py::test_construct_default_factory" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2021-01-22 10:52:42+00:00
mit
4,791
pydantic__pydantic-2286
diff --git a/pydantic/types.py b/pydantic/types.py --- a/pydantic/types.py +++ b/pydantic/types.py @@ -799,10 +799,13 @@ def validate_length_for_brand(cls, card_number: 'PaymentCardNumber') -> 'Payment Validate length based on BIN for major brands: https://en.wikipedia.org/wiki/Payment_card_number#Issuer_identification_number_(IIN) """ - required_length: Optional[int] = None - if card_number.brand in {PaymentCardBrand.visa, PaymentCardBrand.mastercard}: + required_length: Union[None, int, str] = None + if card_number.brand in PaymentCardBrand.mastercard: required_length = 16 valid = len(card_number) == required_length + elif card_number.brand == PaymentCardBrand.visa: + required_length = '13, 16 or 19' + valid = len(card_number) in {13, 16, 19} elif card_number.brand == PaymentCardBrand.amex: required_length = 15 valid = len(card_number) == required_length
pydantic/pydantic
13a5c7d676167b415080de5e6e6a74bea095b239
happy to accept a PR to fix this. Just to clarify, is any length between 13 and 19 digits inclusive allowed? Or just 13, 16, or 19 digits? AFAIU it's not inclusive. Did some research and this formatting [website](https://www.freeformatter.com/credit-card-number-generator-validator.html#cardFormats) came up. Let me ask you something about implementation. We may create subtypes following faker's approach (`visa13`, `visa19`, `visa16`). In my opinion, we shouldn't replace `visa` in favor of `visa16` as it's going to break. Let's keep the non explicit `visa` brand ? Any thoughts about this ? I'm opposed to having multiple types. We should have just one card type, people can subclass that or add validators to constrain types more if they wish.
diff --git a/tests/test_types_payment_card_number.py b/tests/test_types_payment_card_number.py --- a/tests/test_types_payment_card_number.py +++ b/tests/test_types_payment_card_number.py @@ -9,7 +9,9 @@ VALID_AMEX = '370000000000002' VALID_MC = '5100000000000003' -VALID_VISA = '4050000000000001' +VALID_VISA_13 = '4050000000001' +VALID_VISA_16 = '4050000000000001' +VALID_VISA_19 = '4050000000000000001' VALID_OTHER = '2000000000000000008' LUHN_INVALID = '4000000000000000' LEN_INVALID = '40000000000000006' @@ -73,7 +75,9 @@ def test_validate_luhn_check_digit(card_number: str, valid: bool): @pytest.mark.parametrize( 'card_number, brand, valid', [ - (VALID_VISA, PaymentCardBrand.visa, True), + (VALID_VISA_13, PaymentCardBrand.visa, True), + (VALID_VISA_16, PaymentCardBrand.visa, True), + (VALID_VISA_19, PaymentCardBrand.visa, True), (VALID_MC, PaymentCardBrand.mastercard, True), (VALID_AMEX, PaymentCardBrand.amex, True), (VALID_OTHER, PaymentCardBrand.other, True), @@ -95,7 +99,7 @@ def test_length_for_brand(card_number: str, brand: PaymentCardBrand, valid: bool [ (VALID_AMEX, PaymentCardBrand.amex), (VALID_MC, PaymentCardBrand.mastercard), - (VALID_VISA, PaymentCardBrand.visa), + (VALID_VISA_16, PaymentCardBrand.visa), (VALID_OTHER, PaymentCardBrand.other), ], ) @@ -104,8 +108,8 @@ def test_get_brand(card_number: str, brand: PaymentCardBrand): def test_valid(): - card = PaymentCard(card_number=VALID_VISA) - assert str(card.card_number) == VALID_VISA + card = PaymentCard(card_number=VALID_VISA_16) + assert str(card.card_number) == VALID_VISA_16 assert card.card_number.masked == '405000******0001'
Support for 13/19 digits VISA credit cards in PaymentCardNumber type # Feature Request Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.5 pydantic compiled: True install path: /Users/<hidden>/.pyenv/versions/3.7.2/envs/common-utils/lib/python3.7/site-packages/pydantic python version: 3.7.2 (default, Jan 22 2020, 18:22:02) [Clang 10.0.1 (clang-1001.0.46.4)] platform: Darwin-18.7.0-x86_64-i386-64bit optional deps. installed: ['typing-extensions'] ``` Currently `PaymentCardNumber` type does support 16-digits VISA only: https://github.com/samuelcolvin/pydantic/blob/3cd8b1ee2d5aac76528dbe627f40fe1c27bf59f6/pydantic/types.py#L677-L679 However as described on wiki page https://en.wikipedia.org/wiki/Payment_card_number: > While the vast majority of Visa's account ranges describe 16 digit card numbers there are still a few account ranges (forty as of 11 December 2013) dedicated to 13 digit PANs and several (439 as of 11 Dec. 2013) account ranges where the issuer can mix 13 and 16 digit card numbers. Visa's VPay brand can specify PAN lengths from **13** to **19** digits and so card numbers of more than 16 digits are now being seen. This fact is handler properly in `faker` library: https://github.com/joke2k/faker/blob/0f86b60178fbbd27d50a184e94c429d4b60d8aef/faker/providers/credit_card/__init__.py#L48-L49 But not handled in pydantic.
0.0
13a5c7d676167b415080de5e6e6a74bea095b239
[ "tests/test_types_payment_card_number.py::test_length_for_brand[4050000000001-Visa-True]", "tests/test_types_payment_card_number.py::test_length_for_brand[4050000000000000001-Visa-True]" ]
[ "tests/test_types_payment_card_number.py::test_validate_digits", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[0-True]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[00-True]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[18-True]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[0000000000000000-True]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[4242424242424240-False]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[4242424242424241-False]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[4242424242424242-True]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[4242424242424243-False]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[4242424242424244-False]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[4242424242424245-False]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[4242424242424246-False]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[4242424242424247-False]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[4242424242424248-False]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[4242424242424249-False]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[42424242424242426-True]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[424242424242424267-True]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[4242424242424242675-True]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[5164581347216566-True]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[4345351087414150-True]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[343728738009846-True]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[5164581347216567-False]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[4345351087414151-False]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[343728738009847-False]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[000000018-True]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[99999999999999999999-True]", "tests/test_types_payment_card_number.py::test_validate_luhn_check_digit[99999999999999999999999999999999999999999999999999999999999999999997-True]", "tests/test_types_payment_card_number.py::test_length_for_brand[4050000000000001-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_length_for_brand[370000000000002-Mastercard-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[4050000000000001-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]", "tests/test_types_payment_card_number.py::test_payment_card_brand" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2021-01-24 23:20:30+00:00
mit
4,792
pydantic__pydantic-2291
diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -627,7 +627,12 @@ def copy( cls = self.__class__ m = cls.__new__(cls) object_setattr(m, '__dict__', v) - object_setattr(m, '__fields_set__', self.__fields_set__.copy()) + # 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:
pydantic/pydantic
13a5c7d676167b415080de5e6e6a74bea095b239
diff --git a/tests/test_construction.py b/tests/test_construction.py --- a/tests/test_construction.py +++ b/tests/test_construction.py @@ -1,5 +1,5 @@ import pickle -from typing import Any, List +from typing import Any, List, Optional import pytest @@ -191,6 +191,14 @@ def test_copy_update(): assert m != m2 +def test_copy_update_unset(): + class Foo(BaseModel): + foo: Optional[str] + bar: Optional[str] + + assert Foo(foo='hello').copy(update={'bar': 'world'}).json(exclude_unset=True) == '{"foo": "hello", "bar": "world"}' + + def test_copy_set_fields(): m = ModelTwo(a=24, d=Model(a='12')) m2 = m.copy()
BaseModel.copy(update=…) does not update __fields_set__ ### 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.7.2 pydantic compiled: False install path: /usr/local/lib/python3.6/dist-packages/pydantic python version: 3.6.9 (default, Oct 8 2020, 12:12:24) [GCC 8.4.0] platform: Linux-4.15.0-112-generic-x86_64-with-Ubuntu-18.04-bionic optional deps. installed: ['typing-extensions', 'email-validator'] ``` ```py from typing import Optional import pydantic class Foo(pydantic.BaseModel): foo: Optional[str] bar: Optional[str] print(Foo(foo='hello') .copy(update={'bar': 'world'}) .json(exclude_unset=True)) # Observed: {"foo": "hello"} # Expected: {"foo": "hello", "bar": "world"} ```
0.0
13a5c7d676167b415080de5e6e6a74bea095b239
[ "tests/test_construction.py::test_copy_update_unset" ]
[ "tests/test_construction.py::test_simple_construct", "tests/test_construction.py::test_construct_misuse", "tests/test_construction.py::test_construct_fields_set", "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_construction.py::test_shallow_copy_modify", "tests/test_construction.py::test_construct_default_factory" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2021-01-26 22:36:05+00:00
mit
4,793
pydantic__pydantic-2294
diff --git a/pydantic/json.py b/pydantic/json.py --- a/pydantic/json.py +++ b/pydantic/json.py @@ -18,6 +18,27 @@ def isoformat(o: Union[datetime.date, datetime.time]) -> str: return o.isoformat() +def decimal_encoder(dec_value: Decimal) -> Union[int, float]: + """ + Encodes a Decimal as int of there's no exponent, otherwise float + + This is useful when we use ConstrainedDecimal to represent Numeric(x,0) + where a integer (but not int typed) is used. Encoding this as a float + results in failed round-tripping between encode and prase. + Our Id type is a prime example of this. + + >>> decimal_encoder(Decimal("1.0")) + 1.0 + + >>> decimal_encoder(Decimal("1")) + 1 + """ + if dec_value.as_tuple().exponent >= 0: + return int(dec_value) + else: + return float(dec_value) + + ENCODERS_BY_TYPE: Dict[Type[Any], Callable[[Any], Any]] = { bytes: lambda o: o.decode(), Color: str, @@ -25,7 +46,7 @@ def isoformat(o: Union[datetime.date, datetime.time]) -> str: datetime.datetime: isoformat, datetime.time: isoformat, datetime.timedelta: lambda td: td.total_seconds(), - Decimal: float, + Decimal: decimal_encoder, Enum: lambda o: o.value, frozenset: list, deque: list,
pydantic/pydantic
cc3010c80d5c635680ca1cad35d4d5a9bf3e219b
diff --git a/tests/test_json.py b/tests/test_json.py --- a/tests/test_json.py +++ b/tests/test_json.py @@ -16,7 +16,7 @@ from pydantic.color import Color from pydantic.dataclasses import dataclass as pydantic_dataclass from pydantic.json import pydantic_encoder, timedelta_isoformat -from pydantic.types import DirectoryPath, FilePath, SecretBytes, SecretStr +from pydantic.types import ConstrainedDecimal, DirectoryPath, FilePath, SecretBytes, SecretStr class MyEnum(Enum): @@ -170,6 +170,25 @@ class Config: assert m.json() == '{"x": "P0DT0H2M3.000000S"}' +def test_con_decimal_encode() -> None: + """ + Makes sure a decimal with decimal_places = 0, as well as one with places + can handle a encode/decode roundtrip. + """ + + class Id(ConstrainedDecimal): + max_digits = 22 + decimal_places = 0 + ge = 0 + + class Obj(BaseModel): + id: Id + price: Decimal = Decimal('0.01') + + assert Obj(id=1).json() == '{"id": 1, "price": 0.01}' + assert Obj.parse_raw('{"id": 1, "price": 0.01}') == Obj(id=1) + + def test_json_encoder_simple_inheritance(): class Parent(BaseModel): dt: datetime.datetime = datetime.datetime.now()
Can't roundtrip json encode/prase properly with ConstrainedDecimal ### 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.7.3 pydantic compiled: True install path: /Users/hultner/Library/Caches/pypoetry/virtualenvs/hantera-backend-5YPPF0bI-py3.9/lib/python3.9/site-packages/pydantic python version: 3.9.0 (default, Oct 10 2020, 11:40:52) [Clang 11.0.3 (clang-1103.0.32.62)] platform: macOS-10.15.7-x86_64-i386-64bit optional deps. installed: ['typing-extensions', 'email-validator', 'devtools'] ``` <!-- 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: --> When using a `ConstrainedDecimal` with zero decimal_places (as provided in example below), pydantic incorrectly encodes the value as a float, thus resulting in failure if one tries to parse the recently encoded json object. Using a decimal with `max_digits = x` and `decimal_places = 0` is a great way of representing for instance a `Numeric(22,0)` (where x is 22) from many SQL database schemas. Certain database engines like the popular pyodbc will properly handle and convert such a Decimal value, but won't handle it as an int as this is implicitly interpreted as a 32 bit int by pyodbc. Having a fixed number of max_digits also allows ones query-engine to pre-compile reusable query plans, which other wise would have to be recomputed for every length of of the given number. In other words, using a ConstrainedDecimal for this type of data is ideal. I have provided a minimal test/example which can both be executed directly but also ran with pytest to showcase the issue at hand. ```py """ Self contained example showcasing problem with decimals using pydantics default encoder. """ from pydantic import ConstrainedDecimal, BaseModel from decimal import Decimal class Id(ConstrainedDecimal): max_digits = 22 decimal_places = 0 ge = 0 ObjId = Id class Obj(BaseModel): id: ObjId name: str price: Decimal = Decimal(0.00) class ObjWithEncoder(BaseModel): id: ObjId name: str price: Decimal = Decimal(0.00) class Config: json_encoders = { Id: int, } def test_con_decimal_encode() -> None: test_obj = Obj(id=1, name="Test Obj") cycled_obj = Obj.parse_raw(test_obj.json()) assert test_obj == cycled_obj def test_con_decimal_encode_custom_encoder() -> None: test_obj = ObjWithEncoder(id=1, name="Test Obj") cycled_obj = ObjWithEncoder.parse_raw(test_obj.json()) assert test_obj == cycled_obj if __name__ == "__main__": from pprint import pprint print_obj = Obj(id=1, name="Test Obj", price=1.23) json_obj = print_obj.json() pprint(json_obj) ``` I have a small patch for pydantic.json-module which I can provide as a pull-request. When using said patch all the tests above will pass, notice that I both handle the case where Decimals do have an negative exponent (decimal_places) and the case where it doesn't. The patch handles both these cases as expected and is written in a minimal, and of course readable fashion. I am right now in the process of reading through the contributor guidelines to ensure that my patch is up to the standards which the project holds for contributions.
0.0
cc3010c80d5c635680ca1cad35d4d5a9bf3e219b
[ "tests/test_json.py::test_con_decimal_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[<genexpr>-[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_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_custom_encoder", "tests/test_json.py::test_custom_iso_timedelta", "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" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2021-01-27 17:25:20+00:00
mit
4,794
pydantic__pydantic-2319
diff --git a/pydantic/fields.py b/pydantic/fields.py --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -449,18 +449,20 @@ def _type_analysis(self) -> None: # noqa: C901 (ignore complexity) if issubclass(origin, Tuple): # type: ignore # origin == Tuple without item type - if not get_args(self.type_): + args = get_args(self.type_) + if not args: # plain tuple self.type_ = Any self.shape = SHAPE_TUPLE_ELLIPSIS - else: + elif len(args) == 2 and args[1] is Ellipsis: # e.g. Tuple[int, ...] + self.type_ = args[0] + self.shape = SHAPE_TUPLE_ELLIPSIS + elif args == ((),): # Tuple[()] means empty tuple self.shape = SHAPE_TUPLE + self.type_ = Any self.sub_fields = [] - for i, t in enumerate(get_args(self.type_)): - if t is Ellipsis: - self.type_ = get_args(self.type_)[0] - self.shape = SHAPE_TUPLE_ELLIPSIS - return - self.sub_fields.append(self._create_sub_type(t, f'{self.name}_{i}')) + else: + self.shape = SHAPE_TUPLE + self.sub_fields = [self._create_sub_type(t, f'{self.name}_{i}') for i, t in enumerate(args)] return if issubclass(origin, List):
pydantic/pydantic
bd9c5723c676395363689549268738153e45a7e5
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 @@ -194,26 +194,38 @@ class Model(BaseModel): def test_tuple_more(): class Model(BaseModel): + empty_tuple: Tuple[()] simple_tuple: tuple = None tuple_of_different_types: Tuple[int, float, str, bool] = None - m = Model(simple_tuple=[1, 2, 3, 4], tuple_of_different_types=[4, 3, 2, 1]) - assert m.dict() == {'simple_tuple': (1, 2, 3, 4), 'tuple_of_different_types': (4, 3.0, '2', True)} + m = Model(empty_tuple=[], simple_tuple=[1, 2, 3, 4], tuple_of_different_types=[4, 3, 2, 1]) + assert m.dict() == { + 'empty_tuple': (), + 'simple_tuple': (1, 2, 3, 4), + 'tuple_of_different_types': (4, 3.0, '2', True), + } def test_tuple_length_error(): class Model(BaseModel): v: Tuple[int, float, bool] + w: Tuple[()] with pytest.raises(ValidationError) as exc_info: - Model(v=[1, 2]) + Model(v=[1, 2], w=[1]) assert exc_info.value.errors() == [ { 'loc': ('v',), 'msg': 'wrong tuple length 2, expected 3', 'type': 'value_error.tuple.length', 'ctx': {'actual_length': 2, 'expected_length': 3}, - } + }, + { + 'loc': ('w',), + 'msg': 'wrong tuple length 1, expected 0', + 'type': 'value_error.tuple.length', + 'ctx': {'actual_length': 1, 'expected_length': 0}, + }, ]
Empty tuple type # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.7.3 pydantic compiled: True install path: /home/guilherme/PycharmProjects/bulk-uploader/venv/lib/python3.8/site-packages/pydantic python version: 3.8.5 (default, Jul 28 2020, 12:59:40) [GCC 9.3.0] platform: Linux-5.4.0-65-generic-x86_64-with-glibc2.29 optional deps. installed: ['typing-extensions'] ``` ```py from pydantic import BaseModel class Example(BaseModel): example: Tuple[()] ``` Will result in: ``` Traceback (most recent call last): File "pydantic/validators.py", line 615, in pydantic.validators.find_validators TypeError: issubclass() arg 1 must be a class During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "...", line 12, in <module> class Example(BaseModel): File "pydantic/main.py", line 262, in pydantic.main.ModelMetaclass.__new__ File "pydantic/fields.py", line 315, in pydantic.fields.ModelField.infer File "pydantic/fields.py", line 284, in pydantic.fields.ModelField.__init__ File "pydantic/fields.py", line 356, in pydantic.fields.ModelField.prepare File "pydantic/fields.py", line 458, in pydantic.fields.ModelField._type_analysis File "pydantic/fields.py", line 516, in pydantic.fields.ModelField._create_sub_type File "pydantic/fields.py", line 284, in pydantic.fields.ModelField.__init__ File "pydantic/fields.py", line 362, in pydantic.fields.ModelField.prepare File "pydantic/fields.py", line 538, in pydantic.fields.ModelField.populate_validators File "pydantic/validators.py", line 624, in find_validators RuntimeError: error checking inheritance of () (type: tuple) ```
0.0
bd9c5723c676395363689549268738153e45a7e5
[ "tests/test_edge_cases.py::test_tuple_more", "tests/test_edge_cases.py::test_tuple_length_error" ]
[ "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_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_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_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_fields_deprecated", "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_side_effect", "tests/test_edge_cases.py::test_default_factory_validator_child" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2021-02-04 20:50:54+00:00
mit
4,795
pydantic__pydantic-2321
diff --git a/pydantic/types.py b/pydantic/types.py --- a/pydantic/types.py +++ b/pydantic/types.py @@ -103,7 +103,6 @@ if TYPE_CHECKING: from .dataclasses import Dataclass # noqa: F401 - from .fields import ModelField from .main import BaseConfig, BaseModel # noqa: F401 from .typing import CallableGenerator @@ -159,8 +158,8 @@ def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None: update_not_none(field_schema, minItems=cls.min_items, maxItems=cls.max_items) @classmethod - def list_length_validator(cls, v: 'Optional[List[T]]', field: 'ModelField') -> 'Optional[List[T]]': - if v is None and not field.required: + def list_length_validator(cls, v: 'Optional[List[T]]') -> 'Optional[List[T]]': + if v is None: return None v = list_validator(v) @@ -201,7 +200,10 @@ def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None: update_not_none(field_schema, minItems=cls.min_items, maxItems=cls.max_items) @classmethod - def set_length_validator(cls, v: 'Optional[Set[T]]', field: 'ModelField') -> 'Optional[Set[T]]': + def set_length_validator(cls, v: 'Optional[Set[T]]') -> 'Optional[Set[T]]': + if v is None: + return None + v = set_validator(v) v_len = len(v)
pydantic/pydantic
bd9c5723c676395363689549268738153e45a7e5
diff --git a/tests/test_types.py b/tests/test_types.py --- a/tests/test_types.py +++ b/tests/test_types.py @@ -156,6 +156,34 @@ class ConListModelMin(BaseModel): ] +def test_constrained_list_optional(): + class Model(BaseModel): + req: Optional[conlist(str, min_items=1)] = ... + opt: Optional[conlist(str, min_items=1)] + + assert Model(req=None).dict() == {'req': None, 'opt': None} + assert Model(req=None, opt=None).dict() == {'req': None, 'opt': None} + + with pytest.raises(ValidationError) as exc_info: + Model(req=[], opt=[]) + assert exc_info.value.errors() == [ + { + 'loc': ('req',), + 'msg': 'ensure this value has at least 1 items', + 'type': 'value_error.list.min_items', + 'ctx': {'limit_value': 1}, + }, + { + 'loc': ('opt',), + 'msg': 'ensure this value has at least 1 items', + 'type': 'value_error.list.min_items', + 'ctx': {'limit_value': 1}, + }, + ] + + assert Model(req=['a'], opt=['a']).dict() == {'req': ['a'], 'opt': ['a']} + + def test_constrained_list_constraints(): class ConListModelBoth(BaseModel): v: conlist(int, min_items=7, max_items=11) @@ -307,6 +335,34 @@ class ConSetModelMin(BaseModel): ] +def test_constrained_set_optional(): + class Model(BaseModel): + req: Optional[conset(str, min_items=1)] = ... + opt: Optional[conset(str, min_items=1)] + + assert Model(req=None).dict() == {'req': None, 'opt': None} + assert Model(req=None, opt=None).dict() == {'req': None, 'opt': None} + + with pytest.raises(ValidationError) as exc_info: + Model(req=set(), opt=set()) + assert exc_info.value.errors() == [ + { + 'loc': ('req',), + 'msg': 'ensure this value has at least 1 items', + 'type': 'value_error.set.min_items', + 'ctx': {'limit_value': 1}, + }, + { + 'loc': ('opt',), + 'msg': 'ensure this value has at least 1 items', + 'type': 'value_error.set.min_items', + 'ctx': {'limit_value': 1}, + }, + ] + + assert Model(req={'a'}, opt={'a'}).dict() == {'req': {'a'}, 'opt': {'a'}} + + def test_constrained_set_constraints(): class ConSetModelBoth(BaseModel): v: conset(int, min_items=7, max_items=11)
BaseSetting Optional[conset(...)] not validated correctly ### 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.7.3 pydantic compiled: True install path: /home/mihai/.virtualenvs/pydantic/lib/python3.9/site-packages/pydantic python version: 3.9.1 (default, Dec 13 2020, 11:55:53) [GCC 10.2.0] platform: Linux-5.10.12-3-ck-x86_64-with-glibc2.32 optional deps. installed: [] ``` ```py from typing import Optional from pydantic import BaseModel, BaseSettings, IPvAnyNetwork, conset class InfoModelSet(BaseModel): network_segments: Optional[set[IPvAnyNetwork]] class InfoModelConset(BaseModel): network_segments: Optional[conset(IPvAnyNetwork, min_items=1)] class InfoSettingsSet(BaseSettings): network_segments: Optional[set[IPvAnyNetwork]] class InfoSettingsConset(BaseSettings): network_segments: Optional[conset(IPvAnyNetwork, min_items=1)] print(f"Info model set: {InfoModelSet()}") print(f"Info model conset: {InfoModelConset()}") print(f"Info settings set: {InfoSettingsSet()}") print() print(f"Info settings conset: {InfoSettingsConset()}") ``` Results in: ``` Info model set: network_segments=None Info model conset: network_segments=None Info settings set: network_segments=None Traceback (most recent call last): File "/home/mihai/bug.py", line 25, in <module> print(f"Info settings conset: {InfoSettingsConset()}") File "pydantic/env_settings.py", line 34, in pydantic.env_settings.BaseSettings.__init__ File "pydantic/main.py", line 362, in pydantic.main.BaseModel.__init__ pydantic.error_wrappers.ValidationError: 1 validation error for InfoSettingsConset network_segments value is not a valid set (type=type_error.set) ``` I would have expected the sample to pass without raising errors and `network_segments` of the `InfoSettingsConset` instance to be `None`.
0.0
bd9c5723c676395363689549268738153e45a7e5
[ "tests/test_types.py::test_constrained_list_optional", "tests/test_types.py::test_constrained_set_optional" ]
[ "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_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_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_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_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_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_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]" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2021-02-05 15:21:55+00:00
mit
4,796
pydantic__pydantic-2325
diff --git a/pydantic/fields.py b/pydantic/fields.py --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -1,9 +1,10 @@ import warnings -from collections import deque +from collections import defaultdict, deque from collections.abc import Iterable as CollectionsIterable from typing import ( TYPE_CHECKING, Any, + DefaultDict, Deque, Dict, FrozenSet, @@ -249,6 +250,8 @@ def Schema(default: Any, **kwargs: Any) -> Any: SHAPE_ITERABLE = 9 SHAPE_GENERIC = 10 SHAPE_DEQUE = 11 +SHAPE_DICT = 12 +SHAPE_DEFAULTDICT = 13 SHAPE_NAME_LOOKUP = { SHAPE_LIST: 'List[{}]', SHAPE_SET: 'Set[{}]', @@ -257,8 +260,12 @@ def Schema(default: Any, **kwargs: Any) -> Any: SHAPE_FROZENSET: 'FrozenSet[{}]', SHAPE_ITERABLE: 'Iterable[{}]', SHAPE_DEQUE: 'Deque[{}]', + SHAPE_DICT: 'Dict[{}]', + SHAPE_DEFAULTDICT: 'DefaultDict[{}]', } +MAPPING_LIKE_SHAPES: Set[int] = {SHAPE_DEFAULTDICT, SHAPE_DICT, SHAPE_MAPPING} + class ModelField(Representation): __slots__ = ( @@ -572,6 +579,14 @@ def _type_analysis(self) -> None: # noqa: C901 (ignore complexity) elif issubclass(origin, Sequence): self.type_ = get_args(self.type_)[0] self.shape = SHAPE_SEQUENCE + elif issubclass(origin, DefaultDict): + self.key_field = self._create_sub_type(get_args(self.type_)[0], 'key_' + self.name, for_keys=True) + self.type_ = get_args(self.type_)[1] + self.shape = SHAPE_DEFAULTDICT + elif issubclass(origin, Dict): + self.key_field = self._create_sub_type(get_args(self.type_)[0], 'key_' + self.name, for_keys=True) + self.type_ = get_args(self.type_)[1] + self.shape = SHAPE_DICT elif issubclass(origin, Mapping): self.key_field = self._create_sub_type(get_args(self.type_)[0], 'key_' + self.name, for_keys=True) self.type_ = get_args(self.type_)[1] @@ -688,8 +703,8 @@ def validate( if self.shape == SHAPE_SINGLETON: v, errors = self._validate_singleton(v, values, loc, cls) - elif self.shape == SHAPE_MAPPING: - v, errors = self._validate_mapping(v, values, loc, cls) + elif self.shape in MAPPING_LIKE_SHAPES: + v, errors = self._validate_mapping_like(v, values, loc, cls) elif self.shape == SHAPE_TUPLE: v, errors = self._validate_tuple(v, values, loc, cls) elif self.shape == SHAPE_ITERABLE: @@ -806,7 +821,7 @@ def _validate_tuple( else: return tuple(result), None - def _validate_mapping( + def _validate_mapping_like( self, v: Any, values: Dict[str, Any], loc: 'LocStr', cls: Optional['ModelOrDc'] ) -> 'ValidateReturn': try: @@ -832,8 +847,30 @@ def _validate_mapping( result[key_result] = value_result if errors: return v, errors - else: + elif self.shape == SHAPE_DICT: return result, None + elif self.shape == SHAPE_DEFAULTDICT: + return defaultdict(self.type_, result), None + else: + return self._get_mapping_value(v, result), None + + def _get_mapping_value(self, original: T, converted: Dict[Any, Any]) -> Union[T, Dict[Any, Any]]: + """ + When type is `Mapping[KT, KV]` (or another unsupported mapping), we try to avoid + coercing to `dict` unwillingly. + """ + original_cls = original.__class__ + + if original_cls == dict or original_cls == Dict: + return converted + elif original_cls in {defaultdict, DefaultDict}: + return defaultdict(self.type_, converted) + else: + try: + # Counter, OrderedDict, UserDict, ... + return original_cls(converted) # type: ignore + except TypeError: + raise RuntimeError(f'Could not convert dictionary to {original_cls.__name__!r}') from None def _validate_singleton( self, v: Any, values: Dict[str, Any], loc: 'LocStr', cls: Optional['ModelOrDc'] @@ -876,7 +913,7 @@ def _type_display(self) -> PyObjectStr: t = display_as_type(self.type_) # have to do this since display_as_type(self.outer_type_) is different (and wrong) on python 3.6 - if self.shape == SHAPE_MAPPING: + if self.shape in MAPPING_LIKE_SHAPES: t = f'Mapping[{display_as_type(self.key_field.type_)}, {t}]' # type: ignore elif self.shape == SHAPE_TUPLE: t = 'Tuple[{}]'.format(', '.join(display_as_type(f.type_) for f in self.sub_fields)) # type: ignore diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -28,7 +28,7 @@ from .class_validators import 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, ModelField, ModelPrivateAttr, PrivateAttr, Undefined +from .fields import MAPPING_LIKE_SHAPES, ModelField, ModelPrivateAttr, PrivateAttr, Undefined from .json import custom_pydantic_encoder, pydantic_encoder from .parse import Protocol, load_file, load_str_bytes from .schema import default_ref_template, model_schema @@ -559,7 +559,8 @@ def json( @classmethod def _enforce_dict_if_root(cls, obj: Any) -> Any: if cls.__custom_root_type__ and ( - not (isinstance(obj, dict) and obj.keys() == {ROOT_KEY}) or cls.__fields__[ROOT_KEY].shape == SHAPE_MAPPING + not (isinstance(obj, dict) and obj.keys() == {ROOT_KEY}) + or cls.__fields__[ROOT_KEY].shape in MAPPING_LIKE_SHAPES ): return {ROOT_KEY: obj} else: diff --git a/pydantic/schema.py b/pydantic/schema.py --- a/pydantic/schema.py +++ b/pydantic/schema.py @@ -29,11 +29,11 @@ from typing_extensions import Annotated, Literal from .fields import ( + MAPPING_LIKE_SHAPES, SHAPE_FROZENSET, SHAPE_GENERIC, SHAPE_ITERABLE, SHAPE_LIST, - SHAPE_MAPPING, SHAPE_SEQUENCE, SHAPE_SET, SHAPE_SINGLETON, @@ -450,7 +450,7 @@ def field_type_schema( if field.shape in {SHAPE_SET, SHAPE_FROZENSET}: f_schema['uniqueItems'] = True - elif field.shape == SHAPE_MAPPING: + elif field.shape in MAPPING_LIKE_SHAPES: f_schema = {'type': 'object'} key_field = cast(ModelField, field.key_field) regex = getattr(key_field.type_, 'regex', None)
pydantic/pydantic
c8883e34db8b42261617f45bf5e46f616dd5862c
Hi @ofek pydantic allows you to use arbitrary classes for validation with the setting `arbitrary_types_allowed` (cf. https://pydantic-docs.helpmanual.io/usage/model_config/): ```py from __future__ import annotations from immutables import Map from pydantic import BaseModel class Model(BaseModel): class Config: arbitrary_types_allowed = True test: Map print(type(Model(test=Map(key=42)).test)) # > <class 'immutables._map.Map'> ``` I hope this help ! Hi @ofek The problem with @rhuille solution is that validation won't be done. If you still need it, see https://github.com/samuelcolvin/pydantic/issues/2311#issuecomment-771794594 ------- @samuelcolvin We already support quite well `Sequence` by having a dedicated check and trying to return the original type https://github.com/samuelcolvin/pydantic/blob/bd9c5723c676395363689549268738153e45a7e5/pydantic/fields.py#L649-L666 Maybe we could do something alike ? I guess something quite easy like https://github.com/PrettyWood/pydantic/pull/70/files could already handle most mapping types (works with OrderedDict, DefaultDict, Map, FrozenDict, ...) WDYT ? Hello @rshin, You are right it comes from the default mapping validator, which always returns a `dict`. @samuelcolvin A potential fix could be something like [this](https://github.com/samuelcolvin/pydantic/compare/master...PrettyWood:fix/dict_validation?expand=1). maybe with a try...except Are you willing to consider it in which case I open a PR? Surely better to implement a validator for `DefaultDict`, thus avoiding any performance impact on normal dictionaries?
diff --git a/tests/test_main.py b/tests/test_main.py --- a/tests/test_main.py +++ b/tests/test_main.py @@ -1,6 +1,7 @@ import sys +from collections import defaultdict from enum import Enum -from typing import Any, Callable, ClassVar, Dict, List, Mapping, Optional, Type, get_type_hints +from typing import Any, Callable, ClassVar, DefaultDict, Dict, List, Mapping, Optional, Type, get_type_hints from uuid import UUID, uuid4 import pytest @@ -1611,6 +1612,70 @@ class Item(BaseModel): assert id(image_2) == id(item.images[1]) +def test_mapping_retains_type_subclass(): + class CustomMap(dict): + pass + + class Model(BaseModel): + x: Mapping[str, Mapping[str, int]] + + m = Model(x=CustomMap(outer=CustomMap(inner=42))) + assert isinstance(m.x, CustomMap) + assert isinstance(m.x['outer'], CustomMap) + assert m.x['outer']['inner'] == 42 + + +def test_mapping_retains_type_defaultdict(): + class Model(BaseModel): + x: Mapping[str, int] + + d = defaultdict(int) + d[1] = '2' + d['3'] + + m = Model(x=d) + assert isinstance(m.x, defaultdict) + assert m.x['1'] == 2 + assert m.x['3'] == 0 + + +def test_mapping_retains_type_fallback_error(): + class CustomMap(dict): + def __init__(self, *args, **kwargs): + if args or kwargs: + raise TypeError('test') + super().__init__(*args, **kwargs) + + class Model(BaseModel): + x: Mapping[str, int] + + d = CustomMap() + d['one'] = 1 + d['two'] = 2 + + with pytest.raises(RuntimeError, match="Could not convert dictionary to 'CustomMap'"): + Model(x=d) + + +def test_typing_coercion_dict(): + class Model(BaseModel): + x: Dict[str, int] + + m = Model(x={'one': 1, 'two': 2}) + assert repr(m) == "Model(x={'one': 1, 'two': 2})" + + +def test_typing_coercion_defaultdict(): + class Model(BaseModel): + x: DefaultDict[int, str] + + d = defaultdict(str) + d['1'] + m = Model(x=d) + m.x['a'] + assert repr(m) == "Model(x=defaultdict(<class 'str'>, {1: '', 'a': ''}))" + + def test_class_kwargs_config(): class Base(BaseModel, extra='forbid', alias_generator=str.upper): a: int
Mapping types are coerced to dict # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.5.1 pydantic compiled: True install path: C:\Users\ofek\AppData\Local\Programs\Python\Python38\Lib\site-packages\pydantic python version: 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 23:11:46) [MSC v.1916 64 bit (AMD64)] platform: Windows-10-10.0.19041-SP0 optional deps. installed: ['typing-extensions', 'email-validator'] ``` I'm trying to use https://github.com/MagicStack/immutables ```py from __future__ import annotations from typing import Mapping from immutables import Map from pydantic import BaseModel class Model(BaseModel): test: Mapping[str, int] print(type(Model(test=Map(key=42)).test)) ``` produces ``` <class 'dict'> ``` Is there a way to keep the type of encountered Mappings, or create a type representing `immutables.Map`? I've been at this for hours reading docs/closed issues, trying various approaches, and now I'm simply at a loss here. defaultdict converted to dict after __post_init__ # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.5.1 pydantic compiled: True install path: <redacted>/lib/python3.7/site-packages/pydantic python version: 3.7.3 | packaged by conda-forge | (default, Dec 6 2019, 08:36:57) [Clang 9.0.0 (tags/RELEASE_900/final)] platform: Darwin-19.4.0-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: --> If I run the following snippet: ```py import collections import dataclasses from typing import DefaultDict from pydantic.dataclasses import dataclass @dataclass class X: f: DefaultDict[int, int] = dataclasses.field(init=False) def __post_init__(self): self.f = collections.defaultdict(int) self.f[2] += 1 print(f"__post_init__: {self.f}") x = X() print(type(x.f)) print(x.f) ``` It prints the following: ``` __post_init__: defaultdict(<class 'int'>, {2: 1}) <class 'dict'> {2: 1} ``` In other words, the `defaultdict` field is converted into a `dict` (while preserving the keys), even though the field is annotated as DefaultDict, which is surprising. Is this intended behavior?
0.0
c8883e34db8b42261617f45bf5e46f616dd5862c
[ "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_defaultdict" ]
[ "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_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_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_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", "tests/test_main.py::test_model_export_dict_exclusion", "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_inherited_model_field_copy", "tests/test_main.py::test_inherited_model_field_untouched", "tests/test_main.py::test_typing_coercion_dict", "tests/test_main.py::test_class_kwargs_config", "tests/test_main.py::test_class_kwargs_config_and_attr_conflict" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2021-02-07 16:39:36+00:00
mit
4,797
pydantic__pydantic-2336
diff --git a/docs/examples/schema_ad_hoc.py b/docs/examples/schema_ad_hoc.py new file mode 100644 --- /dev/null +++ b/docs/examples/schema_ad_hoc.py @@ -0,0 +1,20 @@ +from typing import Literal, Union + +from typing_extensions import Annotated + +from pydantic import BaseModel, Field, schema_json + + +class Cat(BaseModel): + pet_type: Literal['cat'] + cat_name: str + + +class Dog(BaseModel): + pet_type: Literal['dog'] + dog_name: str + + +Pet = Annotated[Union[Cat, Dog], Field(discriminator='pet_type')] + +print(schema_json(Pet, title='The Pet Schema', indent=2)) diff --git a/docs/examples/types_union_discriminated.py b/docs/examples/types_union_discriminated.py new file mode 100644 --- /dev/null +++ b/docs/examples/types_union_discriminated.py @@ -0,0 +1,30 @@ +from typing import Literal, Union + +from pydantic import BaseModel, Field, ValidationError + + +class Cat(BaseModel): + pet_type: Literal['cat'] + meows: int + + +class Dog(BaseModel): + pet_type: Literal['dog'] + barks: float + + +class Lizard(BaseModel): + pet_type: Literal['reptile', 'lizard'] + scales: bool + + +class Model(BaseModel): + pet: Union[Cat, Dog, Lizard] = Field(..., discriminator='pet_type') + n: int + + +print(Model(pet={'pet_type': 'dog', 'barks': 3.14}, n=1)) +try: + Model(pet={'pet_type': 'dog'}, n=1) +except ValidationError as e: + print(e) diff --git a/docs/examples/types_union_discriminated_nested.py b/docs/examples/types_union_discriminated_nested.py new file mode 100644 --- /dev/null +++ b/docs/examples/types_union_discriminated_nested.py @@ -0,0 +1,50 @@ +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 + + +m = Model(pet={'pet_type': 'cat', 'color': 'black', 'black_name': 'felix'}, n=1) +print(m) +try: + Model(pet={'pet_type': 'cat', 'color': 'red'}, n='1') +except ValidationError as e: + print(e) +try: + Model(pet={'pet_type': 'cat', 'color': 'black'}, n='1') +except ValidationError as e: + print(e) diff --git a/pydantic/__init__.py b/pydantic/__init__.py --- a/pydantic/__init__.py +++ b/pydantic/__init__.py @@ -66,6 +66,8 @@ 'parse_file_as', 'parse_obj_as', 'parse_raw_as', + 'schema', + 'schema_json', # types 'NoneStr', 'NoneBytes', diff --git a/pydantic/errors.py b/pydantic/errors.py --- a/pydantic/errors.py +++ b/pydantic/errors.py @@ -1,6 +1,6 @@ from decimal import Decimal from pathlib import Path -from typing import TYPE_CHECKING, Any, Callable, Set, Tuple, Type, Union +from typing import TYPE_CHECKING, Any, Callable, Sequence, Set, Tuple, Type, Union from .typing import display_as_type @@ -99,6 +99,8 @@ 'InvalidLengthForBrand', 'InvalidByteSize', 'InvalidByteSizeUnit', + 'MissingDiscriminator', + 'InvalidDiscriminator', ) @@ -611,3 +613,23 @@ class InvalidByteSize(PydanticValueError): class InvalidByteSizeUnit(PydanticValueError): msg_template = 'could not interpret byte unit: {unit}' + + +class MissingDiscriminator(PydanticValueError): + code = 'discriminated_union.missing_discriminator' + msg_template = 'Discriminator {discriminator_key!r} is missing in value' + + +class InvalidDiscriminator(PydanticValueError): + code = 'discriminated_union.invalid_discriminator' + msg_template = ( + 'No match for discriminator {discriminator_key!r} and value {discriminator_value!r} ' + '(allowed values: {allowed_values})' + ) + + def __init__(self, *, discriminator_key: str, discriminator_value: Any, allowed_values: Sequence[Any]) -> None: + super().__init__( + discriminator_key=discriminator_key, + discriminator_value=discriminator_value, + allowed_values=', '.join(map(repr, allowed_values)), + ) diff --git a/pydantic/fields.py b/pydantic/fields.py --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -28,7 +28,7 @@ from . import errors as errors_ from .class_validators import Validator, make_generic_validator, prep_validators from .error_wrappers import ErrorWrapper -from .errors import ConfigError, NoneIsNotAllowedError +from .errors import ConfigError, InvalidDiscriminator, MissingDiscriminator, NoneIsNotAllowedError from .types import Json, JsonWrapper from .typing import ( Callable, @@ -45,7 +45,16 @@ is_union, new_type_supertype, ) -from .utils import PyObjectStr, Representation, ValueItems, lenient_issubclass, sequence_like, smart_deepcopy +from .utils import ( + PyObjectStr, + Representation, + ValueItems, + get_discriminator_alias_and_values, + get_unique_discriminator_alias, + lenient_issubclass, + sequence_like, + smart_deepcopy, +) from .validators import constant_validator, dict_validator, find_validators, validate_json Required: Any = Ellipsis @@ -108,6 +117,7 @@ class FieldInfo(Representation): 'allow_mutation', 'repr', 'regex', + 'discriminator', 'extra', ) @@ -147,6 +157,7 @@ def __init__(self, default: Any = Undefined, **kwargs: Any) -> None: self.max_length = kwargs.pop('max_length', None) self.allow_mutation = kwargs.pop('allow_mutation', True) self.regex = kwargs.pop('regex', None) + self.discriminator = kwargs.pop('discriminator', None) self.repr = kwargs.pop('repr', True) self.extra = kwargs @@ -212,6 +223,7 @@ def Field( max_length: int = None, allow_mutation: bool = True, regex: str = None, + discriminator: str = None, repr: bool = True, **extra: Any, ) -> Any: @@ -249,6 +261,8 @@ def Field( assigned on an instance. The BaseModel Config must set validate_assignment to True :param regex: only applies to strings, requires the field match against a regular expression pattern string. The schema will have a ``pattern`` validation keyword + :param discriminator: only useful with a (discriminated a.k.a. tagged) `Union` of sub models with a common field. + The `discriminator` is the name of this common field to shorten validation and improve generated schema :param repr: show this field in the representation :param **extra: any additional keyword arguments will be added as is to the schema """ @@ -272,6 +286,7 @@ def Field( max_length=max_length, allow_mutation=allow_mutation, regex=regex, + discriminator=discriminator, repr=repr, **extra, ) @@ -315,6 +330,7 @@ class ModelField(Representation): 'type_', 'outer_type_', 'sub_fields', + 'sub_fields_mapping', 'key_field', 'validators', 'pre_validators', @@ -327,6 +343,8 @@ class ModelField(Representation): 'alias', 'has_alias', 'field_info', + 'discriminator_key', + 'discriminator_alias', 'validate_always', 'allow_none', 'shape', @@ -359,10 +377,13 @@ def __init__( self.required: 'BoolUndefined' = required self.model_config = model_config self.field_info: FieldInfo = field_info or FieldInfo(default) + self.discriminator_key: Optional[str] = self.field_info.discriminator + self.discriminator_alias: Optional[str] = self.discriminator_key self.allow_none: bool = False self.validate_always: bool = False self.sub_fields: Optional[List[ModelField]] = None + self.sub_fields_mapping: Optional[Dict[str, 'ModelField']] = None # used for discriminated union self.key_field: Optional[ModelField] = None self.validators: 'ValidatorsList' = [] self.pre_validators: Optional['ValidatorsList'] = None @@ -547,6 +568,15 @@ def _type_analysis(self) -> None: # noqa: C901 (ignore complexity) return origin = get_origin(self.type_) + + if origin is Annotated: + self.type_ = get_args(self.type_)[0] + self._type_analysis() + return + + if self.discriminator_key is not None and not is_union(origin): + raise TypeError('`discriminator` can only be used with `Union` type') + # add extra check for `collections.abc.Hashable` for python 3.10+ where origin is not `None` if origin is None or origin is CollectionsHashable: # field is not "typing" object eg. Union, Dict, List etc. @@ -554,10 +584,6 @@ def _type_analysis(self) -> None: # noqa: C901 (ignore complexity) if isinstance(self.type_, type) and isinstance(None, self.type_): self.allow_none = True return - elif origin is Annotated: - self.type_ = get_args(self.type_)[0] - self._type_analysis() - return elif origin is Callable: return elif is_union(origin): @@ -579,6 +605,9 @@ def _type_analysis(self) -> None: # noqa: C901 (ignore complexity) self._type_analysis() else: self.sub_fields = [self._create_sub_type(t, f'{self.name}_{display_as_type(t)}') for t in types_] + + if self.discriminator_key is not None: + self.prepare_discriminated_union_sub_fields() return elif issubclass(origin, Tuple): # type: ignore # origin == Tuple without item type @@ -672,6 +701,30 @@ 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 prepare_discriminated_union_sub_fields(self) -> None: + """ + Prepare the mapping <discriminator key> -> <ModelField> and update `sub_fields` + Note that this process can be aborted if a `ForwardRef` is encountered + """ + assert self.discriminator_key is not None + assert self.sub_fields is not None + sub_fields_mapping: Dict[str, 'ModelField'] = {} + all_aliases: Set[str] = set() + + for sub_field in self.sub_fields: + t = sub_field.type_ + if t.__class__ is ForwardRef: + # Stopping everything...will need to call `update_forward_refs` + return + + alias, discriminator_values = get_discriminator_alias_and_values(t, self.discriminator_key) + all_aliases.add(alias) + for discriminator_value in discriminator_values: + sub_fields_mapping[discriminator_value] = sub_field + + self.sub_fields_mapping = sub_fields_mapping + self.discriminator_alias = get_unique_discriminator_alias(all_aliases, self.discriminator_key) + def _create_sub_type(self, type_: Type[Any], name: str, *, for_keys: bool = False) -> 'ModelField': if for_keys: class_validators = None @@ -689,11 +742,15 @@ def _create_sub_type(self, type_: Type[Any], name: str, *, for_keys: bool = Fals for k, v in self.class_validators.items() if v.each_item } + + field_info, _ = self._get_field_info(name, type_, None, self.model_config) + return self.__class__( type_=type_, name=name, class_validators=class_validators, model_config=self.model_config, + field_info=field_info, ) def populate_validators(self) -> None: @@ -940,6 +997,9 @@ def _validate_singleton( self, v: Any, values: Dict[str, Any], loc: 'LocStr', cls: Optional['ModelOrDc'] ) -> 'ValidateReturn': if self.sub_fields: + if self.discriminator_key is not None: + return self._validate_discriminated_union(v, values, loc, cls) + errors = [] if self.model_config.smart_union and is_union(get_origin(self.type_)): @@ -980,6 +1040,46 @@ def _validate_singleton( else: return self._apply_validators(v, values, loc, cls, self.validators) + def _validate_discriminated_union( + self, v: Any, values: Dict[str, Any], loc: 'LocStr', cls: Optional['ModelOrDc'] + ) -> 'ValidateReturn': + assert self.discriminator_key is not None + assert self.discriminator_alias is not None + + try: + discriminator_value = v[self.discriminator_alias] + except KeyError: + return v, ErrorWrapper(MissingDiscriminator(discriminator_key=self.discriminator_key), loc) + except TypeError: + try: + # BaseModel or dataclass + discriminator_value = getattr(v, self.discriminator_alias) + 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: + 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: + assert self.sub_fields_mapping is not None + return v, ErrorWrapper( + InvalidDiscriminator( + discriminator_key=self.discriminator_key, + discriminator_value=discriminator_value, + allowed_values=list(self.sub_fields_mapping), + ), + loc, + ) + else: + if not isinstance(loc, tuple): + loc = (loc,) + return sub_field.validate(v, values, loc=(*loc, display_as_type(sub_field.type_)), cls=cls) + def _apply_validators( self, v: Any, values: Dict[str, Any], loc: 'LocStr', cls: Optional['ModelOrDc'], validators: 'ValidatorsList' ) -> 'ValidateReturn': diff --git a/pydantic/schema.py b/pydantic/schema.py --- a/pydantic/schema.py +++ b/pydantic/schema.py @@ -70,6 +70,7 @@ all_literal_values, get_args, get_origin, + get_sub_types, is_callable_type, is_literal_type, is_namedtuple, @@ -250,6 +251,37 @@ def field_schema( ref_template=ref_template, known_models=known_models or set(), ) + + # https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#discriminator-object + if field.discriminator_key is not None: + assert field.sub_fields_mapping is not None + + discriminator_models_refs: Dict[str, Union[str, Dict[str, Any]]] = {} + + for discriminator_value, sub_field in field.sub_fields_mapping.items(): + # sub_field is either a `BaseModel` or directly an `Annotated` `Union` of many + if is_union(get_origin(sub_field.type_)): + sub_models = get_sub_types(sub_field.type_) + discriminator_models_refs[discriminator_value] = { + model_name_map[sub_model]: get_schema_ref( + model_name_map[sub_model], ref_prefix, ref_template, False + ) + for sub_model in sub_models + } + else: + sub_field_type = sub_field.type_ + if hasattr(sub_field_type, '__pydantic_model__'): + sub_field_type = sub_field_type.__pydantic_model__ + + discriminator_model_name = model_name_map[sub_field_type] + discriminator_model_ref = get_schema_ref(discriminator_model_name, ref_prefix, ref_template, False) + discriminator_models_refs[discriminator_value] = discriminator_model_ref['$ref'] + + s['discriminator'] = { + 'propertyName': field.discriminator_alias, + 'mapping': discriminator_models_refs, + } + # $ref will only be returned when there are no schema_overrides if '$ref' in f_schema: return f_schema, f_definitions, f_nested_models diff --git a/pydantic/tools.py b/pydantic/tools.py --- a/pydantic/tools.py +++ b/pydantic/tools.py @@ -1,16 +1,19 @@ import json from functools import lru_cache from pathlib import Path -from typing import Any, Callable, Optional, Type, TypeVar, Union +from typing import TYPE_CHECKING, Any, Callable, Optional, Type, TypeVar, Union from .parse import Protocol, load_file, load_str_bytes from .types import StrBytes from .typing import display_as_type -__all__ = ('parse_file_as', 'parse_obj_as', 'parse_raw_as') +__all__ = ('parse_file_as', 'parse_obj_as', 'parse_raw_as', 'schema', 'schema_json') NameFactory = Union[str, Callable[[Type[Any]], str]] +if TYPE_CHECKING: + from .typing import DictStrAny + def _generate_parsing_type_name(type_: Any) -> str: return f'ParsingModel[{display_as_type(type_)}]' @@ -77,3 +80,13 @@ def parse_raw_as( json_loads=json_loads, ) return parse_obj_as(type_, obj, type_name=type_name) + + +def schema(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: + """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) diff --git a/pydantic/typing.py b/pydantic/typing.py --- a/pydantic/typing.py +++ b/pydantic/typing.py @@ -262,6 +262,7 @@ def is_union(tp: Type[Any]) -> bool: 'WithArgsTypes', 'get_args', 'get_origin', + 'get_sub_types', 'typing_base', 'get_all_type_hints', 'is_union', @@ -310,6 +311,9 @@ def display_as_type(v: Type[Any]) -> str: if not isinstance(v, typing_base) and not isinstance(v, WithArgsTypes) and not isinstance(v, type): v = v.__class__ + if is_union(get_origin(v)): + return f'Union[{", ".join(map(display_as_type, get_args(v)))}]' + if isinstance(v, WithArgsTypes): # Generic alias are constructs like `list[int]` return str(v).replace('typing.', '') @@ -443,10 +447,14 @@ def update_field_forward_refs(field: 'ModelField', globalns: Any, localns: Any) if field.type_.__class__ == 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) + if field.discriminator_key is not None: + field.prepare_discriminated_union_sub_fields() + def update_model_forward_refs( model: Type[Any], @@ -487,3 +495,17 @@ def get_class(type_: Type[Any]) -> Union[None, bool, Type[Any]]: except (AttributeError, TypeError): pass return None + + +def get_sub_types(tp: Any) -> List[Any]: + """ + Return all the types that are allowed by type `tp` + `tp` can be a `Union` of allowed types or an `Annotated` type + """ + origin = get_origin(tp) + if origin is Annotated: + return get_sub_types(get_args(tp)[0]) + elif is_union(origin): + return [x for t in get_args(tp) for x in get_sub_types(t)] + else: + return [tp] diff --git a/pydantic/utils.py b/pydantic/utils.py --- a/pydantic/utils.py +++ b/pydantic/utils.py @@ -9,6 +9,7 @@ AbstractSet, Any, Callable, + Collection, Dict, Generator, Iterable, @@ -23,7 +24,19 @@ Union, ) -from .typing import NoneType, WithArgsTypes, display_as_type +from typing_extensions import Annotated + +from .errors import ConfigError +from .typing import ( + NoneType, + WithArgsTypes, + all_literal_values, + display_as_type, + get_args, + get_origin, + is_literal_type, + is_union, +) from .version import version_info if TYPE_CHECKING: @@ -57,6 +70,8 @@ 'ClassAttribute', 'path_type', 'ROOT_KEY', + 'get_unique_discriminator_alias', + 'get_discriminator_alias_and_values', ) ROOT_KEY = '__root__' @@ -665,3 +680,63 @@ def all_identical(left: Iterable[Any], right: Iterable[Any]) -> bool: if left_item is not right_item: return False return True + + +def get_unique_discriminator_alias(all_aliases: Collection[str], discriminator_key: str) -> str: + """Validate that all aliases are the same and if that's the case return the alias""" + unique_aliases = set(all_aliases) + if len(unique_aliases) > 1: + raise ConfigError( + f'Aliases for discriminator {discriminator_key!r} must be the same (got {", ".join(sorted(all_aliases))})' + ) + return unique_aliases.pop() + + +def get_discriminator_alias_and_values(tp: Any, discriminator_key: str) -> Tuple[str, Tuple[str, ...]]: + """ + Get alias and all valid values in the `Literal` type of the discriminator field + `tp` can be a `BaseModel` class or directly an `Annotated` `Union` of many. + """ + is_root_model = getattr(tp, '__custom_root_type__', False) + + if get_origin(tp) is Annotated: + tp = get_args(tp)[0] + + if hasattr(tp, '__pydantic_model__'): + tp = tp.__pydantic_model__ + + if is_union(get_origin(tp)): + alias, all_values = _get_union_alias_and_all_values(tp, discriminator_key) + return alias, tuple(v for values in all_values for v in values) + elif is_root_model: + union_type = tp.__fields__[ROOT_KEY].type_ + alias, all_values = _get_union_alias_and_all_values(union_type, discriminator_key) + + if len(set(all_values)) > 1: + raise ConfigError( + f'Field {discriminator_key!r} is not the same for all submodels of {display_as_type(tp)!r}' + ) + + return alias, all_values[0] + + else: + try: + t_discriminator_type = tp.__fields__[discriminator_key].type_ + except AttributeError as e: + raise TypeError(f'Type {tp.__name__!r} is not a valid `BaseModel` or `dataclass`') from e + except KeyError as e: + raise ConfigError(f'Model {tp.__name__!r} needs a discriminator field for key {discriminator_key!r}') from e + + if not is_literal_type(t_discriminator_type): + raise ConfigError(f'Field {discriminator_key!r} of model {tp.__name__!r} needs to be a `Literal`') + + return tp.__fields__[discriminator_key].alias, all_literal_values(t_discriminator_type) + + +def _get_union_alias_and_all_values( + union_type: Type[Any], discriminator_key: str +) -> Tuple[str, Tuple[Tuple[str, ...], ...]]: + zipped_aliases_values = [get_discriminator_alias_and_values(t, discriminator_key) for t in get_args(union_type)] + # 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
pydantic/pydantic
afcd15522e6a8474270e5e028bc498baffac631a
diff --git a/tests/test_dataclasses.py b/tests/test_dataclasses.py --- a/tests/test_dataclasses.py +++ b/tests/test_dataclasses.py @@ -3,9 +3,10 @@ from collections.abc import Hashable from datetime import datetime from pathlib import Path -from typing import Callable, ClassVar, Dict, FrozenSet, List, Optional +from typing import Callable, ClassVar, Dict, FrozenSet, List, Optional, Union import pytest +from typing_extensions import Literal import pydantic from pydantic import BaseModel, ValidationError, validator @@ -922,6 +923,49 @@ class A2: } +def test_discrimated_union_basemodel_instance_value(): + @pydantic.dataclasses.dataclass + class A: + l: Literal['a'] + + @pydantic.dataclasses.dataclass + class B: + l: Literal['b'] + + @pydantic.dataclasses.dataclass + class Top: + sub: Union[A, B] = dataclasses.field(metadata=dict(discriminator='l')) + + t = Top(sub=A(l='a')) + assert isinstance(t, Top) + assert Top.__pydantic_model__.schema() == { + 'title': 'Top', + 'type': 'object', + 'properties': { + 'sub': { + 'title': 'Sub', + 'discriminator': {'propertyName': 'l', 'mapping': {'a': '#/definitions/A', 'b': '#/definitions/B'}}, + 'anyOf': [{'$ref': '#/definitions/A'}, {'$ref': '#/definitions/B'}], + } + }, + 'required': ['sub'], + 'definitions': { + 'A': { + 'title': 'A', + 'type': 'object', + 'properties': {'l': {'title': 'L', 'enum': ['a'], 'type': 'string'}}, + 'required': ['l'], + }, + 'B': { + 'title': 'B', + 'type': 'object', + 'properties': {'l': {'title': 'L', 'enum': ['b'], 'type': 'string'}}, + 'required': ['l'], + }, + }, + } + + def test_keeps_custom_properties(): class StandardClass: """Class which modifies instance creation.""" diff --git a/tests/test_discrimated_union.py b/tests/test_discrimated_union.py new file mode 100644 --- /dev/null +++ b/tests/test_discrimated_union.py @@ -0,0 +1,363 @@ +import re +from enum import Enum +from typing import Union + +import pytest +from typing_extensions import Annotated, Literal + +from pydantic import BaseModel, Field, ValidationError +from pydantic.errors import ConfigError + + +def test_discriminated_union_only_union(): + with pytest.raises(TypeError, match='`discriminator` can only be used with `Union` type'): + + class Model(BaseModel): + x: str = Field(..., discriminator='qwe') + + +def test_discriminated_union_invalid_type(): + with pytest.raises(TypeError, match="Type 'str' is not a valid `BaseModel` or `dataclass`"): + + class Model(BaseModel): + x: Union[str, int] = Field(..., discriminator='qwe') + + +def test_discriminated_union_defined_discriminator(): + class Cat(BaseModel): + c: str + + class Dog(BaseModel): + pet_type: Literal['dog'] + d: str + + with pytest.raises(ConfigError, match="Model 'Cat' needs a discriminator field for key 'pet_type'"): + + class Model(BaseModel): + pet: Union[Cat, Dog] = Field(..., discriminator='pet_type') + number: int + + +def test_discriminated_union_literal_discriminator(): + class Cat(BaseModel): + pet_type: int + c: str + + class Dog(BaseModel): + pet_type: Literal['dog'] + d: str + + with pytest.raises(ConfigError, match="Field 'pet_type' of model 'Cat' needs to be a `Literal`"): + + class Model(BaseModel): + pet: Union[Cat, Dog] = Field(..., discriminator='pet_type') + number: int + + +def test_discriminated_union_root_same_discriminator(): + class BlackCat(BaseModel): + pet_type: Literal['blackcat'] + + class WhiteCat(BaseModel): + pet_type: Literal['whitecat'] + + class Cat(BaseModel): + __root__: Union[BlackCat, WhiteCat] + + class Dog(BaseModel): + pet_type: Literal['dog'] + + with pytest.raises(ConfigError, match="Field 'pet_type' is not the same for all submodels of 'Cat'"): + + class Pet(BaseModel): + __root__: Union[Cat, Dog] = Field(..., discriminator='pet_type') + + +def test_discriminated_union_validation(): + class BlackCat(BaseModel): + pet_type: Literal['cat'] + color: Literal['black'] + black_infos: str + + class WhiteCat(BaseModel): + pet_type: Literal['cat'] + color: Literal['white'] + white_infos: str + + class Cat(BaseModel): + __root__: Annotated[Union[BlackCat, WhiteCat], Field(discriminator='color')] + + class Dog(BaseModel): + pet_type: Literal['dog'] + d: str + + class Lizard(BaseModel): + pet_type: Literal['reptile', 'lizard'] + l: str + + class Model(BaseModel): + pet: Annotated[Union[Cat, Dog, Lizard], Field(discriminator='pet_type')] + number: int + + with pytest.raises(ValidationError) as exc_info: + Model.parse_obj({'pet': {'pet_typ': 'cat'}, 'number': 'x'}) + assert exc_info.value.errors() == [ + { + 'loc': ('pet',), + 'msg': "Discriminator 'pet_type' is missing in value", + 'type': 'value_error.discriminated_union.missing_discriminator', + 'ctx': {'discriminator_key': 'pet_type'}, + }, + {'loc': ('number',), 'msg': 'value is not a valid integer', 'type': 'type_error.integer'}, + ] + + with pytest.raises(ValidationError) as exc_info: + Model.parse_obj({'pet': 'fish', 'number': 2}) + assert exc_info.value.errors() == [ + { + 'loc': ('pet',), + 'msg': "Discriminator 'pet_type' is missing in value", + 'type': 'value_error.discriminated_union.missing_discriminator', + 'ctx': {'discriminator_key': 'pet_type'}, + }, + ] + + with pytest.raises(ValidationError) as exc_info: + Model.parse_obj({'pet': {'pet_type': 'fish'}, 'number': 2}) + assert exc_info.value.errors() == [ + { + 'loc': ('pet',), + 'msg': ( + "No match for discriminator 'pet_type' and value 'fish' " + "(allowed values: 'cat', 'dog', 'reptile', 'lizard')" + ), + 'type': 'value_error.discriminated_union.invalid_discriminator', + 'ctx': { + 'discriminator_key': 'pet_type', + 'discriminator_value': 'fish', + 'allowed_values': "'cat', 'dog', 'reptile', 'lizard'", + }, + }, + ] + + with pytest.raises(ValidationError) as exc_info: + Model.parse_obj({'pet': {'pet_type': 'lizard'}, 'number': 2}) + assert exc_info.value.errors() == [ + {'loc': ('pet', 'Lizard', 'l'), 'msg': 'field required', 'type': 'value_error.missing'}, + ] + + m = Model.parse_obj({'pet': {'pet_type': 'lizard', 'l': 'pika'}, 'number': 2}) + assert isinstance(m.pet, Lizard) + assert m.dict() == {'pet': {'pet_type': 'lizard', 'l': 'pika'}, 'number': 2} + + with pytest.raises(ValidationError) as exc_info: + Model.parse_obj({'pet': {'pet_type': 'cat', 'color': 'white'}, 'number': 2}) + assert exc_info.value.errors() == [ + { + 'loc': ('pet', 'Cat', '__root__', 'WhiteCat', 'white_infos'), + 'msg': 'field required', + 'type': 'value_error.missing', + } + ] + m = Model.parse_obj({'pet': {'pet_type': 'cat', 'color': 'white', 'white_infos': 'pika'}, 'number': 2}) + assert isinstance(m.pet.__root__, WhiteCat) + + +def test_discriminated_annotated_union(): + class BlackCat(BaseModel): + pet_type: Literal['cat'] + color: Literal['black'] + black_infos: str + + class WhiteCat(BaseModel): + pet_type: Literal['cat'] + color: Literal['white'] + white_infos: str + + Cat = Annotated[Union[BlackCat, WhiteCat], Field(discriminator='color')] + + class Dog(BaseModel): + pet_type: Literal['dog'] + dog_name: str + + Pet = Annotated[Union[Cat, Dog], Field(discriminator='pet_type')] + + class Model(BaseModel): + pet: Pet + number: int + + with pytest.raises(ValidationError) as exc_info: + Model.parse_obj({'pet': {'pet_typ': 'cat'}, 'number': 'x'}) + assert exc_info.value.errors() == [ + { + 'loc': ('pet',), + 'msg': "Discriminator 'pet_type' is missing in value", + 'type': 'value_error.discriminated_union.missing_discriminator', + 'ctx': {'discriminator_key': 'pet_type'}, + }, + {'loc': ('number',), 'msg': 'value is not a valid integer', 'type': 'type_error.integer'}, + ] + + with pytest.raises(ValidationError) as exc_info: + Model.parse_obj({'pet': {'pet_type': 'fish'}, 'number': 2}) + assert exc_info.value.errors() == [ + { + 'loc': ('pet',), + 'msg': "No match for discriminator 'pet_type' and value 'fish' " "(allowed values: 'cat', 'dog')", + 'type': 'value_error.discriminated_union.invalid_discriminator', + 'ctx': {'discriminator_key': 'pet_type', 'discriminator_value': 'fish', 'allowed_values': "'cat', 'dog'"}, + }, + ] + + with pytest.raises(ValidationError) as exc_info: + Model.parse_obj({'pet': {'pet_type': 'dog'}, 'number': 2}) + assert exc_info.value.errors() == [ + {'loc': ('pet', 'Dog', 'dog_name'), 'msg': 'field required', 'type': 'value_error.missing'}, + ] + m = Model.parse_obj({'pet': {'pet_type': 'dog', 'dog_name': 'milou'}, 'number': 2}) + assert isinstance(m.pet, Dog) + + with pytest.raises(ValidationError) as exc_info: + Model.parse_obj({'pet': {'pet_type': 'cat', 'color': 'red'}, 'number': 2}) + assert exc_info.value.errors() == [ + { + 'loc': ('pet', 'Union[BlackCat, WhiteCat]'), + 'msg': "No match for discriminator 'color' and value 'red' " "(allowed values: 'black', 'white')", + 'type': 'value_error.discriminated_union.invalid_discriminator', + 'ctx': {'discriminator_key': 'color', 'discriminator_value': 'red', 'allowed_values': "'black', 'white'"}, + } + ] + + with pytest.raises(ValidationError) as exc_info: + Model.parse_obj({'pet': {'pet_type': 'cat', 'color': 'white'}, 'number': 2}) + assert exc_info.value.errors() == [ + { + 'loc': ('pet', 'Union[BlackCat, WhiteCat]', 'WhiteCat', 'white_infos'), + 'msg': 'field required', + 'type': 'value_error.missing', + } + ] + m = Model.parse_obj({'pet': {'pet_type': 'cat', 'color': 'white', 'white_infos': 'pika'}, 'number': 2}) + assert isinstance(m.pet, WhiteCat) + + +def test_discriminated_union_basemodel_instance_value(): + class A(BaseModel): + l: Literal['a'] + + class B(BaseModel): + l: Literal['b'] + + class Top(BaseModel): + sub: Union[A, B] = Field(..., discriminator='l') + + t = Top(sub=A(l='a')) + assert isinstance(t, Top) + + +def test_discriminated_union_int(): + class A(BaseModel): + l: Literal[1] + + class B(BaseModel): + l: Literal[2] + + class Top(BaseModel): + sub: Union[A, B] = Field(..., discriminator='l') + + assert isinstance(Top.parse_obj({'sub': {'l': 2}}).sub, B) + with pytest.raises(ValidationError) as exc_info: + Top.parse_obj({'sub': {'l': 3}}) + assert exc_info.value.errors() == [ + { + 'loc': ('sub',), + 'msg': "No match for discriminator 'l' and value 3 (allowed values: 1, 2)", + 'type': 'value_error.discriminated_union.invalid_discriminator', + 'ctx': {'discriminator_key': 'l', 'discriminator_value': 3, 'allowed_values': '1, 2'}, + } + ] + + +def test_discriminated_union_enum(): + class EnumValue(Enum): + a = 1 + b = 2 + + class A(BaseModel): + l: Literal[EnumValue.a] + + class B(BaseModel): + l: Literal[EnumValue.b] + + class Top(BaseModel): + sub: Union[A, B] = Field(..., discriminator='l') + + assert isinstance(Top.parse_obj({'sub': {'l': EnumValue.b}}).sub, B) + with pytest.raises(ValidationError) as exc_info: + Top.parse_obj({'sub': {'l': 3}}) + assert exc_info.value.errors() == [ + { + 'loc': ('sub',), + 'msg': "No match for discriminator 'l' and value 3 (allowed values: <EnumValue.a: 1>, <EnumValue.b: 2>)", + 'type': 'value_error.discriminated_union.invalid_discriminator', + 'ctx': { + 'discriminator_key': 'l', + 'discriminator_value': 3, + 'allowed_values': '<EnumValue.a: 1>, <EnumValue.b: 2>', + }, + } + ] + + +def test_alias_different(): + class Cat(BaseModel): + pet_type: Literal['cat'] = Field(alias='U') + c: str + + class Dog(BaseModel): + pet_type: Literal['dog'] = Field(alias='T') + d: str + + with pytest.raises( + ConfigError, match=re.escape("Aliases for discriminator 'pet_type' must be the same (got T, U)") + ): + + class Model(BaseModel): + pet: Union[Cat, Dog] = Field(discriminator='pet_type') + + +def test_alias_same(): + class Cat(BaseModel): + pet_type: Literal['cat'] = Field(alias='typeOfPet') + c: str + + class Dog(BaseModel): + pet_type: Literal['dog'] = Field(alias='typeOfPet') + d: str + + class Model(BaseModel): + pet: Union[Cat, Dog] = Field(discriminator='pet_type') + + assert Model(**{'pet': {'typeOfPet': 'dog', 'd': 'milou'}}).pet.pet_type == 'dog' + + +def test_nested(): + class Cat(BaseModel): + pet_type: Literal['cat'] + name: str + + class Dog(BaseModel): + pet_type: Literal['dog'] + name: str + + CommonPet = Annotated[Union[Cat, Dog], Field(discriminator='pet_type')] + + class Lizard(BaseModel): + pet_type: Literal['reptile', 'lizard'] + name: str + + class Model(BaseModel): + pet: Union[CommonPet, Lizard] = Field(..., discriminator='pet_type') + n: int + + assert isinstance(Model(**{'pet': {'pet_type': 'dog', 'name': 'Milou'}, 'n': 5}).pet, Dog) 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 @@ -564,6 +564,53 @@ class NestedTuple(BaseModel): assert obj.dict() == {'x': (1, {'x': (2, {'x': (3, None)})})} +def test_discriminated_union_forward_ref(create_module): + @create_module + def module(): + from typing import Union + + from typing_extensions import Literal + + from pydantic import BaseModel, Field + + class Pet(BaseModel): + __root__: Union['Cat', 'Dog'] = Field(..., discriminator='type') # noqa: F821 + + class Cat(BaseModel): + type: Literal['cat'] + + class Dog(BaseModel): + type: Literal['dog'] + + with pytest.raises(ConfigError, match='you might need to call Pet.update_forward_refs()'): + module.Pet.parse_obj({'type': 'pika'}) + + module.Pet.update_forward_refs() + + with pytest.raises(ValidationError, match="No match for discriminator 'type' and value 'pika'"): + module.Pet.parse_obj({'type': 'pika'}) + + assert module.Pet.schema() == { + 'title': 'Pet', + 'discriminator': {'propertyName': 'type', 'mapping': {'cat': '#/definitions/Cat', 'dog': '#/definitions/Dog'}}, + 'anyOf': [{'$ref': '#/definitions/Cat'}, {'$ref': '#/definitions/Dog'}], + 'definitions': { + 'Cat': { + 'title': 'Cat', + 'type': 'object', + 'properties': {'type': {'title': 'Type', 'enum': ['cat'], 'type': 'string'}}, + 'required': ['type'], + }, + 'Dog': { + 'title': 'Dog', + 'type': 'object', + 'properties': {'type': {'title': 'Type', 'enum': ['dog'], 'type': 'string'}}, + 'required': ['type'], + }, + }, + } + + @skip_pre_37 def test_class_var_as_string(create_module): module = create_module( diff --git a/tests/test_main.py b/tests/test_main.py --- a/tests/test_main.py +++ b/tests/test_main.py @@ -19,7 +19,6 @@ from uuid import UUID, uuid4 import pytest -from pytest import param from pydantic import ( BaseConfig, @@ -1373,61 +1372,61 @@ class Bar(BaseModel): @pytest.mark.parametrize( 'exclude,expected,raises_match', [ - param( + pytest.param( {'foos': {0: {'a'}, 1: {'a'}}}, {'c': 3, 'foos': [{'b': 2}, {'b': 4}]}, None, id='excluding fields of indexed list items', ), - param( + pytest.param( {'foos': {'a'}}, TypeError, 'expected integer keys', id='should fail trying to exclude string keys on list field (1).', ), - param( + pytest.param( {'foos': {0: ..., 'a': ...}}, TypeError, 'expected integer keys', id='should fail trying to exclude string keys on list field (2).', ), - param( + pytest.param( {'foos': {0: 1}}, TypeError, 'Unexpected type', id='should fail using integer key to specify list item field name (1)', ), - param( + pytest.param( {'foos': {'__all__': 1}}, TypeError, 'Unexpected type', id='should fail using integer key to specify list item field name (2)', ), - param( + pytest.param( {'foos': {'__all__': {'a'}}}, {'c': 3, 'foos': [{'b': 2}, {'b': 4}]}, None, id='using "__all__" to exclude specific nested field', ), - param( + pytest.param( {'foos': {0: {'b'}, '__all__': {'a'}}}, {'c': 3, 'foos': [{}, {'b': 4}]}, None, id='using "__all__" to exclude specific nested field in combination with more specific exclude', ), - param( + pytest.param( {'foos': {'__all__'}}, {'c': 3, 'foos': []}, None, id='using "__all__" to exclude all list items', ), - param( + pytest.param( {'foos': {1, '__all__'}}, {'c': 3, 'foos': []}, None, id='using "__all__" and other items should get merged together, still excluding all list items', ), - param( + pytest.param( {'foos': {1: {'a'}, -1: {'b'}}}, {'c': 3, 'foos': [{'a': 1, 'b': 2}, {}]}, None, @@ -1458,13 +1457,13 @@ class Bar(BaseModel): @pytest.mark.parametrize( 'excludes,expected', [ - param( + pytest.param( {'bars': {0}}, {'a': 1, 'bars': [{'y': 2}, {'w': -1, 'z': 3}]}, id='excluding first item from list field using index', ), - param({'bars': {'__all__'}}, {'a': 1, 'bars': []}, id='using "__all__" to exclude all list items'), - param( + pytest.param({'bars': {'__all__'}}, {'a': 1, 'bars': []}, id='using "__all__" to exclude all list items'), + pytest.param( {'bars': {'__all__': {'w'}}}, {'a': 1, 'bars': [{'x': 1}, {'y': 2}, {'z': 3}]}, id='exclude single dict key from all list items', @@ -2094,7 +2093,7 @@ class Model(Base, some_config='new_value'): @pytest.mark.skipif(sys.version_info < (3, 10), reason='need 3.10 version') def test_new_union_origin(): - """On 3.10+, origin of `int | str` is `types.Union`, not `typing.Union`""" + """On 3.10+, origin of `int | str` is `types.UnionType`, not `typing.Union`""" class Model(BaseModel): x: int | str diff --git a/tests/test_schema.py b/tests/test_schema.py --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -27,7 +27,7 @@ from uuid import UUID import pytest -from typing_extensions import Literal +from typing_extensions import Annotated, Literal from pydantic import BaseModel, Extra, Field, ValidationError, confrozenset, conlist, conset, validator from pydantic.color import Color @@ -2626,3 +2626,254 @@ def resolve(self) -> 'Model': # noqa }, '$ref': '#/definitions/Model', } + + +def test_discriminated_union(): + class BlackCat(BaseModel): + pet_type: Literal['cat'] + color: Literal['black'] + + class WhiteCat(BaseModel): + pet_type: Literal['cat'] + color: Literal['white'] + + class Cat(BaseModel): + __root__: Union[BlackCat, WhiteCat] = Field(..., discriminator='color') + + class Dog(BaseModel): + pet_type: Literal['dog'] + + class Lizard(BaseModel): + pet_type: Literal['reptile', 'lizard'] + + class Model(BaseModel): + pet: Union[Cat, Dog, Lizard] = Field(..., discriminator='pet_type') + + assert Model.schema() == { + 'title': 'Model', + 'type': 'object', + 'properties': { + 'pet': { + 'title': 'Pet', + 'discriminator': { + 'propertyName': 'pet_type', + 'mapping': { + 'cat': '#/definitions/Cat', + 'dog': '#/definitions/Dog', + 'reptile': '#/definitions/Lizard', + 'lizard': '#/definitions/Lizard', + }, + }, + 'anyOf': [ + {'$ref': '#/definitions/Cat'}, + {'$ref': '#/definitions/Dog'}, + {'$ref': '#/definitions/Lizard'}, + ], + } + }, + 'required': ['pet'], + 'definitions': { + 'BlackCat': { + 'title': 'BlackCat', + 'type': 'object', + 'properties': { + 'pet_type': {'title': 'Pet Type', 'enum': ['cat'], 'type': 'string'}, + 'color': {'title': 'Color', 'enum': ['black'], 'type': 'string'}, + }, + 'required': ['pet_type', 'color'], + }, + 'WhiteCat': { + 'title': 'WhiteCat', + 'type': 'object', + 'properties': { + 'pet_type': {'title': 'Pet Type', 'enum': ['cat'], 'type': 'string'}, + 'color': {'title': 'Color', 'enum': ['white'], 'type': 'string'}, + }, + 'required': ['pet_type', 'color'], + }, + 'Cat': { + 'title': 'Cat', + 'discriminator': { + 'propertyName': 'color', + 'mapping': {'black': '#/definitions/BlackCat', 'white': '#/definitions/WhiteCat'}, + }, + 'anyOf': [{'$ref': '#/definitions/BlackCat'}, {'$ref': '#/definitions/WhiteCat'}], + }, + 'Dog': { + 'title': 'Dog', + 'type': 'object', + 'properties': {'pet_type': {'title': 'Pet Type', 'enum': ['dog'], 'type': 'string'}}, + 'required': ['pet_type'], + }, + 'Lizard': { + 'title': 'Lizard', + 'type': 'object', + 'properties': {'pet_type': {'title': 'Pet Type', 'enum': ['reptile', 'lizard'], 'type': 'string'}}, + 'required': ['pet_type'], + }, + }, + } + + +def test_discriminated_annotated_union(): + class BlackCatWithHeight(BaseModel): + pet_type: Literal['cat'] + color: Literal['black'] + info: Literal['height'] + black_infos: str + + class BlackCatWithWeight(BaseModel): + pet_type: Literal['cat'] + color: Literal['black'] + info: Literal['weight'] + black_infos: str + + BlackCat = Annotated[Union[BlackCatWithHeight, BlackCatWithWeight], Field(discriminator='info')] + + class WhiteCat(BaseModel): + pet_type: Literal['cat'] + color: Literal['white'] + white_infos: str + + Cat = Annotated[Union[BlackCat, WhiteCat], Field(discriminator='color')] + + class Dog(BaseModel): + pet_type: Literal['dog'] + dog_name: str + + Pet = Annotated[Union[Cat, Dog], Field(discriminator='pet_type')] + + class Model(BaseModel): + pet: Pet + number: int + + assert Model.schema() == { + 'title': 'Model', + 'type': 'object', + 'properties': { + 'pet': { + 'title': 'Pet', + 'discriminator': { + 'propertyName': 'pet_type', + 'mapping': { + 'cat': { + 'BlackCatWithHeight': {'$ref': '#/definitions/BlackCatWithHeight'}, + 'BlackCatWithWeight': {'$ref': '#/definitions/BlackCatWithWeight'}, + 'WhiteCat': {'$ref': '#/definitions/WhiteCat'}, + }, + 'dog': '#/definitions/Dog', + }, + }, + 'anyOf': [ + { + 'anyOf': [ + { + 'anyOf': [ + {'$ref': '#/definitions/BlackCatWithHeight'}, + {'$ref': '#/definitions/BlackCatWithWeight'}, + ] + }, + {'$ref': '#/definitions/WhiteCat'}, + ] + }, + {'$ref': '#/definitions/Dog'}, + ], + }, + 'number': {'title': 'Number', 'type': 'integer'}, + }, + 'required': ['pet', 'number'], + 'definitions': { + 'BlackCatWithHeight': { + 'title': 'BlackCatWithHeight', + 'type': 'object', + 'properties': { + 'pet_type': {'title': 'Pet Type', 'enum': ['cat'], 'type': 'string'}, + 'color': {'title': 'Color', 'enum': ['black'], 'type': 'string'}, + 'info': {'title': 'Info', 'enum': ['height'], 'type': 'string'}, + 'black_infos': {'title': 'Black Infos', 'type': 'string'}, + }, + 'required': ['pet_type', 'color', 'info', 'black_infos'], + }, + 'BlackCatWithWeight': { + 'title': 'BlackCatWithWeight', + 'type': 'object', + 'properties': { + 'pet_type': {'title': 'Pet Type', 'enum': ['cat'], 'type': 'string'}, + 'color': {'title': 'Color', 'enum': ['black'], 'type': 'string'}, + 'info': {'title': 'Info', 'enum': ['weight'], 'type': 'string'}, + 'black_infos': {'title': 'Black Infos', 'type': 'string'}, + }, + 'required': ['pet_type', 'color', 'info', 'black_infos'], + }, + 'WhiteCat': { + 'title': 'WhiteCat', + 'type': 'object', + 'properties': { + 'pet_type': {'title': 'Pet Type', 'enum': ['cat'], 'type': 'string'}, + 'color': {'title': 'Color', 'enum': ['white'], 'type': 'string'}, + 'white_infos': {'title': 'White Infos', 'type': 'string'}, + }, + 'required': ['pet_type', 'color', 'white_infos'], + }, + 'Dog': { + 'title': 'Dog', + 'type': 'object', + 'properties': { + 'pet_type': {'title': 'Pet Type', 'enum': ['dog'], 'type': 'string'}, + 'dog_name': {'title': 'Dog Name', 'type': 'string'}, + }, + 'required': ['pet_type', 'dog_name'], + }, + }, + } + + +def test_alias_same(): + class Cat(BaseModel): + pet_type: Literal['cat'] = Field(alias='typeOfPet') + c: str + + class Dog(BaseModel): + pet_type: Literal['dog'] = Field(alias='typeOfPet') + d: str + + class Model(BaseModel): + pet: Union[Cat, Dog] = Field(discriminator='pet_type') + number: int + + assert Model.schema() == { + 'type': 'object', + 'title': 'Model', + 'properties': { + 'number': {'title': 'Number', 'type': 'integer'}, + 'pet': { + 'anyOf': [{'$ref': '#/definitions/Cat'}, {'$ref': '#/definitions/Dog'}], + 'discriminator': { + 'mapping': {'cat': '#/definitions/Cat', 'dog': '#/definitions/Dog'}, + 'propertyName': 'typeOfPet', + }, + 'title': 'Pet', + }, + }, + 'required': ['pet', 'number'], + 'definitions': { + 'Cat': { + 'properties': { + 'c': {'title': 'C', 'type': 'string'}, + 'typeOfPet': {'enum': ['cat'], 'title': 'Typeofpet', 'type': 'string'}, + }, + 'required': ['typeOfPet', 'c'], + 'title': 'Cat', + 'type': 'object', + }, + 'Dog': { + 'properties': { + 'd': {'title': 'D', 'type': 'string'}, + 'typeOfPet': {'enum': ['dog'], 'title': 'Typeofpet', 'type': 'string'}, + }, + 'required': ['typeOfPet', 'd'], + 'title': 'Dog', + 'type': 'object', + }, + }, + } diff --git a/tests/test_tools.py b/tests/test_tools.py --- a/tests/test_tools.py +++ b/tests/test_tools.py @@ -1,11 +1,11 @@ import json -from typing import Dict, List, Mapping +from typing import Dict, List, Mapping, Union import pytest from pydantic import BaseModel, ValidationError from pydantic.dataclasses import dataclass -from pydantic.tools import parse_file_as, parse_obj_as, parse_raw_as +from pydantic.tools import parse_file_as, parse_obj_as, parse_raw_as, schema, schema_json @pytest.mark.parametrize('obj,type_,parsed', [('1', int, 1), (['1'], List[int], [1])]) @@ -98,3 +98,23 @@ class Item(BaseModel): item_data = '[{"id": 1, "name": "My Item"}]' items = parse_raw_as(List[Item], item_data) assert items == [Item(id=1, name='My Item')] + + +def test_schema(): + assert schema(Union[int, str], title='IntOrStr') == { + 'title': 'IntOrStr', + 'anyOf': [{'type': 'integer'}, {'type': 'string'}], + } + assert schema_json(Union[int, str], title='IntOrStr', indent=2) == ( + '{\n' + ' "title": "IntOrStr",\n' + ' "anyOf": [\n' + ' {\n' + ' "type": "integer"\n' + ' },\n' + ' {\n' + ' "type": "string"\n' + ' }\n' + ' ]\n' + '}' + )
Validation of fields in tagged unions creates confusing errors ### 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/jonas.obrist/playground/pydantic/pydantic python version: 3.8.3 (default, Jul 17 2020, 11:57:37) [Clang 10.0.0 ] platform: macOS-10.16-x86_64-i386-64bit optional deps. installed: ['devtools', 'dotenv', 'email-validator', 'typing-extensions'] ``` Tested with git checkout 5ccbdcb5904f35834300b01432a665c75dc02296. See [this test in my branch](https://github.com/ojii/pydantic/blob/54176644ec5494b9dd705d60c88ca2fbd64f5c36/tests/test_errors.py#L470-L491). ```py from typing import Literal, Union from pydantic import BaseModel, conint class A(BaseModel): tag: Literal["a"] class B(BaseModel): tag: Literal["b"] x: conint(ge=0, le=1) class Model(BaseModel): value: Union[A, B] Model(value={"tag": "b", "x": 2}) # this will fail with "tag must be 'a'" and "x" must be LE 1 ``` I would expect the error to be just "'x' needs to be LE 1", but the error also complains that "'tag' must be 'a'". This is somewhat related to #619
0.0
afcd15522e6a8474270e5e028bc498baffac631a
[ "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_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_discrimated_union_basemodel_instance_value", "tests/test_dataclasses.py::test_keeps_custom_properties", "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", "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_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_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_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_discriminated_union", "tests/test_schema.py::test_discriminated_annotated_union", "tests/test_schema.py::test_alias_same", "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_hyperlinks", "has_git_commit_hash", "has_added_files", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2021-02-09 23:09:12+00:00
mit
4,798
pydantic__pydantic-2338
diff --git a/pydantic/fields.py b/pydantic/fields.py --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -420,7 +420,7 @@ def prepare(self) -> None: e.g. calling it it multiple times may modify the field and configure it incorrectly. """ self._set_default_and_type() - if self.type_.__class__ == ForwardRef: + if self.type_.__class__ is ForwardRef or self.type_.__class__ is DeferredType: # self.type_ is currently a ForwardRef and there's nothing we can do now, # user will need to call model.update_forward_refs() return @@ -661,6 +661,8 @@ def validate( self, v: Any, values: Dict[str, Any], *, loc: 'LocStr', cls: Optional['ModelOrDc'] = None ) -> 'ValidateReturn': + assert self.type_.__class__ is not DeferredType + if self.type_.__class__ is ForwardRef: assert cls is not None raise ConfigError( @@ -946,3 +948,9 @@ def PrivateAttr( default, default_factory=default_factory, ) + + +class DeferredType: + """ + Used to postpone field preparation, while creating recursive generic models. + """ diff --git a/pydantic/generics.py b/pydantic/generics.py --- a/pydantic/generics.py +++ b/pydantic/generics.py @@ -9,6 +9,7 @@ Iterable, Iterator, List, + Mapping, Optional, Tuple, Type, @@ -19,7 +20,7 @@ ) from .class_validators import gather_all_validators -from .fields import FieldInfo, ModelField +from .fields import DeferredType from .main import BaseModel, create_model from .typing import display_as_type, get_args, get_origin, typing_base from .utils import all_identical, lenient_issubclass @@ -69,19 +70,15 @@ def __class_getitem__(cls: Type[GenericModelT], params: Union[Type[Any], Tuple[T if all_identical(typevars_map.keys(), typevars_map.values()) and typevars_map: return cls # if arguments are equal to parameters it's the same object - # Recursively walk class type hints and replace generic typevars - # with concrete types that were passed. + # Create new model with original model as parent inserting fields with DeferredType. + model_name = cls.__concrete_name__(params) + validators = gather_all_validators(cls) + type_hints = get_type_hints(cls).items() instance_type_hints = {k: v for k, v in type_hints if get_origin(v) is not ClassVar} - concrete_type_hints: Dict[str, Type[Any]] = { - k: replace_types(v, typevars_map) for k, v in instance_type_hints.items() - } - # Create new model with original model as parent inserting fields with - # updated type hints. - model_name = cls.__concrete_name__(params) - validators = gather_all_validators(cls) - fields = _build_generic_fields(cls.__fields__, concrete_type_hints) + fields = {k: (DeferredType(), cls.__fields__[k].field_info) for k in instance_type_hints if k in cls.__fields__} + model_module, called_globally = get_caller_frame_info() created_model = cast( Type[GenericModel], # casting ensures mypy is aware of the __concrete__ and __parameters__ attributes @@ -121,6 +118,11 @@ def __class_getitem__(cls: Type[GenericModelT], params: Union[Type[Any], Tuple[T _generic_types_cache[(cls, params)] = created_model if len(params) == 1: _generic_types_cache[(cls, params[0])] = created_model + + # Recursively walk class type hints and replace generic typevars + # with concrete types that were passed. + _prepare_model_fields(created_model, fields, instance_type_hints, typevars_map) + return created_model @classmethod @@ -140,11 +142,11 @@ def __concrete_name__(cls: Type[Any], params: Tuple[Type[Any], ...]) -> str: return f'{cls.__name__}[{params_component}]' -def replace_types(type_: Any, type_map: Dict[Any, Any]) -> Any: +def replace_types(type_: Any, type_map: Mapping[Any, Any]) -> Any: """Return type with all occurances of `type_map` keys recursively replaced with their values. :param type_: Any type, class or generic alias - :type_map: Mapping from `TypeVar` instance to concrete types. + :param type_map: Mapping from `TypeVar` instance to concrete types. :return: New type representing the basic structure of `type_` with all `typevar_map` keys recursively replaced. @@ -218,13 +220,6 @@ def iter_contained_typevars(v: Any) -> Iterator[TypeVarType]: yield from iter_contained_typevars(arg) -def _build_generic_fields( - raw_fields: Dict[str, ModelField], - concrete_type_hints: Dict[str, Type[Any]], -) -> Dict[str, Tuple[Type[Any], FieldInfo]]: - return {k: (v, raw_fields[k].field_info) for k, v in concrete_type_hints.items() if k in raw_fields} - - def get_caller_frame_info() -> Tuple[Optional[str], bool]: """ Used inside a function to check whether it was called globally @@ -241,3 +236,29 @@ def get_caller_frame_info() -> Tuple[Optional[str], bool]: return None, False frame_globals = previous_caller_frame.f_globals return frame_globals.get('__name__'), previous_caller_frame.f_locals is frame_globals + + +def _prepare_model_fields( + created_model: Type[GenericModel], + fields: Mapping[str, Any], + instance_type_hints: Mapping[str, type], + typevars_map: Mapping[Any, type], +) -> None: + """ + Replace DeferredType fields with concrete type hints and prepare them. + """ + + for key, field in created_model.__fields__.items(): + if key not in fields: + assert field.type_.__class__ is not DeferredType + # https://github.com/nedbat/coveragepy/issues/198 + continue # pragma: no cover + + assert field.type_.__class__ is DeferredType, field.type_.__class__ + + field_type_hint = instance_type_hints[key] + concrete_type = replace_types(field_type_hint, typevars_map) + field.type_ = concrete_type + field.outer_type_ = concrete_type + field.prepare() + created_model.__annotations__[key] = concrete_type
pydantic/pydantic
7cc8d254e97367082d9d53c3529c5a45f079390e
I don't think there's currently a solution for this. The most relevant discussion to this is #659, though I wouldn't all this a duplicate since that's specific to `from_orm`. The short answer is that pydantic doesn't (yet) have any solution for detecting and coping with circular references. If you have a suggestion of a solution, please comment on #659 or submit a demo PR. I have no idea off the top of my head, how hard it would be to use the same approach for `from_orm`, `parse_obj` and our case above - or if they're even particularly linked.
diff --git a/tests/test_generics.py b/tests/test_generics.py --- a/tests/test_generics.py +++ b/tests/test_generics.py @@ -1015,3 +1015,27 @@ class Model(GenericModel, Generic[T, U]): Model[str, U].__concrete__ is False Model[str, U].__parameters__ == [U] Model[str, int].__concrete__ is False + + +@skip_36 +def test_generic_recursive_models(create_module): + @create_module + def module(): + from typing import Generic, TypeVar, Union + + from pydantic.generics import GenericModel + + T = TypeVar('T') + + class Model1(GenericModel, Generic[T]): + ref: 'Model2[T]' + + class Model2(GenericModel, Generic[T]): + ref: Union[T, Model1[T]] + + Model1.update_forward_refs() + + Model1 = module.Model1 + Model2 = module.Model2 + result = Model1[str].parse_obj(dict(ref=dict(ref=dict(ref=dict(ref=123))))) + assert result == Model1(ref=Model2(ref=Model1(ref=Model2(ref='123'))))
Recursive model: maximum recursion depth exceeded # Bug `RecursionError: maximum recursion depth exceeded while calling a Python object` I get this error message, when using recursive models. ```py class A(BaseModel): ... class B(A): key: List[B] ... ``` Using ```py from __future__ import annotations from typings import ForwardRef B = ForwardRef('B') ... B.update_forward_refs() ``` does not make a difference aswell. Issue #531 did not have any clue on how to solve this. The docs don't cover the usage with lists. Hope you understand my issue here :smile: Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.4 pydantic compiled: True install path: /usr/local/lib/python3.8/site-packages/pydantic python version: 3.8.2 (default, Feb 26 2020, 14:58:38) [GCC 8.3.0] platform: Linux-5.3.0-45-generic-x86_64-with-glibc2.2.5 optional deps. installed: ['email-validator'] ``` EDIT: Just saw that the issue is pointed to in #524, but there is no response. Maybe there is a solution for it now?
0.0
7cc8d254e97367082d9d53c3529c5a45f079390e
[ "tests/test_generics.py::test_generic_recursive_models" ]
[ "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_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" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-02-10 19:55:48+00:00
mit
4,799
pydantic__pydantic-2348
diff --git a/pydantic/schema.py b/pydantic/schema.py --- a/pydantic/schema.py +++ b/pydantic/schema.py @@ -1,5 +1,6 @@ import re import warnings +from collections import defaultdict from datetime import date, datetime, time, timedelta from decimal import Decimal from enum import Enum @@ -64,12 +65,12 @@ from .typing import ( NONE_TYPES, ForwardRef, + all_literal_values, get_args, get_origin, is_callable_type, is_literal_type, is_namedtuple, - literal_values, ) from .utils import ROOT_KEY, get_model, lenient_issubclass, sequence_like @@ -789,19 +790,21 @@ def field_singleton_schema( # noqa: C901 (ignore complexity) f_schema['const'] = field.default field_type = field.type_ if is_literal_type(field_type): - values = literal_values(field_type) - if len(values) > 1: + values = all_literal_values(field_type) + + if len({v.__class__ for v in values}) > 1: return field_schema( - multivalue_literal_field_for_schema(values, field), + multitypes_literal_field_for_schema(values, field), by_alias=by_alias, model_name_map=model_name_map, ref_prefix=ref_prefix, ref_template=ref_template, known_models=known_models, ) - literal_value = values[0] - field_type = literal_value.__class__ - f_schema['const'] = literal_value + + # All values have the same type + field_type = values[0].__class__ + f_schema['enum'] = list(values) if lenient_issubclass(field_type, Enum): enum_name = model_name_map[field_type] @@ -859,10 +862,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: ModelField) -> ModelField: +def multitypes_literal_field_for_schema(values: Tuple[Any, ...], field: ModelField) -> ModelField: + """ + To support `Literal` with values of different types, we split it into multiple `Literal` with same type + e.g. `Literal['qwe', 'asd', 1, 2]` becomes `Union[Literal['qwe', 'asd'], Literal[1, 2]]` + """ + literal_distinct_types = defaultdict(list) + for v in values: + literal_distinct_types[v.__class__].append(v) + distinct_literals = (Literal[tuple(same_type_values)] for same_type_values in literal_distinct_types.values()) + return ModelField( name=field.name, - type_=Union[tuple(Literal[value] for value in values)], # type: ignore + type_=Union[tuple(distinct_literals)], # type: ignore class_validators=field.class_validators, model_config=field.model_config, default=field.default, diff --git a/pydantic/typing.py b/pydantic/typing.py --- a/pydantic/typing.py +++ b/pydantic/typing.py @@ -203,7 +203,7 @@ def get_args(tp: Type[Any]) -> Tuple[Any, ...]: 'resolve_annotations', 'is_callable_type', 'is_literal_type', - 'literal_values', + 'all_literal_values', 'is_namedtuple', 'is_typeddict', 'is_new_type',
pydantic/pydantic
b7a8ef25c667b5dd4c4cd0b109c6625d1a57139a
This is not really a bug in Pydantic. Pydantic generates valid JSON Schema. OpenAPI uses an old version of JSON Schema that only supports enums. But you can change your model to use an enum instead: https://pydantic-docs.helpmanual.io/usage/types/#enums-and-choices It achieves the same and will generate a JSON Schema with enums, that is valid with OpenAPI. Should we change pydantic so literal with multiple choices matches enum? @tiangolo I agree, my concern is more about the benefit of the Literal type as a one-liner choice on a Pydantic/FastAPI/Swagger UI context. @samuelcolvin If it breaks too many things, I would suggest a simple note in the documentation to avoid this unexpected behaviour (Literal with one element works well in fastapi context but not with multiple elements) Please add a pr to improve the documentation. We should change literals in V2. > Should we change pydantic so literal with multiple choices matches enum? @samuelcolvin actually that makes sense, a `Literal` generates a JSON Schema `const`, and it could only have a single value. So, yes, a multi-valued `Literal` *should* create a JSON Schema equivalent to an enum. okay, do you think the change represents a "breaking change" that needs to wait for v2, or a bug fix than can go out in a minor version? Sorry for the delay (still figuring out how to handle GitHub email notifications), I think that looks like a "bug fix" or extra feature that could go in a minor version. Is there any progress? I have the same problem. Not yet, would you like to submit a PR. Hi guys, thanks for the research on this topics. For us, this is right now a blocker to go to production (not fulfilling good practices in documentation)... So would you mind to provide me a small hint on where to start in the code, I will take a look and let see if I can do a PR 😊 Thanks again for the efforts! @JavierMartinezAlc it looks like it is implemented [here](https://github.com/samuelcolvin/pydantic/blob/master/pydantic/schema.py#L778) and/or [there](https://github.com/samuelcolvin/pydantic/blob/master/pydantic/schema.py#L834)
diff --git a/tests/test_schema.py b/tests/test_schema.py --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -1759,14 +1759,22 @@ class Model(BaseModel): a: Literal[1] b: Literal['a'] c: Literal['a', 1] + d: Literal['a', Literal['b'], 1, 2] assert Model.schema() == { 'properties': { - 'a': {'title': 'A', 'type': 'integer', 'const': 1}, - 'b': {'title': 'B', 'type': 'string', 'const': 'a'}, - 'c': {'anyOf': [{'type': 'string', 'const': 'a'}, {'type': 'integer', 'const': 1}], 'title': 'C'}, + 'a': {'title': 'A', 'type': 'integer', 'enum': [1]}, + 'b': {'title': 'B', 'type': 'string', 'enum': ['a']}, + 'c': {'title': 'C', 'anyOf': [{'type': 'string', 'enum': ['a']}, {'type': 'integer', 'enum': [1]}]}, + 'd': { + 'title': 'D', + 'anyOf': [ + {'type': 'string', 'enum': ['a', 'b']}, + {'type': 'integer', 'enum': [1, 2]}, + ], + }, }, - 'required': ['a', 'b', 'c'], + 'required': ['a', 'b', 'c', 'd'], 'title': 'Model', 'type': 'object', }
Multi-value Literal isn't compliant with OpenAPI Multi-value Literal returns `const` in the JSON sub-schema of an `anyOf`, which isn't supported by OpenAPI: > anyOf – the subschemas must be OpenAPI schemas and not standard JSON Schemas. Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.4 pydantic compiled: False install path: /Users/[...]/venv/lib/python3.7/site-packages/pydantic python version: 3.7.4 (default, Sep 7 2019, 18:27:02) [Clang 10.0.1 (clang-1001.0.46.4)] platform: Darwin-18.7.0-x86_64-i386-64bit optional deps. installed: ['typing-extensions'] ``` # Code to reproduce ```python from pydantic import BaseModel from typing_extensions import Literal class FooBar(BaseModel): values: Literal["value_1", "value_2"] print(FooBar.schema_json(indent=2)) ``` output: ``` { "title": "FooBar", "type": "object", "properties": { "values": { "title": "Values", "anyOf": [ { "const": "value_1", "type": "string" }, { "const": "value_2", "type": "string" } ] } }, "required": [ "values" ] } ``` Literal with only one value is OpenAPI compliant btw This issue is linked to: https://github.com/tiangolo/fastapi/issues/562, https://github.com/samuelcolvin/pydantic/pull/649 (the simple `enum` would work well)
0.0
b7a8ef25c667b5dd4c4cd0b109c6625d1a57139a
[ "tests/test_schema.py::test_literal_schema" ]
[ "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_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_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" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-02-12 16:42:51+00:00
mit
4,800
pydantic__pydantic-2356
diff --git a/docs/examples/model_config_class_kwargs.py b/docs/examples/model_config_class_kwargs.py new file mode 100644 --- /dev/null +++ b/docs/examples/model_config_class_kwargs.py @@ -0,0 +1,11 @@ +from pydantic import BaseModel, ValidationError, Extra + + +class Model(BaseModel, extra=Extra.forbid): + a: str + + +try: + Model(a='spam', b='oh no') +except ValidationError as e: + print(e) diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -168,18 +168,18 @@ def prepare_field(cls, field: 'ModelField') -> None: pass -def inherit_config(self_config: 'ConfigType', parent_config: 'ConfigType') -> 'ConfigType': - namespace = {} +def inherit_config(self_config: 'ConfigType', parent_config: 'ConfigType', **namespace: Any) -> 'ConfigType': if not self_config: - base_classes = (parent_config,) + base_classes: Tuple['ConfigType', ...] = (parent_config,) elif self_config == parent_config: base_classes = (self_config,) else: - base_classes = self_config, parent_config # type: ignore - namespace['json_encoders'] = { - **getattr(parent_config, 'json_encoders', {}), - **getattr(self_config, 'json_encoders', {}), - } + base_classes = self_config, parent_config + + namespace['json_encoders'] = { + **getattr(parent_config, 'json_encoders', {}), + **getattr(self_config, 'json_encoders', {}), + } return type('Config', base_classes, namespace) @@ -251,7 +251,12 @@ def __new__(mcs, name, bases, namespace, **kwargs): # noqa C901 private_attributes.update(base.__private_attributes__) class_vars.update(base.__class_vars__) - config = inherit_config(namespace.get('Config'), config) + config_kwargs = {key: kwargs.pop(key) for key in kwargs.keys() & BaseConfig.__dict__.keys()} + config_from_namespace = namespace.get('Config') + if config_kwargs and config_from_namespace: + raise TypeError('Specifying config in two places is ambiguous, use either Config attribute or class kwargs') + config = inherit_config(config_from_namespace, config, **config_kwargs) + validators = inherit_validators(extract_validators(namespace), validators) vg = ValidatorGroup(validators)
pydantic/pydantic
fc18f8ef3490c5f0940de12268fb45e6ac9642d1
I saw this the other day on typed dicts, which python versions support this? I'm keen if the implementation isn't too complicated. It's supported in 3.6+ for sure. Great, I'll make a PR soon then! BTW, was this issue closed by accident?
diff --git a/tests/test_main.py b/tests/test_main.py --- a/tests/test_main.py +++ b/tests/test_main.py @@ -1551,3 +1551,32 @@ class Item(BaseModel): assert id(image_1) == id(item.images[0]) assert id(image_2) == id(item.images[1]) + + +def test_class_kwargs_config(): + class Base(BaseModel, extra='forbid', alias_generator=str.upper): + a: int + + assert Base.__config__.extra is Extra.forbid + assert Base.__config__.alias_generator is str.upper + assert Base.__fields__['a'].alias == 'A' + + class Model(Base, extra='allow'): + b: int + + assert Model.__config__.extra is Extra.allow # overwritten as intended + assert Model.__config__.alias_generator is str.upper # inherited as intended + assert Model.__fields__['b'].alias == 'B' # alias_generator still works + + +def test_class_kwargs_config_and_attr_conflict(): + + with pytest.raises( + TypeError, match='Specifying config in two places is ambiguous, use either Config attribute or class kwargs' + ): + + class Model(BaseModel, extra='allow'): + b: int + + class Config: + extra = 'forbid'
Configure models through class kwargs ### 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 feature/change is needed * [x] After submitting this, I commit to one of: * Look through open issues and helped at least one other person * Hit the "watch" button on this repo to receive notifications and I commit to help at least 2 people that ask questions in the future * Implement a Pull Request for a confirmed bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ```py pydantic version: 1.6.1 pydantic compiled: True install path: /Users/rocky/.local/share/virtualenvs/superapp-search-hVQXXu_u/lib/python3.8/site-packages/pydantic python version: 3.8.7 (v3.8.7:6503f05dd5, Dec 21 2020, 12:45:15) [Clang 6.0 (clang-600.0.57)] platform: macOS-10.16-x86_64-i386-64bit optional deps. installed: ['typing-extensions'] ``` # Feature Request Allow to configure models through class kwargs, allowing more elegant and compact code ```py from pydantic import BaseModel class Model(BaseModel, alias_generator=str.upper): foo: int bar: int ``` == ```py class Model(BaseModel) foo: int bar: int class Config: alias_generator = str.upper ``` Will be happy to implement this myself, once feature request is accepted.
0.0
fc18f8ef3490c5f0940de12268fb45e6ac9642d1
[ "tests/test_main.py::test_class_kwargs_config", "tests/test_main.py::test_class_kwargs_config_and_attr_conflict" ]
[ "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_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_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_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_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", "tests/test_main.py::test_model_export_dict_exclusion", "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_inherited_model_field_copy", "tests/test_main.py::test_inherited_model_field_untouched" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2021-02-13 12:54:33+00:00
mit
4,801
pydantic__pydantic-2366
diff --git a/pydantic/typing.py b/pydantic/typing.py --- a/pydantic/typing.py +++ b/pydantic/typing.py @@ -289,10 +289,16 @@ def resolve_annotations(raw_annotations: Dict[str, Type[Any]], module_name: Opti Resolve string or ForwardRef annotations into type objects if possible. """ + base_globals: Optional[Dict[str, Any]] = None if module_name: - base_globals: Optional[Dict[str, Any]] = sys.modules[module_name].__dict__ - else: - base_globals = None + try: + module = sys.modules[module_name] + except KeyError: + # happens occasionally, see https://github.com/samuelcolvin/pydantic/issues/2363 + pass + else: + base_globals = module.__dict__ + annotations = {} for name, value in raw_annotations.items(): if isinstance(value, str):
pydantic/pydantic
cc3010c80d5c635680ca1cad35d4d5a9bf3e219b
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 @@ -1,3 +1,4 @@ +import importlib.util import sys from collections.abc import Hashable from decimal import Decimal @@ -1773,3 +1774,22 @@ def get_double_a(self) -> float: assert model.a == 10.2 assert model.b == 10 return model.get_double_a() == 20.2 + + +def test_resolve_annotations_module_missing(tmp_path): + # see https://github.com/samuelcolvin/pydantic/issues/2363 + file_path = tmp_path / 'module_to_load.py' + # language=Python + file_path.write_text( + """ +from pydantic import BaseModel +class User(BaseModel): + id: int + name = 'Jane Doe' +""" + ) + + spec = importlib.util.spec_from_file_location('my_test_module', file_path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + assert module.User(id=12).dict() == {'id': 12, 'name': 'Jane Doe'}
Issue with BaseModel if used with importlib ### 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.7.3 pydantic compiled: True install path: /opt/conda/lib/python3.8/site-packages/pydantic python version: 3.8.2 (default, Mar 25 2020, 17:03:02) [GCC 7.3.0] platform: Linux-4.15.0-130-generic-x86_64-with-glibc2.10 optional deps. installed: ['typing-extensions'] ``` If I'm trying to load a module using `importlib` where a BaseModel is used then execution is crashed with the following traceback: ``` Traceback (most recent call last): File "loader.py", line 13, in <module> m = load_module("module_to_load.py") File "loader.py", line 7, in load_module spec.loader.exec_module(module) # type: ignore[union-attr] File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "module_to_load.py", line 4, in <module> class User(BaseModel): File "pydantic/main.py", line 274, in pydantic.main.ModelMetaclass.__new__ File "pydantic/typing.py", line 293, in pydantic.typing.resolve_annotations def __copy__(self): ``` How to repro: 1) create `loader.py` file with the following content ```python import importlib.util def load_module(fpath): spec = importlib.util.spec_from_file_location("mymodule", fpath) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) # type: ignore[union-attr] return module if __name__ == "__main__": m = load_module("module_to_load.py") print(m) m.foo() ``` 2) create `module_to_load.py` : ```python from pydantic import BaseModel class User(BaseModel): id: int name = 'Jane Doe' def foo(): print(User(id=12, name="test")) ``` 3) Run `python loader.py` As use-case may seem strange, I'm a bit hestiating between a bug and wrong usage, but in the latter case, error message is unclear at all. Important part is that I have to import the module in this way and not in any other more standard python way in which pydantic indeed work without any issue. Thanks EDIT: Indeed, if we add `sys.modules["mymodule"] = module` to `load_module` as suggested [here](https://docs.python.org/3/library/importlib.html?highlight=exec_module#importing-a-source-file-directly), there is no issue, anymore. I have to figure out what would be the impact of doing that for my goal.
0.0
cc3010c80d5c635680ca1cad35d4d5a9bf3e219b
[ "tests/test_edge_cases.py::test_resolve_annotations_module_missing" ]
[ "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_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_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_fields_deprecated", "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_side_effect", "tests/test_edge_cases.py::test_default_factory_validator_child", "tests/test_edge_cases.py::test_cython_function_untouched" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2021-02-15 11:53:18+00:00
mit
4,802
pydantic__pydantic-2384
diff --git a/docs/examples/dataclasses_default_schema.py b/docs/examples/dataclasses_default_schema.py --- a/docs/examples/dataclasses_default_schema.py +++ b/docs/examples/dataclasses_default_schema.py @@ -1,5 +1,7 @@ import dataclasses -from typing import List +from typing import List, Optional + +from pydantic import Field from pydantic.dataclasses import dataclass @@ -8,6 +10,11 @@ class User: id: int name: str = 'John Doe' friends: List[int] = dataclasses.field(default_factory=lambda: [0]) + age: Optional[int] = dataclasses.field( + default=None, + metadata=dict(title='The age of the user', description='do not lie!') + ) + height: Optional[int] = Field(None, title='The height in cm', ge=50, le=300) user = User(id='42') diff --git a/pydantic/dataclasses.py b/pydantic/dataclasses.py --- a/pydantic/dataclasses.py +++ b/pydantic/dataclasses.py @@ -3,14 +3,14 @@ from .class_validators import gather_all_validators from .error_wrappers import ValidationError from .errors import DataclassTypeError -from .fields import Required +from .fields import Field, FieldInfo, Required, Undefined from .main import create_model, validate_model from .typing import resolve_annotations from .utils import ClassAttribute if TYPE_CHECKING: from .main import BaseConfig, BaseModel # noqa: F401 - from .typing import CallableGenerator + from .typing import CallableGenerator, NoArgAnyCallable DataclassT = TypeVar('DataclassT', bound='Dataclass') @@ -19,6 +19,7 @@ class Dataclass: __initialised__: bool __post_init_original__: Optional[Callable[..., None]] __processed__: Optional[ClassAttribute] + __has_field_info_default__: bool # whether or not a `pydantic.Field` is used as default value def __init__(self, *args: Any, **kwargs: Any) -> None: pass @@ -80,6 +81,30 @@ def is_builtin_dataclass(_cls: Type[Any]) -> bool: return not hasattr(_cls, '__processed__') and dataclasses.is_dataclass(_cls) +def _generate_pydantic_post_init( + post_init_original: Optional[Callable[..., None]], post_init_post_parse: Optional[Callable[..., None]] +) -> Callable[..., None]: + def _pydantic_post_init(self: 'Dataclass', *initvars: Any) -> None: + if post_init_original is not None: + post_init_original(self, *initvars) + + if getattr(self, '__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! + input_data = {k: v for k, v in self.__dict__.items() if not isinstance(v, FieldInfo)} + else: + input_data = self.__dict__ + d, _, validation_error = validate_model(self.__pydantic_model__, input_data, 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: + post_init_post_parse(self, *initvars) + + return _pydantic_post_init + + def _process_class( _cls: Type[Any], init: bool, @@ -100,16 +125,7 @@ def _process_class( post_init_post_parse = getattr(_cls, '__post_init_post_parse__', None) - def _pydantic_post_init(self: 'Dataclass', *initvars: Any) -> None: - if post_init_original is not None: - post_init_original(self, *initvars) - 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: - post_init_post_parse(self, *initvars) + _pydantic_post_init = _generate_pydantic_post_init(post_init_original, post_init_post_parse) # If the class is already a dataclass, __post_init__ will not be called automatically # so no validation will be added. @@ -144,22 +160,31 @@ def _pydantic_post_init(self: 'Dataclass', *initvars: Any) -> None: ) cls.__processed__ = ClassAttribute('__processed__', True) - fields: Dict[str, Any] = {} + field_definitions: Dict[str, Any] = {} for field in dataclasses.fields(cls): + default: Any = Undefined + default_factory: Optional['NoArgAnyCallable'] = None + field_info: FieldInfo - if field.default != dataclasses.MISSING: - field_value = field.default + if field.default is not dataclasses.MISSING: + default = field.default # mypy issue 7020 and 708 - elif field.default_factory != dataclasses.MISSING: # type: ignore - field_value = field.default_factory() # type: ignore + elif field.default_factory is not dataclasses.MISSING: # type: ignore + default_factory = field.default_factory # type: ignore + else: + default = Required + + if isinstance(default, FieldInfo): + field_info = default + cls.__has_field_info_default__ = True else: - field_value = Required + field_info = Field(default=default, default_factory=default_factory, **field.metadata) - fields[field.name] = (field.type, field_value) + field_definitions[field.name] = (field.type, field_info) validators = gather_all_validators(cls) cls.__pydantic_model__ = create_model( - cls.__name__, __config__=config, __module__=_cls.__module__, __validators__=validators, **fields + cls.__name__, __config__=config, __module__=_cls.__module__, __validators__=validators, **field_definitions ) cls.__initialised__ = False
pydantic/pydantic
c8883e34db8b42261617f45bf5e46f616dd5862c
Hi @m10d This is not a bug but a feature request related to https://github.com/samuelcolvin/pydantic/issues/470. There is no current support of what you're asking for _pydantic_ `dataclass` But I agree using `metadata` kwarg of `field` would make sense
diff --git a/tests/test_dataclasses.py b/tests/test_dataclasses.py --- a/tests/test_dataclasses.py +++ b/tests/test_dataclasses.py @@ -429,7 +429,7 @@ class User: assert fields['id'].default is None assert fields['aliases'].required is False - assert fields['aliases'].default == {'John': 'Joey'} + assert fields['aliases'].default_factory() == {'John': 'Joey'} def test_default_factory_singleton_field(): @@ -456,6 +456,10 @@ class User: name: str = 'John Doe' aliases: Dict[str, str] = dataclasses.field(default_factory=lambda: {'John': 'Joey'}) signup_ts: datetime = None + age: Optional[int] = dataclasses.field( + default=None, metadata=dict(title='The age of the user', description='do not lie!') + ) + height: Optional[int] = pydantic.Field(None, title='The height in cm', ge=50, le=300) user = User(id=123) assert user.__pydantic_model__.schema() == { @@ -466,11 +470,21 @@ class User: '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'}, + 'age': { + 'title': 'The age of the user', + 'description': 'do not lie!', + 'type': 'integer', + }, + 'height': { + 'title': 'The height in cm', + 'minimum': 50, + 'maximum': 300, + 'type': 'integer', + }, }, 'required': ['id'], }
Use metadata in dataclass field to populate pydantic 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.7.3 pydantic compiled: True install path: $VENV_PATH/lib/python3.8/site-packages/pydantic python version: 3.8.5 (default, Jul 28 2020, 12:59:40) [GCC 9.3.0] platform: Linux-5.8.0-43-generic-x86_64-with-glibc2.29 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 from pydantic import BaseModel, Field from pydantic.dataclasses import dataclass from dataclasses import field class DescriptionFromBasemodel(BaseModel): descr_present: int = Field( 42, title='my title', description='descr text',) print(DescriptionFromBasemodel.schema_json(indent=4)) @dataclass class DataclassWithDescription: descr_missing: int = field(metadata=dict( title="my title", description="descr text")) print(DataclassWithDescription.__pydantic_model__.schema_json(indent=4)) ``` outputs as expected for raw basemodel: ``` { "title": "DescriptionFromBasemodel", "type": "object", "properties": { "descr_present": { "title": "my title", "description": "descr text", "default": 42, "type": "integer" } } } ``` but for the model generated from the dataclass, no attrs are preserved: ```{ "title": "DataclassWithDescription", "type": "object", "properties": { "descr_missing": { "title": "Descr Missing", "type": "integer" } }, "required": [ "descr_missing" ] } ```
0.0
c8883e34db8b42261617f45bf5e46f616dd5862c
[ "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_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_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_singleton_field", "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" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-02-22 00:09:28+00:00
mit
4,803
pydantic__pydantic-2392
diff --git a/pydantic/typing.py b/pydantic/typing.py --- a/pydantic/typing.py +++ b/pydantic/typing.py @@ -221,6 +221,7 @@ def get_args(tp: Type[Any]) -> Tuple[Any, ...]: 'CallableGenerator', 'ReprArgs', 'CallableGenerator', + 'GenericAlias', 'get_args', 'get_origin', 'typing_base', diff --git a/pydantic/utils.py b/pydantic/utils.py --- a/pydantic/utils.py +++ b/pydantic/utils.py @@ -24,7 +24,7 @@ no_type_check, ) -from .typing import NoneType, display_as_type +from .typing import GenericAlias, NoneType, display_as_type from .version import version_info if TYPE_CHECKING: @@ -149,7 +149,12 @@ def validate_field_name(bases: List[Type['BaseModel']], field_name: str) -> None def lenient_issubclass(cls: Any, class_or_tuple: Union[Type[Any], Tuple[Type[Any], ...]]) -> bool: - return isinstance(cls, type) and issubclass(cls, class_or_tuple) + try: + return isinstance(cls, type) and issubclass(cls, class_or_tuple) + except TypeError: + if isinstance(cls, GenericAlias): + return False + raise # pragma: no cover def in_ipython() -> bool:
pydantic/pydantic
eab9d054733537a21c70aa9afe89d0a552537ecd
diff --git a/tests/test_utils.py b/tests/test_utils.py --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -109,6 +109,14 @@ class A(str): assert lenient_issubclass(A, str) is True [email protected](sys.version_info < (3, 9), reason='generic aliases are not available in python < 3.9') +def test_lenient_issubclass_with_generic_aliases(): + from collections.abc import Mapping + + # should not raise an error here: + assert lenient_issubclass(list[str], Mapping) is False + + def test_lenient_issubclass_is_lenient(): assert lenient_issubclass('a', 'a') is False
lenient_issubclass does not work for generic 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 # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.7.3 pydantic compiled: False install path: /home/user/pydantic/pydantic python version: 3.9.0 (default, Nov 15 2020, 14:28:56) [GCC 7.3.0] platform: Linux-5.4.0-65-generic-x86_64-with-glibc2.31 optional deps. installed: ['devtools', 'dotenv', 'email-validator', 'typing-extensions'] ``` Using `lenient_issubclass` breaks for `GernicAlias` types. This is important in python >= 3.9 as the typing become the default for defining types. Reproducible example: ```py from pydantic.utils import lenient_issubclass from collections.abc import Mapping # should not raise an error here: assert lenient_issubclass(list[str], Mapping) is False ``` raises: ``` if lenient_issubclass(param.annotation, Request): \lib\site-packages\pydantic\utils.py:151: in lenient_issubclass return isinstance(cls, type) and issubclass(cls, class_or_tuple) \lib\abc.py:102: in __subclasscheck__ return _abc_subclasscheck(cls, subclass) E TypeError: issubclass() arg 1 must be a class ```
0.0
eab9d054733537a21c70aa9afe89d0a552537ecd
[ "tests/test_utils.py::test_lenient_issubclass_with_generic_aliases" ]
[ "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_display_as_type_generic_alias", "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_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_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_version_strict", "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_get_args[ConstrainedListValue-output_value0]", "tests/test_utils.py::test_get_args[ConstrainedList-output_value1]", "tests/test_utils.py::test_get_args[input_value2-output_value2]", "tests/test_utils.py::test_get_args[input_value3-output_value3]", "tests/test_utils.py::test_get_args[int-output_value4]", "tests/test_utils.py::test_get_args[input_value5-output_value5]", "tests/test_utils.py::test_get_args[input_value6-output_value6]", "tests/test_utils.py::test_get_args[input_value7-output_value7]", "tests/test_utils.py::test_get_args[input_value8-output_value8]", "tests/test_utils.py::test_resolve_annotations_no_module", "tests/test_utils.py::test_all_identical" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2021-02-24 09:31:21+00:00
mit
4,804
pydantic__pydantic-2421
diff --git a/pydantic/fields.py b/pydantic/fields.py --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -538,6 +538,7 @@ def _type_analysis(self) -> None: # noqa: C901 (ignore complexity) elif len(args) == 2 and args[1] is Ellipsis: # e.g. Tuple[int, ...] self.type_ = args[0] self.shape = SHAPE_TUPLE_ELLIPSIS + self.sub_fields = [self._create_sub_type(args[0], f'{self.name}_0')] elif args == ((),): # Tuple[()] means empty tuple self.shape = SHAPE_TUPLE self.type_ = Any
pydantic/pydantic
a8d50aef0c375374302d050fbe16703d33aaeb86
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 @@ -203,12 +203,19 @@ class Model(BaseModel): empty_tuple: Tuple[()] simple_tuple: tuple = None tuple_of_different_types: Tuple[int, float, str, bool] = None + tuple_of_single_tuples: Tuple[Tuple[int], ...] = () - m = Model(empty_tuple=[], simple_tuple=[1, 2, 3, 4], tuple_of_different_types=[4, 3, 2, 1]) + m = Model( + empty_tuple=[], + simple_tuple=[1, 2, 3, 4], + tuple_of_different_types=[4, 3, 2, 1], + tuple_of_single_tuples=(('1',), (2,)), + ) assert m.dict() == { 'empty_tuple': (), 'simple_tuple': (1, 2, 3, 4), 'tuple_of_different_types': (4, 3.0, '2', True), + 'tuple_of_single_tuples': ((1,), (2,)), }
Variable length tuples not working in 1.8.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 It wasn't clear to me from the description of the breaking changes described in 1.8.0 whether it is expected that variable length tuples should now be handled differently, but I'm seeing something similar to #2132 when nesting generics inside of a variable length tuple: ```python from typing import Tuple from pydantic import BaseModel # works class A(BaseModel): t: Tuple[Tuple[int]] = () # works class B(BaseModel): t: Tuple[Tuple[int, ...]] = () # fails class C(BaseModel): t: Tuple[Tuple[int], ...] = () ``` ```pytb TypeError Traceback (most recent call last) ~/miniconda3/envs/napdev/lib/python3.8/site-packages/pydantic/validators.cpython-38-darwin.so in pydantic.validators.find_validators() TypeError: issubclass() arg 1 must be a class During handling of the above exception, another exception occurred: RuntimeError Traceback (most recent call last) <ipython-input-3-3f541325cc4d> in <module> ----> 1 class C(BaseModel): 2 t: Tuple[Tuple[int], ...] = () 3 ~/miniconda3/envs/napdev/lib/python3.8/site-packages/pydantic/main.cpython-38-darwin.so in pydantic.main.ModelMetaclass.__new__() ~/miniconda3/envs/napdev/lib/python3.8/site-packages/pydantic/fields.cpython-38-darwin.so in pydantic.fields.ModelField.infer() ~/miniconda3/envs/napdev/lib/python3.8/site-packages/pydantic/fields.cpython-38-darwin.so in pydantic.fields.ModelField.__init__() ~/miniconda3/envs/napdev/lib/python3.8/site-packages/pydantic/fields.cpython-38-darwin.so in pydantic.fields.ModelField.prepare() ~/miniconda3/envs/napdev/lib/python3.8/site-packages/pydantic/fields.cpython-38-darwin.so in pydantic.fields.ModelField.populate_validators() ~/miniconda3/envs/napdev/lib/python3.8/site-packages/pydantic/validators.cpython-38-darwin.so in find_validators() RuntimeError: error checking inheritance of typing.Tuple[int] (type: Tuple[int]) ``` Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.8 pydantic compiled: True install path: ~/miniconda3/envs/napdev/lib/python3.8/site-packages/pydantic python version: 3.8.6 | packaged by conda-forge | (default, Jan 25 2021, 23:22:12) [Clang 11.0.1 ] platform: macOS-10.15.7-x86_64-i386-64bit optional deps. installed: ['typing-extensions'] ```
0.0
a8d50aef0c375374302d050fbe16703d33aaeb86
[ "tests/test_edge_cases.py::test_tuple_more" ]
[ "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_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_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_side_effect", "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" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2021-02-27 11:17:45+00:00
mit
4,805
pydantic__pydantic-2423
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 slots: SetStr = namespace.get('__slots__', ()) slots = {slots} if isinstance(slots, str) else set(slots) class_vars: SetStr = set() + hash_func: Optional[Callable[[Any], int]] = None for base in reversed(bases): if _is_base_model_class_defined and issubclass(base, BaseModel) and base != BaseModel: @@ -241,6 +242,7 @@ def __new__(mcs, name, bases, namespace, **kwargs): # noqa C901 post_root_validators += base.__post_root_validators__ private_attributes.update(base.__private_attributes__) class_vars.update(base.__class_vars__) + hash_func = base.__hash__ config_kwargs = {key: kwargs.pop(key) for key in kwargs.keys() & BaseConfig.__dict__.keys()} config_from_namespace = namespace.get('Config') @@ -332,6 +334,9 @@ def is_untouched(v: Any) -> bool: json_encoder = pydantic_encoder pre_rv_new, post_rv_new = extract_root_validators(namespace) + if hash_func is None: + hash_func = generate_hash_function(config.frozen) + exclude_from_namespace = fields | private_attributes.keys() | {'__slots__'} new_namespace = { '__config__': config, @@ -344,7 +349,7 @@ def is_untouched(v: Any) -> bool: '__custom_root_type__': _custom_root_type, '__private_attributes__': private_attributes, '__slots__': slots | private_attributes.keys(), - '__hash__': generate_hash_function(config.frozen), + '__hash__': hash_func, '__class_vars__': class_vars, **{n: v for n, v in namespace.items() if n not in exclude_from_namespace}, }
pydantic/pydantic
a8d50aef0c375374302d050fbe16703d33aaeb86
diff --git a/tests/test_main.py b/tests/test_main.py --- a/tests/test_main.py +++ b/tests/test_main.py @@ -395,6 +395,27 @@ class TestModel(BaseModel): assert "unhashable type: 'TestModel'" in exc_info.value.args[0] +def test_with_declared_hash(): + class Foo(BaseModel): + x: int + + def __hash__(self): + return self.x ** 2 + + class Bar(Foo): + y: int + + def __hash__(self): + return self.y ** 3 + + class Buz(Bar): + z: int + + assert hash(Foo(x=2)) == 4 + assert hash(Bar(x=2, y=3)) == 27 + assert hash(Buz(x=2, y=3, z=4)) == 27 + + def test_frozen_with_hashable_fields_are_hashable(): class TestModel(BaseModel): a: int = 10
__hash__() is squashed on subclass ### 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 worked in pydantic 1.7.3 (version info shown below), but fails with pydantic 1.8: ```py from pydantic import BaseModel class Foo(BaseModel): x: int # Failed attempt to fix; see below # __slots__ = ("__hash__",) def __hash__(self): return self.x ** 2 f = Foo(x=2) assert hash(f) == 4 class Bar(Foo): y: float b = Bar(x=2, y=1.1) try: assert hash(b) == 4 except TypeError as e: # TypeError: unhashable type: 'Bar' print(e) ``` It seems like this code prevents the use of `Foo.__hash__` on `Bar` instances: https://github.com/samuelcolvin/pydantic/blob/master/pydantic/main.py#L347 I tried to experiment with adding `"__hash__"` to `__slots__`, but an error is triggered in `ModelMetaclass.__new__`: ``` Traceback (most recent call last): File "bug.py", line 4, in <module> class Foo1(BaseModel): File "pydantic/main.py", line 352, in pydantic.main.ModelMetaclass.__new__ File "/usr/lib/python3.8/abc.py", line 85, in __new__ cls = super().__new__(mcls, name, bases, namespace, **kwargs) ValueError: '__hash__' in __slots__ conflicts with class variable ``` I would expect that this continues to work as in 1.7.3, or that the documentation suggests how to avoid having these methods squashed. ---- Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: Passing version: ``` $ python -c "import pydantic.utils; print(pydantic.utils.version_info())" pydantic version: 1.7.3 pydantic compiled: True install path: /home/khaeru/.local/lib/python3.8/site-packages/pydantic python version: 3.8.6 (default, Jan 27 2021, 15:42:20) [GCC 10.2.0] platform: Linux-5.8.0-43-generic-x86_64-with-glibc2.32 optional deps. installed: ['typing-extensions'] ``` Failing version: ``` $ python -c "import pydantic.utils; print(pydantic.utils.version_info())" pydantic version: 1.8 pydantic compiled: True install path: /home/khaeru/.local/lib/python3.8/site-packages/pydantic python version: 3.8.6 (default, Jan 27 2021, 15:42:20) [GCC 10.2.0] platform: Linux-5.8.0-43-generic-x86_64-with-glibc2.32 optional deps. installed: ['typing-extensions'] ```
0.0
a8d50aef0c375374302d050fbe16703d33aaeb86
[ "tests/test_main.py::test_with_declared_hash" ]
[ "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_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_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", "tests/test_main.py::test_model_export_dict_exclusion", "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_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_class_kwargs_config", "tests/test_main.py::test_class_kwargs_config_and_attr_conflict" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-02-27 14:46:56+00:00
mit
4,806
pydantic__pydantic-2434
diff --git a/pydantic/__init__.py b/pydantic/__init__.py --- a/pydantic/__init__.py +++ b/pydantic/__init__.py @@ -48,6 +48,7 @@ # network 'AnyUrl', 'AnyHttpUrl', + 'FileUrl', 'HttpUrl', 'stricturl', 'EmailStr', diff --git a/pydantic/networks.py b/pydantic/networks.py --- a/pydantic/networks.py +++ b/pydantic/networks.py @@ -60,6 +60,7 @@ class Parts(TypedDict, total=False): __all__ = [ 'AnyUrl', 'AnyHttpUrl', + 'FileUrl', 'HttpUrl', 'stricturl', 'EmailStr', @@ -125,6 +126,7 @@ class AnyUrl(str): allowed_schemes: Optional[Set[str]] = None tld_required: bool = False user_required: bool = False + host_required: bool = True hidden_parts: Set[str] = set() __slots__ = ('scheme', 'user', 'password', 'host', 'tld', 'host_type', 'port', 'path', 'query', 'fragment') @@ -140,7 +142,7 @@ def __init__( scheme: str, user: Optional[str] = None, password: Optional[str] = None, - host: str, + host: Optional[str] = None, tld: Optional[str] = None, host_type: str = 'domain', port: Optional[str] = None, @@ -270,7 +272,8 @@ def validate_host(cls, parts: 'Parts') -> Tuple[str, Optional[str], str, bool]: break if host is None: - raise errors.UrlHostError() + if cls.host_required: + raise errors.UrlHostError() elif host_type == 'domain': is_international = False d = ascii_domain_regex().fullmatch(host) @@ -340,6 +343,11 @@ def hide_parts(cls, original_parts: 'Parts') -> None: cls.hidden_parts.add('port') +class FileUrl(AnyUrl): + allowed_schemes = {'file'} + host_required = False + + class PostgresDsn(AnyUrl): allowed_schemes = { 'postgres', @@ -356,6 +364,7 @@ class PostgresDsn(AnyUrl): class RedisDsn(AnyUrl): allowed_schemes = {'redis', 'rediss'} + host_required = False @staticmethod def get_default_parts(parts: 'Parts') -> 'Parts': @@ -383,6 +392,7 @@ def stricturl( min_length: int = 1, max_length: int = 2 ** 16, tld_required: bool = True, + host_required: bool = True, allowed_schemes: Optional[Union[FrozenSet[str], Set[str]]] = None, ) -> Type[AnyUrl]: # use kwargs then define conf in a dict to aid with IDE type hinting @@ -391,6 +401,7 @@ def stricturl( min_length=min_length, max_length=max_length, tld_required=tld_required, + host_required=host_required, allowed_schemes=allowed_schemes, ) return type('UrlValue', (AnyUrl,), namespace)
pydantic/pydantic
65fc336cf3f15310a7438de2163841470ad6204e
I guess we could add `host_required` like `user_required`, then make it true for most of the descendant types.
diff --git a/tests/test_networks.py b/tests/test_networks.py --- a/tests/test_networks.py +++ b/tests/test_networks.py @@ -4,6 +4,7 @@ AnyUrl, BaseModel, EmailStr, + FileUrl, HttpUrl, KafkaDsn, NameEmail, @@ -69,6 +70,7 @@ 'http://twitter.com/@handle/', 'http://11.11.11.11.example.com/action', 'http://abc.11.11.11.11.example.com/action', + 'file://localhost/foo/bar', ], ) def test_any_url_success(value): @@ -113,6 +115,7 @@ class Model(BaseModel): ), ('http://[192.168.1.1]:8329', 'value_error.url.host', 'URL host invalid', None), ('http://example.com:99999', 'value_error.url.port', 'URL port invalid, port cannot exceed 65535', None), + ('file:///foo/bar', 'value_error.url.host', 'URL host invalid', None), ], ) def test_any_url_invalid(value, err_type, err_msg, err_ctx): @@ -265,7 +268,7 @@ def test_http_url_success(value): class Model(BaseModel): v: HttpUrl - assert Model(v=value).v == value, value + assert Model(v=value).v == value @pytest.mark.parametrize( @@ -343,6 +346,17 @@ class Model(BaseModel): assert Model(v=input).v.tld == output [email protected]( + 'value', + ['file:///foo/bar', 'file://localhost/foo/bar' 'file:////localhost/foo/bar'], +) +def test_file_url_success(value): + class Model(BaseModel): + v: FileUrl + + assert Model(v=value).v == value + + def test_get_default_parts(): class MyConnectionString(AnyUrl): @staticmethod @@ -403,6 +417,11 @@ class Model(BaseModel): error = exc_info.value.errors()[0] assert error == {'loc': ('a',), 'msg': 'userinfo required in URL but missing', 'type': 'value_error.url.userinfo'} + with pytest.raises(ValidationError) as exc_info: + Model(a='postgres://user@/foo/bar:5432/app') + error = exc_info.value.errors()[0] + assert error == {'loc': ('a',), 'msg': 'URL host invalid', 'type': 'value_error.url.host'} + def test_redis_dsns(): class Model(BaseModel): @@ -464,7 +483,11 @@ def test_custom_schemes(): class Model(BaseModel): v: stricturl(strip_whitespace=False, allowed_schemes={'ws', 'wss'}) # noqa: F821 + class Model2(BaseModel): + v: stricturl(host_required=False, allowed_schemes={'foo'}) # noqa: F821 + assert Model(v='ws://example.org').v == 'ws://example.org' + assert Model2(v='foo:///foo/bar').v == 'foo:///foo/bar' with pytest.raises(ValidationError): Model(v='http://example.org') @@ -472,6 +495,9 @@ class Model(BaseModel): with pytest.raises(ValidationError): Model(v='ws://example.org ') + with pytest.raises(ValidationError): + Model(v='ws:///foo/bar') + @pytest.mark.parametrize( 'kwargs,expected',
AnyUrl doesn't accept file URLs with implicit host # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.5.1 pydantic compiled: True install path: /shared/conda/envs/ubide-mastr/lib/python3.6/site-packages/pydantic python version: 3.6.10 |Anaconda, Inc.| (default, May 8 2020, 02:54:21) [GCC 7.3.0] platform: Linux-5.4.0-48-generic-x86_64-with-debian-buster-sid optional deps. installed: [] ``` ```py import pydantic class MyModel(pydantic.BaseModel): url: pydantic.AnyUrl MyModel(url='file:///foo/bar') ``` raises: ``` ValidationError: 1 validation error for MyModel url URL host invalid (type=value_error.url.host) ``` However, `MyModel(url='file://hostname/foo/bar')`, i.e. a URL with an explicit hostname, works. RFC 8089 [says](https://tools.ietf.org/html/rfc8089#section-2) that the hostname is optional. Hence I would expect that `AnyUrl` would accept that.
0.0
65fc336cf3f15310a7438de2163841470ad6204e
[ "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[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[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/barfile:////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", "tests/test_networks.py::test_redis_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_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_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-03-01 08:16:12+00:00
mit
4,807
pydantic__pydantic-2438
diff --git a/pydantic/generics.py b/pydantic/generics.py --- a/pydantic/generics.py +++ b/pydantic/generics.py @@ -6,7 +6,6 @@ ClassVar, Dict, Generic, - Iterable, Iterator, List, Mapping, @@ -205,13 +204,16 @@ def check_parameters_count(cls: Type[GenericModel], parameters: Tuple[Any, ...]) raise TypeError(f'Too {description} parameters for {cls.__name__}; actual {actual}, expected {expected}') +DictValues: Type[Any] = {}.values().__class__ + + def iter_contained_typevars(v: Any) -> Iterator[TypeVarType]: """Recursively iterate through all subtypes and type args of `v` and yield any typevars that are found.""" if isinstance(v, TypeVar): yield v elif hasattr(v, '__parameters__') and not get_origin(v) and lenient_issubclass(v, GenericModel): yield from v.__parameters__ - elif isinstance(v, Iterable): + elif isinstance(v, (DictValues, list)): for var in v: yield from iter_contained_typevars(var) else:
pydantic/pydantic
429b4398309454374dbe2432b20c287acd80be9b
diff --git a/tests/test_generics.py b/tests/test_generics.py --- a/tests/test_generics.py +++ b/tests/test_generics.py @@ -3,6 +3,7 @@ from typing import Any, Callable, ClassVar, Dict, Generic, List, Optional, Sequence, Tuple, Type, TypeVar, Union import pytest +from typing_extensions import Literal from pydantic import BaseModel, Field, ValidationError, root_validator, validator from pydantic.generics import GenericModel, _generic_types_cache, iter_contained_typevars, replace_types @@ -1039,3 +1040,34 @@ class Model2(GenericModel, Generic[T]): Model2 = module.Model2 result = Model1[str].parse_obj(dict(ref=dict(ref=dict(ref=dict(ref=123))))) assert result == Model1(ref=Model2(ref=Model1(ref=Model2(ref='123')))) + + +@skip_36 +def test_generic_enum(): + T = TypeVar('T') + + class SomeGenericModel(GenericModel, Generic[T]): + some_field: T + + class SomeStringEnum(str, Enum): + A = 'A' + B = 'B' + + class MyModel(BaseModel): + my_gen: SomeGenericModel[SomeStringEnum] + + m = MyModel.parse_obj({'my_gen': {'some_field': 'A'}}) + assert m.my_gen.some_field is SomeStringEnum.A + + +@skip_36 +def test_generic_literal(): + FieldType = TypeVar('FieldType') + ValueType = TypeVar('ValueType') + + class GModel(GenericModel, Generic[FieldType, ValueType]): + field: Dict[FieldType, ValueType] + + Fields = Literal['foo', 'bar'] + m = GModel[Fields, str](field={'foo': 'x'}) + assert m.dict() == {'field': {'foo': 'x'}}
RecursionError when using Literal types in GenericModel ## Bug If we are trying to use Literal types in GenericModel we are getting `RecursionError: maximum recursion depth exceeded in comparison`. The minimal code example: ```py from typing import Literal, Dict, TypeVar, Generic from pydantic.generics import GenericModel Fields = Literal['foo', 'bar'] FieldType = TypeVar('FieldType') ValueType = TypeVar('ValueType') class GModel(GenericModel, Generic[FieldType, ValueType]): field: Dict[FieldType, ValueType] GModelType = GModel[Fields, str] ``` The traceback: ``` Traceback (most recent call last): File "scratch_101.py", line 12, in <module> GModelType = GModel[Fields, str] File "virtualenvs\foobar-HGIuaRl7-py3.9\lib\site-packages\pydantic\generics.py", line 110, in __class_getitem__ {param: None for param in iter_contained_typevars(typevars_map.values())} File "virtualenvs\foobar-HGIuaRl7-py3.9\lib\site-packages\pydantic\generics.py", line 110, in <dictcomp> {param: None for param in iter_contained_typevars(typevars_map.values())} File "virtualenvs\foobar-HGIuaRl7-py3.9\lib\site-packages\pydantic\generics.py", line 216, in iter_contained_typevars yield from iter_contained_typevars(var) File "virtualenvs\foobar-HGIuaRl7-py3.9\lib\site-packages\pydantic\generics.py", line 220, in iter_contained_typevars yield from iter_contained_typevars(arg) File "virtualenvs\foobar-HGIuaRl7-py3.9\lib\site-packages\pydantic\generics.py", line 216, in iter_contained_typevars yield from iter_contained_typevars(var) File "virtualenvs\foobar-HGIuaRl7-py3.9\lib\site-packages\pydantic\generics.py", line 216, in iter_contained_typevars yield from iter_contained_typevars(var) File "virtualenvs\foobar-HGIuaRl7-py3.9\lib\site-packages\pydantic\generics.py", line 216, in iter_contained_typevars yield from iter_contained_typevars(var) [Previous line repeated 982 more times] File "virtualenvs\foobar-HGIuaRl7-py3.9\lib\site-packages\pydantic\generics.py", line 214, in iter_contained_typevars elif isinstance(v, Iterable): File "C:\Programs\Python\Python39_x64\lib\typing.py", line 657, in __instancecheck__ return self.__subclasscheck__(type(obj)) File "C:\Programs\Python\Python39_x64\lib\typing.py", line 789, in __subclasscheck__ return issubclass(cls, self.__origin__) File "C:\Programs\Python\Python39_x64\lib\abc.py", line 102, in __subclasscheck__ return _abc_subclasscheck(cls, subclass) RecursionError: maximum recursion depth exceeded in comparison ``` ---- Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.8 pydantic compiled: True install path: /home/esp/.cache/pypoetry/virtualenvs/foobar-n-Q38lsL-py3.9/lib/python3.9/site-packages/pydantic python version: 3.9.1 (default, Dec 8 2020, 02:26:20) [GCC 9.3.0] platform: Linux-4.4.0-19041-Microsoft-x86_64-with-glibc2.31 optional deps. installed: ['typing-extensions'] ```
0.0
429b4398309454374dbe2432b20c287acd80be9b
[ "tests/test_generics.py::test_generic_enum", "tests/test_generics.py::test_generic_literal" ]
[ "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_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" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2021-03-01 11:59:05+00:00
mit
4,808
pydantic__pydantic-2451
diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -717,11 +717,12 @@ 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 + value = cls._enforce_dict_if_root(value) if isinstance(value, dict): return cls(**value) - elif isinstance(value, cls): - return value.copy() if cls.__config__.copy_on_model_validation else value elif cls.__config__.orm_mode: return cls.from_orm(value) else:
pydantic/pydantic
a74232e10105c18b7197ff29ee1a6d685b1a47b9
diff --git a/tests/test_main.py b/tests/test_main.py --- a/tests/test_main.py +++ b/tests/test_main.py @@ -1137,6 +1137,17 @@ class MyModel(BaseModel): assert m.__root__ == ['a'] +def test_root_nested(): + class MyList(BaseModel): + __root__: List[str] + + class MyModel(BaseModel): + my_list: MyList + + my_list = MyList(__root__=['pika']) + assert MyModel(my_list=my_list).dict() == {'my_list': ['pika']} + + def test_encode_nested_root(): house_dict = {'pets': ['dog', 'cats']}
Missing downwards compatibility and bug with custom root types ```py from typing import Generic from typing import TypeVar from typing import List from pydantic.generics import GenericModel from pydantic import BaseModel T = TypeVar("T") class BaseList(GenericModel, Generic[T]): __root__: List[T] class Test(BaseModel): mylist: BaseList[int] Test(mylist=[1,2,3,4]) # Test(mylist=BaseList[int](__root__=[1, 2, 3, 4])) Test(mylist=BaseList[int](__root__=[1,2,3,4])) # --------------------------------------------------------------------------- # ValidationError Traceback (most recent call last) # <ipython-input-10-c373af038c5b> in <module> # ----> 1 Test(mylist=BaseList[int](__root__=[1,2,3,4])) # # /usr/local/lib/python3.8/dist-packages/pydantic/main.cpython-38-x86_64-linux-gnu.so in pydantic.main.BaseModel.__init__() # # ValidationError: 1 validation error for Test # mylist -> __root__ # value is not a valid list (type=type_error.list) ``` Certainly no error with pydantic 1.6.1 (I tested this locally). Probably also no errors with versions <1.8 because we have automatic tests in place with the newest package versions and these tests only fired yesterday. On a first glance the documentation does not seem to have changed - so I assume also the behaviour should not have changed with the 1.8 release. See https://pydantic-docs.helpmanual.io/usage/models/#generic-models and https://pydantic-docs.helpmanual.io/usage/models/#custom-root-types 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.8/dist-packages/pydantic python version: 3.8.0 (default, Oct 28 2019, 16:14:01) [GCC 8.3.0] platform: Linux-5.4.0-62-generic-x86_64-with-glibc2.27 optional deps. installed: ['devtools', 'email-validator', 'typing-extensions'] ... ```
0.0
a74232e10105c18b7197ff29ee1a6d685b1a47b9
[ "tests/test_main.py::test_root_nested" ]
[ "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_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", "tests/test_main.py::test_model_export_dict_exclusion", "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_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_class_kwargs_config", "tests/test_main.py::test_class_kwargs_config_and_attr_conflict" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2021-03-02 12:53:23+00:00
mit
4,809
pydantic__pydantic-2461
diff --git a/pydantic/fields.py b/pydantic/fields.py --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -106,7 +106,8 @@ class FieldInfo(Representation): 'extra', ) - __field_constraints__ = { # field constraints with the default value + # field constraints with the default value, it's also used in update_from_config below + __field_constraints__ = { 'min_length': None, 'max_length': None, 'regex': None, @@ -153,6 +154,20 @@ def get_constraints(self) -> Set[str]: """ return {attr for attr, default in self.__field_constraints__.items() if getattr(self, attr) != default} + def update_from_config(self, from_config: Dict[str, Any]) -> None: + """ + Update this FieldInfo based on a dict from get_field_info, only fields which have not been set are dated. + """ + for attr_name, value in from_config.items(): + try: + 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 + else: + if current_value is self.__field_constraints__.get(attr_name, None): + setattr(self, attr_name, value) + def _validate(self) -> None: if self.default not in (Undefined, Ellipsis) and self.default_factory is not None: raise ValueError('cannot specify both default and default_factory') @@ -354,17 +369,20 @@ 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.update_from_config(field_info_from_config) if field_info.default not in (Undefined, Ellipsis): raise ValueError(f'`Field` default cannot be set in `Annotated` for {field_name!r}') if value not in (Undefined, Ellipsis): field_info.default = value + if isinstance(value, FieldInfo): if field_info is not None: raise ValueError(f'cannot specify `Annotated` and value `Field`s together for {field_name!r}') field_info = value - if field_info is None: + field_info.update_from_config(field_info_from_config) + elif field_info is None: field_info = FieldInfo(value, **field_info_from_config) - field_info.alias = field_info.alias or field_info_from_config.get('alias') + value = None if field_info.default_factory is not None else field_info.default field_info._validate() return field_info, value diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -142,6 +142,10 @@ class BaseConfig: @classmethod def get_field_info(cls, name: str) -> Dict[str, Any]: + """ + Get properties of FieldInfo from the `fields` property of the config class. + """ + fields_value = cls.fields.get(name) if isinstance(fields_value, str):
pydantic/pydantic
3f84d1405e6c07669a28d1fdd1e9a6f7a33b43a5
Thanks for reporting, see the discussion on #2437, this is rooted in a wider problem which I'm fixing now.
diff --git a/tests/test_annotated.py b/tests/test_annotated.py --- a/tests/test_annotated.py +++ b/tests/test_annotated.py @@ -2,12 +2,10 @@ from typing import get_type_hints import pytest +from typing_extensions import Annotated from pydantic import BaseModel, Field from pydantic.fields import Undefined -from pydantic.typing import Annotated - -pytestmark = pytest.mark.skipif(not Annotated, reason='typing_extensions not installed') @pytest.mark.parametrize( @@ -26,12 +24,12 @@ ), # Test valid Annotated Field uses pytest.param( - lambda: Annotated[int, Field(description='Test')], + lambda: Annotated[int, Field(description='Test')], # noqa: F821 5, id='annotated-field-value-default', ), pytest.param( - lambda: Annotated[int, Field(default_factory=lambda: 5, description='Test')], + lambda: Annotated[int, Field(default_factory=lambda: 5, description='Test')], # noqa: F821 Undefined, id='annotated-field-default_factory', ), @@ -132,3 +130,15 @@ class AnnotatedModel(BaseModel): one: Annotated[int, field] assert AnnotatedModel(one=1).dict() == {'one': 1} + + +def test_config_field_info(): + class Foo(BaseModel): + a: Annotated[int, Field(foobar='hello')] # noqa: F821 + + class Config: + fields = {'a': {'description': 'descr'}} + + assert Foo.schema(by_alias=True)['properties'] == { + 'a': {'title': 'A', 'description': 'descr', 'foobar': 'hello', 'type': 'integer'}, + } 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,6 @@ import pytest -from pydantic import BaseModel, Extra, ValidationError, create_model, errors, validator +from pydantic import BaseModel, Extra, Field, ValidationError, create_model, errors, validator def test_create_model(): @@ -194,3 +194,14 @@ class A(BaseModel): for field_name in ('x', 'y', 'z'): assert A.__fields__[field_name].default == DynamicA.__fields__[field_name].default + + +def test_config_field_info_create_model(): + class Config: + fields = {'a': {'description': 'descr'}} + + m1 = create_model('M1', __config__=Config, a=(str, ...)) + assert m1.schema()['properties'] == {'a': {'title': 'A', 'description': 'descr', 'type': 'string'}} + + m2 = create_model('M2', __config__=Config, a=(str, Field(...))) + assert m2.schema()['properties'] == {'a': {'title': 'A', 'description': 'descr', 'type': 'string'}} diff --git a/tests/test_dataclasses.py b/tests/test_dataclasses.py --- a/tests/test_dataclasses.py +++ b/tests/test_dataclasses.py @@ -901,3 +901,22 @@ class Config: # ensure the restored dataclass is still a pydantic dataclass with pytest.raises(ValidationError, match='value\n +value is not a valid integer'): restored_obj.dataclass.value = 'value of a wrong type' + + +def test_config_field_info_create_model(): + # works + class A1(BaseModel): + a: str + + class Config: + fields = {'a': {'description': 'descr'}} + + assert A1.schema()['properties'] == {'a': {'title': 'A', 'description': 'descr', 'type': 'string'}} + + @pydantic.dataclasses.dataclass(config=A1.Config) + class A2: + a: str + + assert A2.__pydantic_model__.schema()['properties'] == { + 'a': {'title': 'A', 'description': 'descr', 'type': 'string'} + } 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 @@ -1779,3 +1779,63 @@ class MyModel(BaseModel): y: str = 'a' assert list(MyModel()._iter(by_alias=True)) == [('x', 1), ('y', 'a')] + + +def test_config_field_info(): + class Foo(BaseModel): + a: str = Field(...) + + class Config: + fields = {'a': {'description': 'descr'}} + + assert Foo.schema(by_alias=True)['properties'] == {'a': {'title': 'A', 'description': 'descr', 'type': 'string'}} + + +def test_config_field_info_alias(): + class Foo(BaseModel): + a: str = Field(...) + + class Config: + fields = {'a': {'alias': 'b'}} + + assert Foo.schema(by_alias=True)['properties'] == {'b': {'title': 'B', 'type': 'string'}} + + +def test_config_field_info_merge(): + class Foo(BaseModel): + a: str = Field(..., foo='Foo') + + class Config: + fields = {'a': {'bar': 'Bar'}} + + assert Foo.schema(by_alias=True)['properties'] == { + 'a': {'bar': 'Bar', 'foo': 'Foo', 'title': 'A', 'type': 'string'} + } + + +def test_config_field_info_allow_mutation(): + class Foo(BaseModel): + a: str = Field(...) + + class Config: + validate_assignment = True + + assert Foo.__fields__['a'].field_info.allow_mutation is True + + f = Foo(a='x') + f.a = 'y' + assert f.dict() == {'a': 'y'} + + class Bar(BaseModel): + a: str = Field(...) + + class Config: + fields = {'a': {'allow_mutation': False}} + validate_assignment = True + + assert Bar.__fields__['a'].field_info.allow_mutation is False + + b = Bar(a='x') + with pytest.raises(TypeError): + b.a = 'y' + assert b.dict() == {'a': 'x'}
dataclass config fields not warranted in json schema (1.8) ### 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.8 pydantic compiled: True install path: /Users/dafcok/miniconda3/lib/python3.6/site-packages/pydantic python version: 3.6.8 |Anaconda, Inc.| (default, Dec 29 2018, 19:04:46) [GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] platform: Darwin-19.6.0-x86_64-i386-64bit optional deps. installed: ['devtools', 'dotenv', 'email-validator', 'typing-extensions' ``` ```py from pydantic import BaseModel from pydantic.dataclasses import dataclass # works class A(BaseModel): a: str class Config: fields = {"a": {"description": "descr"}} assert A.schema()["properties"]["a"]["description"] == "descr" # works on 1.7.3 # fails on 1.8 @dataclass(config=A.Config) class Ad: a: str assert Ad.__pydantic_model__.schema()["properties"]["a"]["description"] == "descr" ``` ```bash Traceback (most recent call last): File "tests/test_schema_descr.py", line 24, in <module> assert Ad.__pydantic_model__.schema()["properties"]["a"]["description"] == "descr" KeyError: 'description ``` It seems that `config.fields` is not processed in the decorator.
0.0
3f84d1405e6c07669a28d1fdd1e9a6f7a33b43a5
[ "tests/test_annotated.py::test_config_field_info", "tests/test_create_model.py::test_config_field_info_create_model", "tests/test_dataclasses.py::test_config_field_info_create_model", "tests/test_edge_cases.py::test_config_field_info", "tests/test_edge_cases.py::test_config_field_info_merge", "tests/test_edge_cases.py::test_config_field_info_allow_mutation" ]
[ "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_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_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_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_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_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_side_effect", "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_alias" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2021-03-03 11:31:40+00:00
mit
4,810
pydantic__pydantic-2479
diff --git a/pydantic/json.py b/pydantic/json.py --- a/pydantic/json.py +++ b/pydantic/json.py @@ -17,6 +17,7 @@ Pattern = re.compile('a').__class__ from .color import Color +from .networks import NameEmail from .types import SecretBytes, SecretStr __all__ = 'pydantic_encoder', 'custom_pydantic_encoder', 'timedelta_isoformat' @@ -65,6 +66,7 @@ def decimal_encoder(dec_value: Decimal) -> Union[int, float]: IPv6Address: str, IPv6Interface: str, IPv6Network: str, + NameEmail: str, Path: str, Pattern: lambda o: o.pattern, SecretBytes: str,
pydantic/pydantic
4ec6c5290528c32155d9aea0d996ddbf9e34d776
Thanks for reporting. Amazing this has never come up before. Should be relatively simple to fix in [`pydantic/json.py`](https://github.com/samuelcolvin/pydantic/blob/master/pydantic/json.py), the only tricky thing is dealing with conditional imports. @samuelcolvin hey I'm trying to fix this bug and I'm encountering the tricky conditional imports thing. Would it be easier to move `NameEmail` to `pydantic/types.py` like `SecretStr`? Humm, I would prefer not to. What is the problem? network.py shouldn't import json.py
diff --git a/tests/test_json.py b/tests/test_json.py --- a/tests/test_json.py +++ b/tests/test_json.py @@ -12,7 +12,7 @@ import pytest -from pydantic import BaseModel, create_model +from pydantic import BaseModel, NameEmail, create_model from pydantic.color import Color from pydantic.dataclasses import dataclass as pydantic_dataclass from pydantic.json import pydantic_encoder, timedelta_isoformat @@ -35,6 +35,7 @@ class MyEnum(Enum): (SecretStr(''), '""'), (SecretBytes(b'xyz'), '"**********"'), (SecretBytes(b''), '""'), + (NameEmail('foo bar', '[email protected]'), '"foo bar <[email protected]>"'), (IPv6Address('::1:0:1'), '"::1:0:1"'), (IPv4Interface('192.168.0.0/24'), '"192.168.0.0/24"'), (IPv6Interface('2001:db00::/120'), '"2001:db00::/120"'),
Object of type 'NameEmail' is not JSON serializable ### 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.7.3 pydantic compiled: True install path: /app/env/lib/python3.8/site-packages/pydantic python version: 3.8.5 (default, Jul 28 2020, 12:59:40) [GCC 9.3.0] platform: Linux-5.8.0-43-generic-x86_64-with-glibc2.29 optional deps. installed: ['typing-extensions', 'email-validator'] ``` <!-- 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. --> This issue was mentioned in #462, but was only solved for the case of SecretStr, NameEmail was left unsolved. <!-- Where possible please include a self-contained code snippet describing your bug: --> ```py import pydantic class MyModel(pydantic.BaseModel): email: pydantic.NameEmail MyModel(email="foo <[email protected]>").json() ``` I get: ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> File "pydantic/main.py", line 506, in pydantic.main.BaseModel.json File "/usr/lib/python3.8/json/__init__.py", line 234, in dumps return cls( File "/usr/lib/python3.8/json/encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "/usr/lib/python3.8/json/encoder.py", line 257, in iterencode return _iterencode(o, 0) File "pydantic/json.py", line 65, in pydantic.json.pydantic_encoder TypeError: Object of type 'NameEmail' is not JSON serializable ```
0.0
4ec6c5290528c32155d9aea0d996ddbf9e34d776
[ "tests/test_json.py::test_encoding[input8-\"foo" ]
[ "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[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,", "tests/test_json.py::test_encoding[input20-[1,", "tests/test_json.py::test_encoding[<genexpr>-[0,", "tests/test_json.py::test_encoding[this", "tests/test_json.py::test_encoding[input23-12.34]", "tests/test_json.py::test_encoding[input24-{\"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_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" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2021-03-05 10:57:43+00:00
mit
4,811
pydantic__pydantic-2497
diff --git a/docs/build/schema_mapping.py b/docs/build/schema_mapping.py --- a/docs/build/schema_mapping.py +++ b/docs/build/schema_mapping.py @@ -81,10 +81,17 @@ 'JSON Schema Validation', 'And equivalently for any other sub type, e.g. `List[int]`.' ], + [ + 'Tuple[str, ...]', + 'array', + {'items': {'type': 'string'}}, + 'JSON Schema Validation', + 'And equivalently for any other sub type, e.g. `Tuple[int, ...]`.' + ], [ 'Tuple[str, int]', 'array', - {'items': [{'type': 'string'}, {'type': 'integer'}]}, + {'items': [{'type': 'string'}, {'type': 'integer'}], 'minItems': 2, 'maxItems': 2}, 'JSON Schema Validation', ( 'And equivalently for any other set of subtypes. Note: If using schemas for OpenAPI, ' diff --git a/pydantic/schema.py b/pydantic/schema.py --- a/pydantic/schema.py +++ b/pydantic/schema.py @@ -490,15 +490,19 @@ def field_type_schema( definitions.update(sf_definitions) nested_models.update(sf_nested_models) sub_schema.append(sf_schema) - if len(sub_schema) == 1: - if field.shape == SHAPE_GENERIC: - f_schema = sub_schema[0] - else: - f_schema = {'type': 'array', 'items': sub_schema[0]} - else: - f_schema = {'type': 'array', 'items': sub_schema} + + sub_fields_len = len(sub_fields) if field.shape == SHAPE_GENERIC: - f_schema = {'allOf': [f_schema]} + all_of_schemas = sub_schema[0] if sub_fields_len == 1 else {'type': 'array', 'items': sub_schema} + f_schema = {'allOf': [all_of_schemas]} + else: + f_schema = { + 'type': 'array', + 'minItems': sub_fields_len, + 'maxItems': sub_fields_len, + } + if sub_fields_len >= 1: + f_schema['items'] = sub_schema else: assert field.shape in {SHAPE_SINGLETON, SHAPE_GENERIC}, field.shape f_schema, f_definitions, f_nested_models = field_singleton_schema( @@ -835,7 +839,15 @@ def field_singleton_schema( # noqa: C901 (ignore complexity) ref_template=ref_template, known_models=known_models, ) - f_schema.update({'type': 'array', 'items': list(sub_schema['properties'].values())}) + items_schemas = list(sub_schema['properties'].values()) + f_schema.update( + { + 'type': 'array', + 'items': items_schemas, + 'minItems': len(items_schemas), + 'maxItems': len(items_schemas), + } + ) elif not hasattr(field_type, '__pydantic_model__'): add_field_type_to_schema(field_type, f_schema)
pydantic/pydantic
93aed51183fb6c154d8732916a17e1e3b79e6e61
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 @@ -79,6 +79,8 @@ class Model(BaseModel): {'title': 'X', 'type': 'integer'}, {'title': 'Y', 'type': 'integer'}, ], + 'minItems': 2, + 'maxItems': 2, }, 'pos2': { 'title': 'Pos2', @@ -87,6 +89,8 @@ class Model(BaseModel): {'title': 'X'}, {'title': 'Y'}, ], + 'minItems': 2, + 'maxItems': 2, }, 'pos3': { 'title': 'Pos3', @@ -95,6 +99,8 @@ class Model(BaseModel): {'type': 'integer'}, {'type': 'integer'}, ], + 'minItems': 2, + 'maxItems': 2, }, }, 'required': ['pos1', 'pos2', 'pos3'], diff --git a/tests/test_schema.py b/tests/test_schema.py --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -526,34 +526,36 @@ class Model(BaseModel): @pytest.mark.parametrize( - 'field_type,expected_schema', + 'field_type,extra_props', [ - (tuple, {}), + (tuple, {'items': {}}), ( Tuple[str, int, Union[str, int, float], float], - [ - {'type': 'string'}, - {'type': 'integer'}, - {'anyOf': [{'type': 'string'}, {'type': 'integer'}, {'type': 'number'}]}, - {'type': 'number'}, - ], + { + 'items': [ + {'type': 'string'}, + {'type': 'integer'}, + {'anyOf': [{'type': 'string'}, {'type': 'integer'}, {'type': 'number'}]}, + {'type': 'number'}, + ], + 'minItems': 4, + 'maxItems': 4, + }, ), - (Tuple[str], {'type': 'string'}), + (Tuple[str], {'items': [{'type': 'string'}], 'minItems': 1, 'maxItems': 1}), + (Tuple[()], {'maxItems': 0, 'minItems': 0}), ], ) -def test_tuple(field_type, expected_schema): +def test_tuple(field_type, extra_props): class Model(BaseModel): a: field_type - base_schema = { + assert Model.schema() == { 'title': 'Model', 'type': 'object', - 'properties': {'a': {'title': 'A', 'type': 'array'}}, + 'properties': {'a': {'title': 'A', 'type': 'array', **extra_props}}, 'required': ['a'], } - base_schema['properties']['a']['items'] = expected_schema - - assert Model.schema() == base_schema def test_bool(): @@ -1923,6 +1925,8 @@ class Config: {'exclusiveMinimum': 0, 'type': 'integer'}, {'exclusiveMinimum': 0, 'type': 'integer'}, ], + 'minItems': 3, + 'maxItems': 3, }, ), ( @@ -2312,6 +2316,8 @@ class LocationBase(BaseModel): 'default': Coordinates(x=0, y=0), 'type': 'array', 'items': [{'title': 'X', 'type': 'number'}, {'title': 'Y', 'type': 'number'}], + 'minItems': 2, + 'maxItems': 2, } }, } @@ -2403,11 +2409,19 @@ class Model(BaseModel): 'examples': 'examples', }, 'data3': {'title': 'Data3', 'type': 'array', 'items': {}}, - 'data4': {'title': 'Data4', 'type': 'array', 'items': {'$ref': '#/definitions/CustomType'}}, + 'data4': { + 'title': 'Data4', + 'type': 'array', + 'items': [{'$ref': '#/definitions/CustomType'}], + 'minItems': 1, + 'maxItems': 1, + }, 'data5': { 'title': 'Data5', 'type': 'array', 'items': [{'$ref': '#/definitions/CustomType'}, {'type': 'string'}], + 'minItems': 2, + 'maxItems': 2, }, }, 'required': ['data0', 'data1', 'data2', 'data3', 'data4', 'data5'],
Empty tuple type does not generate valid JSON schema ### 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.1 pydantic compiled: True install path: /Users/smacpher/.virtualenvs/nucleus/lib/python3.6/site-packages/pydantic python version: 3.6.9 (default, Oct 16 2019, 11:14:39) [GCC 4.2.1 Compatible Apple LLVM 10.0.0 (clang-1000.10.44.4)] platform: Darwin-17.7.0-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: --> ```py import jsonschema import pydantic from typing import Tuple class Model(pydantic.BaseModel): f: Tuple[()] jsonschema.Draft7Validator.check_schema(Model.schema()) ``` This fails with: ``` SchemaError: [] is not valid under any of the given schemas Failed validating 'anyOf' in metaschema['properties']['properties']['additionalProperties']['properties']['items']: {'anyOf': [{'$ref': '#'}, {'$ref': '#/definitions/schemaArray'}], 'default': True} On schema['properties']['f']['items']: [] ``` The generated schema is: ```py {'title': 'Model', 'type': 'object', 'properties': {'f': {'title': 'F', 'type': 'array', 'items': []}}, 'required': ['f']} ``` Is this expected behavior? Would the desired behavior be to set `maxItems: 0` and remove `items: []` like such (that would make the generated schema valid)? ``` {'title': 'Model', 'type': 'object', 'properties': {'f': {'title': 'F', 'type': 'array', 'maxItems': 0}}, 'required': ['f']} ``` BTW, glad to see that empty tuples (`Tuple[()]`) are now supported (https://github.com/samuelcolvin/pydantic/issues/2318)! Thank you 🙏 .
0.0
93aed51183fb6c154d8732916a17e1e3b79e6e61
[ "tests/test_annotated_types.py::test_namedtuple_schema", "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_enforced_constraints[annotation3-kwargs3-field_schema3]", "tests/test_schema.py::test_namedtuple_default", "tests/test_schema.py::test_advanced_generic_schema" ]
[ "tests/test_annotated_types.py::test_namedtuple", "tests/test_annotated_types.py::test_namedtuple_right_length", "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_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-extra_props0]", "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[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_nested_generic", "tests/test_schema.py::test_nested_generic_model", "tests/test_schema.py::test_complex_nested_generic" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2021-03-08 22:45:54+00:00
mit
4,812
pydantic__pydantic-2502
diff --git a/pydantic/decorator.py b/pydantic/decorator.py --- a/pydantic/decorator.py +++ b/pydantic/decorator.py @@ -1,23 +1,10 @@ from functools import wraps -from typing import ( - TYPE_CHECKING, - Any, - Callable, - Dict, - List, - Mapping, - Optional, - Tuple, - Type, - TypeVar, - Union, - get_type_hints, - overload, -) +from typing import TYPE_CHECKING, Any, Callable, Dict, List, Mapping, Optional, Tuple, Type, TypeVar, Union, overload from . import validator from .errors import ConfigError from .main import BaseModel, Extra, create_model +from .typing import get_all_type_hints from .utils import to_camel __all__ = ('validate_arguments',) @@ -87,17 +74,17 @@ def __init__(self, function: 'AnyCallableT', config: 'ConfigType'): # noqa C901 self.v_args_name = 'args' self.v_kwargs_name = 'kwargs' - type_hints = get_type_hints(function) + type_hints = get_all_type_hints(function) takes_args = False takes_kwargs = False fields: Dict[str, Tuple[Any, Any]] = {} for i, (name, p) in enumerate(parameters.items()): - if p.annotation == p.empty: + if p.annotation is p.empty: annotation = Any else: annotation = type_hints[name] - default = ... if p.default == p.empty else p.default + default = ... if p.default is p.empty else p.default if p.kind == Parameter.POSITIONAL_ONLY: self.arg_mapping[i] = name fields[name] = annotation, default diff --git a/pydantic/fields.py b/pydantic/fields.py --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -169,7 +169,7 @@ def update_from_config(self, from_config: Dict[str, Any]) -> None: setattr(self, attr_name, value) def _validate(self) -> None: - if self.default not in (Undefined, Ellipsis) and self.default_factory is not None: + if self.default is not Undefined and self.default_factory is not None: raise ValueError('cannot specify both default and default_factory') @@ -370,9 +370,10 @@ def _get_field_info( field_info = next(iter(field_infos), None) if field_info is not None: field_info.update_from_config(field_info_from_config) - if field_info.default not in (Undefined, Ellipsis): + if field_info.default is not Undefined: raise ValueError(f'`Field` default cannot be set in `Annotated` for {field_name!r}') - if value not in (Undefined, Ellipsis): + if value is not Undefined and value is not Required: + # check also `Required` because of `validate_arguments` that sets `...` as default value field_info.default = value if isinstance(value, FieldInfo): @@ -450,7 +451,6 @@ def prepare(self) -> None: self._type_analysis() if self.required is Undefined: self.required = True - self.field_info.default = Required if self.default is Undefined and self.default_factory is None: self.default = None self.populate_validators() diff --git a/pydantic/generics.py b/pydantic/generics.py --- a/pydantic/generics.py +++ b/pydantic/generics.py @@ -15,13 +15,14 @@ TypeVar, Union, cast, - get_type_hints, ) +from typing_extensions import Annotated + from .class_validators import gather_all_validators from .fields import DeferredType from .main import BaseModel, create_model -from .typing import display_as_type, get_args, get_origin, typing_base +from .typing import display_as_type, get_all_type_hints, get_args, get_origin, typing_base from .utils import all_identical, lenient_issubclass _generic_types_cache: Dict[Tuple[Type[Any], Union[Any, Tuple[Any, ...]]], Type[BaseModel]] = {} @@ -73,7 +74,7 @@ def __class_getitem__(cls: Type[GenericModelT], params: Union[Type[Any], Tuple[T model_name = cls.__concrete_name__(params) validators = gather_all_validators(cls) - type_hints = get_type_hints(cls).items() + type_hints = get_all_type_hints(cls).items() instance_type_hints = {k: v for k, v in type_hints if get_origin(v) is not ClassVar} fields = {k: (DeferredType(), cls.__fields__[k].field_info) for k in instance_type_hints if k in cls.__fields__} @@ -159,6 +160,10 @@ def replace_types(type_: Any, type_map: Mapping[Any, Any]) -> Any: type_args = get_args(type_) origin_type = get_origin(type_) + if origin_type is Annotated: + annotated_type, *annotations = type_args + return Annotated[replace_types(annotated_type, type_map), tuple(annotations)] + # Having type args is a good indicator that this is a typing module # class instantiation or a generic alias of some sort. if type_args: diff --git a/pydantic/typing.py b/pydantic/typing.py --- a/pydantic/typing.py +++ b/pydantic/typing.py @@ -18,6 +18,7 @@ Union, _eval_type, cast, + get_type_hints, ) from typing_extensions import Annotated, Literal @@ -70,6 +71,18 @@ def evaluate_forwardref(type_: ForwardRef, globalns: Any, localns: Any) -> Any: return cast(Any, type_)._evaluate(globalns, localns, set()) +if sys.version_info < (3, 9): + # Ensure we always get all the whole `Annotated` hint, not just the annotated type. + # For 3.6 to 3.8, `get_type_hints` doesn't recognize `typing_extensions.Annotated`, + # so it already returns the full annotation + get_all_type_hints = get_type_hints + +else: + + def get_all_type_hints(obj: Any, globalns: Any = None, localns: Any = None) -> Any: + return get_type_hints(obj, globalns, localns, include_extras=True) + + if sys.version_info < (3, 7): from typing import Callable as Callable @@ -225,6 +238,7 @@ def get_args(tp: Type[Any]) -> Tuple[Any, ...]: 'get_args', 'get_origin', 'typing_base', + 'get_all_type_hints', )
pydantic/pydantic
14f055e74306799faabc24d0b9b7a80114d51864
diff --git a/tests/test_annotated.py b/tests/test_annotated.py --- a/tests/test_annotated.py +++ b/tests/test_annotated.py @@ -1,11 +1,9 @@ -import sys -from typing import get_type_hints - import pytest from typing_extensions import Annotated from pydantic import BaseModel, Field from pydantic.fields import Undefined +from pydantic.typing import get_all_type_hints @pytest.mark.parametrize( @@ -43,15 +41,7 @@ class M(BaseModel): assert M().x == 5 assert M(x=10).x == 10 - - # get_type_hints doesn't recognize typing_extensions.Annotated, so will return the full - # annotation. 3.9 w/ stock Annotated will return the wrapped type by default, but return the - # full thing with the new include_extras flag. - if sys.version_info >= (3, 9): - assert get_type_hints(M)['x'] is int - assert get_type_hints(M, include_extras=True)['x'] == hint - else: - assert get_type_hints(M)['x'] == hint + assert get_all_type_hints(M)['x'] == hint @pytest.mark.parametrize( diff --git a/tests/test_decorator.py b/tests/test_decorator.py --- a/tests/test_decorator.py +++ b/tests/test_decorator.py @@ -3,14 +3,13 @@ import sys from pathlib import Path from typing import List -from unittest.mock import ANY import pytest +from typing_extensions import Annotated from pydantic import BaseModel, Field, ValidationError, validate_arguments from pydantic.decorator import ValidatedFunction from pydantic.errors import ConfigError -from pydantic.typing import Annotated skip_pre_38 = pytest.mark.skipif(sys.version_info < (3, 8), reason='testing >= 3.8 behaviour only') @@ -154,13 +153,14 @@ def foo(a: int, b: int = Field(default_factory=lambda: 99), *args: int) -> int: assert foo(1, 2, 3) == 6 [email protected](not Annotated, reason='typing_extensions not installed') def test_annotated_field_can_provide_factory() -> None: @validate_arguments - def foo2(a: int, b: Annotated[int, Field(default_factory=lambda: 99)] = ANY, *args: int) -> int: + def foo2(a: int, b: Annotated[int, Field(default_factory=lambda: 99)], *args: int) -> int: """mypy reports Incompatible default for argument "b" if we don't supply ANY as default""" return a + b + sum(args) + assert foo2(1) == 100 + @skip_pre_38 def test_positional_only(create_module): 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 @@ -1839,3 +1839,19 @@ class Config: with pytest.raises(TypeError): b.a = 'y' assert b.dict() == {'a': 'x'} + + +def test_arbitrary_types_allowed_custom_eq(): + class Foo: + def __eq__(self, other): + if other.__class__ is not Foo: + raise TypeError(f'Cannot interpret {other.__class__.__name__!r} as a valid type') + return True + + class Model(BaseModel): + x: Foo = Foo() + + class Config: + arbitrary_types_allowed = True + + assert Model().x == Foo() diff --git a/tests/test_generics.py b/tests/test_generics.py --- a/tests/test_generics.py +++ b/tests/test_generics.py @@ -3,7 +3,7 @@ from typing import Any, Callable, ClassVar, Dict, Generic, List, Optional, Sequence, Tuple, Type, TypeVar, Union import pytest -from typing_extensions import Literal +from typing_extensions import Annotated, Literal from pydantic import BaseModel, Field, ValidationError, root_validator, validator from pydantic.generics import GenericModel, _generic_types_cache, iter_contained_typevars, replace_types @@ -1071,3 +1071,13 @@ class GModel(GenericModel, Generic[FieldType, ValueType]): Fields = Literal['foo', 'bar'] m = GModel[Fields, str](field={'foo': 'x'}) assert m.dict() == {'field': {'foo': 'x'}} + + +@skip_36 +def test_generic_annotated(): + T = TypeVar('T') + + class SomeGenericModel(GenericModel, Generic[T]): + some_field: Annotated[T, Field(alias='the_alias')] + + SomeGenericModel[str](the_alias='qwe')
Pydantic 1.8.0 raises Exception when overriding __eq__ ### 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 <!-- 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 class Foo(BaseModel): value: int def __eq__(self, other): return self.value == other.value class Test(BaseModel): foo: Foo = Foo(value=10) ``` for pydantic 1.7.x it works. when 1.8.1 it raises: ``` Traceback (most recent call last): File "main.py", line 11, in <module> class Test(BaseModel): File "pydantic/main.py", line 287, in pydantic.main.ModelMetaclass.__new__ File "pydantic/fields.py", line 384, in pydantic.fields.ModelField.infer File "pydantic/fields.py", line 369, in pydantic.fields.ModelField._get_field_info File "pydantic/fields.py", line 157, in pydantic.fields.FieldInfo._validate File "main.py", line 8, in __eq__ return self.value < other.value AttributeError: 'UndefinedType' object has no attribute 'value' ```
0.0
14f055e74306799faabc24d0b9b7a80114d51864
[ "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", "tests/test_decorator.py::test_args", "tests/test_decorator.py::test_wrap", "tests/test_decorator.py::test_kwargs", "tests/test_decorator.py::test_untyped", "tests/test_decorator.py::test_var_args_kwargs[True]", "tests/test_decorator.py::test_var_args_kwargs[False]", "tests/test_decorator.py::test_field_can_provide_factory", "tests/test_decorator.py::test_annotated_field_can_provide_factory", "tests/test_decorator.py::test_positional_only", "tests/test_decorator.py::test_args_name", "tests/test_decorator.py::test_v_args", "tests/test_decorator.py::test_async", "tests/test_decorator.py::test_string_annotation", "tests/test_decorator.py::test_item_method", "tests/test_decorator.py::test_class_method", "tests/test_decorator.py::test_config_title", "tests/test_decorator.py::test_config_title_cls", "tests/test_decorator.py::test_config_fields", "tests/test_decorator.py::test_config_arbitrary_types_allowed", "tests/test_decorator.py::test_validate", "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_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_side_effect", "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_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_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_annotated" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-03-09 22:52:38+00:00
mit
4,813
pydantic__pydantic-2512
diff --git a/pydantic/networks.py b/pydantic/networks.py --- a/pydantic/networks.py +++ b/pydantic/networks.py @@ -69,8 +69,8 @@ def url_regex() -> Pattern[str]: r'(?:(?P<scheme>[a-z][a-z0-9+\-.]+)://)?' # scheme https://tools.ietf.org/html/rfc3986#appendix-A r'(?:(?P<user>[^\s:/]*)(?::(?P<password>[^\s/]*))?@)?' # user info r'(?:' - r'(?P<ipv4>(?:\d{1,3}\.){3}\d{1,3})|' # ipv4 - r'(?P<ipv6>\[[A-F0-9]*:[A-F0-9:]+\])|' # ipv6 + r'(?P<ipv4>(?:\d{1,3}\.){3}\d{1,3})(?=$|[/:#?])|' # ipv4 + r'(?P<ipv6>\[[A-F0-9]*:[A-F0-9:]+\])(?=$|[/:#?])|' # ipv6 r'(?P<domain>[^\s/:?#]+)' # domain, validation occurs later r')?' r'(?::(?P<port>\d+))?' # port
pydantic/pydantic
619ff261c9bdc2a612ef2fcfa17a005dfefbcf21
Is there any reason that pydantic is not using the [python builtin url parser](https://docs.python.org/3/library/urllib.parse.html)? `11.11.11.11` looks like an ip address which is what's causing the problem. Happy to accept a PR if you can find an easy way to fix this, but I think it's not trivial. > Is there any reason that pydantic is not using the [python builtin url parser](https://docs.python.org/3/library/urllib.parse.html)? Yes, ```py from urllib.parse import urlparse urlparse('not valid') #> ParseResult(scheme='', netloc='', path='not valid', params='', query='', fragment='') ``` all strings are parsed, it's not trivial to see how you'd use `urlparse` to check if a URL is valid, and then give a reasonable error when it's not. I guess we could check `scheme` is ok, then check `netloc` is not empty and use regexes to see if it's an IP or a valid domain, and so on. I've no idea if this would be more performant than the current solution. pydantic's URL parsing using regexes was originally taken from marshmallow, then altered a lot. I suspect that `urlparse` is not a golden panacea or all other validation libraries would be using it, but maybe I'm wrong.
diff --git a/tests/test_networks.py b/tests/test_networks.py --- a/tests/test_networks.py +++ b/tests/test_networks.py @@ -51,6 +51,8 @@ AnyUrl('https://example.com', scheme='https', host='example.com'), 'https://exam_ple.com/', 'http://twitter.com/@handle/', + 'http://11.11.11.11.example.com/action', + 'http://abc.11.11.11.11.example.com/action', ], ) def test_any_url_success(value): @@ -159,6 +161,16 @@ def test_ipv4_port(): assert url.password is None +def test_ipv4_no_port(): + url = validate_url('ftp://123.45.67.8') + assert url.scheme == 'ftp' + assert url.host == '123.45.67.8' + assert url.host_type == 'ipv4' + assert url.port is None + assert url.user is None + assert url.password is None + + def test_ipv6_port(): url = validate_url('wss://[2001:db8::ff00:42]:8329') assert url.scheme == 'wss'
Validation Error on HttpUrl and AnyHttpUrl on parsing valid url starting with 4 numbers # Validation Error on HttpUrl and AnyHttpUrl on parsing valid url starting with 4 numbers Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.5.1 pydantic compiled: True install path: /opt/virtualenvs/python3/lib/python3.8/site-packages/pydantic python version: 3.8.3 (default, May 14 2020, 20:11:43) [GCC 7.5.0] platform: Linux-5.4.0-1009-gcp-x86_64-with-glibc2.27 optional deps. installed: [] ``` ```py from pydantic import BaseModel, HttpUrl, AnyHttpUrl class MyModel(BaseModel): url: HttpUrl class MyModel2(BaseModel): url: AnyHttpUrl a = MyModel(url='http://abc.11.11.11.11.nip.io/action') b = MyModel2(url='http://abc.11.11.11.11.nip.io/action') c = MyModel(url='http://11.11.11.11.nip.io/action') d = MyModel2(url='http://11.11.11.11.nip.io/action') ``` Output of `c` and `d` ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> File "pydantic/main.py", line 338, in pydantic.main.BaseModel.__init__ pydantic.error_wrappers.ValidationError: 1 validation error for MyModel2 url URL invalid, extra characters found after valid URL: '.nip.io/action' (type=value_error.url.extra; extra=.nip.io/action) ``` `a` and `b` can be validated `c` and `d` raise ValidationError However they are valid URL.
0.0
619ff261c9bdc2a612ef2fcfa17a005dfefbcf21
[ "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://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+psycopg2://postgres:postgres@localhost:5432/hatch]", "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://abc.11.11.11.11.example.com/action]", "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_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_postgres_dsns", "tests/test_networks.py::test_redis_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_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_test_patch": true, "is_lite": false }
2021-03-11 20:30:27+00:00
mit
4,814
pydantic__pydantic-2519
diff --git a/pydantic/fields.py b/pydantic/fields.py --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -30,7 +30,6 @@ from .errors import ConfigError, NoneIsNotAllowedError from .types import Json, JsonWrapper from .typing import ( - NONE_TYPES, Callable, ForwardRef, NoArgAnyCallable, @@ -40,6 +39,7 @@ get_origin, is_literal_type, is_new_type, + is_none_type, is_typeddict, is_union_origin, new_type_supertype, @@ -739,7 +739,7 @@ def validate( return v, errors if v is None: - if self.type_ in NONE_TYPES: + if is_none_type(self.type_): # keep validating pass elif self.allow_none: diff --git a/pydantic/schema.py b/pydantic/schema.py --- a/pydantic/schema.py +++ b/pydantic/schema.py @@ -63,7 +63,6 @@ constr, ) from .typing import ( - NONE_TYPES, ForwardRef, all_literal_values, get_args, @@ -71,6 +70,7 @@ is_callable_type, is_literal_type, is_namedtuple, + is_none_type, is_union_origin, ) from .utils import ROOT_KEY, get_model, lenient_issubclass, sequence_like @@ -788,7 +788,7 @@ def field_singleton_schema( # noqa: C901 (ignore complexity) ) if field_type is Any or field_type.__class__ == TypeVar: return {}, definitions, nested_models # no restrictions - if field_type in NONE_TYPES: + if is_none_type(field_type): return {'type': 'null'}, definitions, nested_models if is_callable_type(field_type): raise SkipField(f'Callable {field.name} was excluded from schema since JSON schema has no equivalent type.') diff --git a/pydantic/typing.py b/pydantic/typing.py --- a/pydantic/typing.py +++ b/pydantic/typing.py @@ -227,7 +227,7 @@ def is_union_origin(origin: Type[Any]) -> bool: 'AnyCallable', 'NoArgAnyCallable', 'NoneType', - 'NONE_TYPES', + 'is_none_type', 'display_as_type', 'resolve_annotations', 'is_callable_type', @@ -260,7 +260,29 @@ def is_union_origin(origin: Type[Any]) -> bool: NoneType = None.__class__ -NONE_TYPES: Set[Any] = {None, NoneType, Literal[None]} + + +NONE_TYPES: Tuple[Any, Any, Any] = (None, NoneType, Literal[None]) + + +if sys.version_info < (3, 8): # noqa: C901 (ignore complexity) + # Even though this implementation is slower, we need it for python 3.6/3.7: + # In python 3.6/3.7 "Literal" is not a builtin type and uses a different + # mechanism. + # for this reason `Literal[None] is Literal[None]` evaluates to `False`, + # breaking the faster implementation used for the other python versions. + + def is_none_type(type_: Any) -> bool: + return type_ in NONE_TYPES + + +else: + + def is_none_type(type_: Any) -> bool: + for none_type in NONE_TYPES: + if type_ is none_type: + return True + return False def display_as_type(v: Type[Any]) -> str: diff --git a/pydantic/validators.py b/pydantic/validators.py --- a/pydantic/validators.py +++ b/pydantic/validators.py @@ -31,7 +31,6 @@ from . import errors from .datetime_parse import parse_date, parse_datetime, parse_duration, parse_time from .typing import ( - NONE_TYPES, AnyCallable, ForwardRef, all_literal_values, @@ -40,6 +39,7 @@ is_callable_type, is_literal_type, is_namedtuple, + is_none_type, is_typeddict, ) from .utils import almost_equal_floats, lenient_issubclass, sequence_like @@ -657,7 +657,8 @@ def find_validators( # noqa: C901 (ignore complexity) type_type = type_.__class__ if type_type == ForwardRef or type_type == TypeVar: return - if type_ in NONE_TYPES: + + if is_none_type(type_): yield none_validator return if type_ is Pattern:
pydantic/pydantic
90080ba0de12e561b138ce221b5a67dcd932ab3e
I can probably look at this this weekend... I don't think many people are using generics in 3.9 yet Yes you're right but supporting generic types seems to be rational, According to [PEP585](https://www.python.org/dev/peps/pep-0585/) legacy typing.List , typing.Dict , ... are **Deprecated** since python3.9 and will be removed from python.
diff --git a/tests/test_callable.py b/tests/test_callable.py --- a/tests/test_callable.py +++ b/tests/test_callable.py @@ -1,11 +1,18 @@ +import sys from typing import Callable import pytest from pydantic import BaseModel, ValidationError +collection_callable_types = [Callable, Callable[[int], int]] +if sys.version_info >= (3, 9): + from collections.abc import Callable as CollectionsCallable [email protected]('annotation', [Callable, Callable[[int], int]]) + collection_callable_types += [CollectionsCallable, CollectionsCallable[[int], int]] + + [email protected]('annotation', collection_callable_types) def test_callable(annotation): class Model(BaseModel): callback: annotation @@ -14,7 +21,7 @@ class Model(BaseModel): assert callable(m.callback) [email protected]('annotation', [Callable, Callable[[int], int]]) [email protected]('annotation', collection_callable_types) def test_non_callable(annotation): class Model(BaseModel): callback: annotation 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,9 @@ from collections import namedtuple -from typing import NamedTuple +from typing import Callable as TypingCallable, NamedTuple import pytest -from pydantic.typing import is_namedtuple, is_typeddict +from pydantic.typing import Literal, is_namedtuple, is_none_type, is_typeddict try: from typing import TypedDict as typing_TypedDict @@ -54,3 +54,15 @@ class Other(dict): id: int assert is_typeddict(Other) is False + + +def test_is_none_type(): + assert is_none_type(Literal[None]) is True + assert is_none_type(None) is True + assert is_none_type(type(None)) is True + assert is_none_type(6) is False + assert is_none_type({}) is False + # WARNING: It's important to test `typing.Callable` not + # `collections.abc.Callable` (even with python >= 3.9) as they behave + # differently + assert is_none_type(TypingCallable) is False
python 3.9 generic alias Callable from collections module does not behave correctly in generics # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.8 pydantic compiled: False install path: /home/user/Documents/Code/pydantic/pydantic python version: 3.9.1 (default, Dec 11 2020, 14:32:07) [GCC 7.3.0] platform: Linux-5.4.0-66-generic-x86_64-with-glibc2.31 optional deps. installed: ['devtools', 'dotenv', 'email-validator', 'typing-extensions'] ``` ``` from typing import Any, Callable, ClassVar, Dict, Generic, List, Literal, Optional, Sequence, Tuple, Type, TypeVar, Union ``` For example, the `test_iter_contained_typevars` test with replacing `typing.Callable` with `collections.abc.Callable`: ```py from collections.abc import Callable from typing import Dict, Generic, List, Optional, Union @skip_36 def test_iter_contained_typevars(): T = TypeVar('T') T2 = TypeVar('T2') class Model(GenericModel, Generic[T]): a: T assert list(iter_contained_typevars(Optional[List[Union[str, Model[T], Callable[[T2, T], str]]]])) == [T, T2, T] ``` results in ``` ----> 1 assert list(iter_contained_typevars(Optional[List[Union[str, Model[T], Callable[[T2, T], str]]]])) == [T, T2, T] pydantic-39/lib/python3.9/typing.py in inner(*args, **kwds) 260 except TypeError: 261 pass # All real errors (not unhashable args) are raised below. --> 262 return func(*args, **kwds) 263 return inner 264 pydantic-39/lib/python3.9/typing.py in __getitem__(self, parameters) 337 @_tp_cache 338 def __getitem__(self, parameters): --> 339 return self._getitem(self, parameters) 340 341 pydantic-39/lib/python3.9/typing.py in Union(self, parameters) 449 msg = "Union[arg, ...]: each arg must be a type." 450 parameters = tuple(_type_check(p, msg) for p in parameters) --> 451 parameters = _remove_dups_flatten(parameters) 452 if len(parameters) == 1: 453 return parameters[0] pydantic-39/lib/python3.9/typing.py in _remove_dups_flatten(parameters) 229 params.append(p) 230 --> 231 return tuple(_deduplicate(params)) 232 233 pydantic-39/lib/python3.9/typing.py in _deduplicate(params) 203 def _deduplicate(params): 204 # Weed out strict duplicates, preserving the first of each occurrence. --> 205 all_params = set(params) 206 if len(all_params) < len(params): 207 new_params = [] TypeError: unhashable type: 'list' ``` This came up while reading the release notes for python 3.10 where this is changed back: https://docs.python.org/3.10/whatsnew/3.10.html#collections-abc So in 3.10 this problem won't be present. However, since I don't think we're testing any of the "collection" module types particularly well, the assumption is that there might be other problems as well. We should therefore probably add some tests that check these python >= 3.9 features / generic alias cases in case they are missing.
0.0
90080ba0de12e561b138ce221b5a67dcd932ab3e
[ "tests/test_callable.py::test_callable[annotation0]", "tests/test_callable.py::test_callable[annotation1]", "tests/test_callable.py::test_callable[Callable0]", "tests/test_callable.py::test_callable[Callable1]", "tests/test_callable.py::test_non_callable[annotation0]", "tests/test_callable.py::test_non_callable[annotation1]", "tests/test_callable.py::test_non_callable[Callable0]", "tests/test_callable.py::test_non_callable[Callable1]", "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_typeddict_typing[TypedDict2]", "tests/test_typing.py::test_is_none_type" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-03-13 18:33:08+00:00
mit
4,815
pydantic__pydantic-2523
diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -184,6 +184,7 @@ def inherit_config(self_config: 'ConfigType', parent_config: 'ConfigType', **nam namespace['json_encoders'] = { **getattr(parent_config, 'json_encoders', {}), **getattr(self_config, 'json_encoders', {}), + **namespace.get('json_encoders', {}), } return type('Config', base_classes, namespace)
pydantic/pydantic
0a5f0fae7a44f7658f777e5bddfdc1e341819357
diff --git a/tests/test_main.py b/tests/test_main.py --- a/tests/test_main.py +++ b/tests/test_main.py @@ -1723,6 +1723,13 @@ class Model(Base, extra='allow'): assert Model.__fields__['b'].alias == 'B' # alias_generator still works +def test_class_kwargs_config_json_encoders(): + class Model(BaseModel, json_encoders={int: str}): + pass + + assert Model.__config__.json_encoders == {int: str} + + def test_class_kwargs_config_and_attr_conflict(): with pytest.raises(
`inherit_config` overwrites `json_encoders` from class creation 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 <!-- 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.1 pydantic compiled: False install path: [...]/lib/python3.9/site-packages/pydantic python version: 3.9.2 (default, Feb 21 2021, 06:38:26) [Clang 7.1.0 (tags/RELEASE_710/final)] platform: macOS-10.14.6-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: --> ```py import pydantic class Foo(pydantic.BaseModel): class Config: json_encoders = {int: str} print('Foo json_encoders:', Foo.__config__.json_encoders) class Bar(pydantic.BaseModel, json_encoders={int: str}): pass print('Bar json_encoders:', Bar.__config__.json_encoders) ``` Output: ``` Foo json_encoders: {<class 'int'>: <class 'str'>} Bar json_encoders: {} ``` Culprit: https://github.com/samuelcolvin/pydantic/blob/62bb2ad4921016df51abf3922c3fe51113b08939/pydantic/main.py#L184-L187 `inherit_config` overwrites `json_encoders` from class creation 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 <!-- 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.1 pydantic compiled: False install path: [...]/lib/python3.9/site-packages/pydantic python version: 3.9.2 (default, Feb 21 2021, 06:38:26) [Clang 7.1.0 (tags/RELEASE_710/final)] platform: macOS-10.14.6-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: --> ```py import pydantic class Foo(pydantic.BaseModel): class Config: json_encoders = {int: str} print('Foo json_encoders:', Foo.__config__.json_encoders) class Bar(pydantic.BaseModel, json_encoders={int: str}): pass print('Bar json_encoders:', Bar.__config__.json_encoders) ``` Output: ``` Foo json_encoders: {<class 'int'>: <class 'str'>} Bar json_encoders: {} ``` Culprit: https://github.com/samuelcolvin/pydantic/blob/62bb2ad4921016df51abf3922c3fe51113b08939/pydantic/main.py#L184-L187
0.0
0a5f0fae7a44f7658f777e5bddfdc1e341819357
[ "tests/test_main.py::test_class_kwargs_config_json_encoders" ]
[ "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_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_class_kwargs_config", "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-03-14 13:04:48+00:00
mit
4,816
pydantic__pydantic-2532
diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -248,7 +248,12 @@ def __new__(mcs, name, bases, namespace, **kwargs): # noqa C901 class_vars.update(base.__class_vars__) hash_func = base.__hash__ - config_kwargs = {key: kwargs.pop(key) for key in kwargs.keys() & BaseConfig.__dict__.keys()} + allowed_config_kwargs: SetStr = { + key + for key in dir(config) + if not (key.startswith('__') and key.endswith('__')) # skip dunder methods and attributes + } + config_kwargs = {key: kwargs.pop(key) for key in kwargs.keys() & allowed_config_kwargs} config_from_namespace = namespace.get('Config') if config_kwargs and config_from_namespace: raise TypeError('Specifying config in two places is ambiguous, use either Config attribute or class kwargs')
pydantic/pydantic
4ec6c5290528c32155d9aea0d996ddbf9e34d776
diff --git a/tests/test_main.py b/tests/test_main.py --- a/tests/test_main.py +++ b/tests/test_main.py @@ -7,6 +7,7 @@ import pytest from pydantic import ( + BaseConfig, BaseModel, ConfigError, Extra, @@ -1734,3 +1735,14 @@ class Model(BaseModel, extra='allow'): class Config: extra = 'forbid' + + +def test_class_kwargs_custom_config(): + class Base(BaseModel): + class Config(BaseConfig): + some_config = 'value' + + class Model(Base, some_config='new_value'): + a: int + + assert Model.__config__.some_config == 'new_value'
`BaseSettings`-specific configuration cannot be passed to class as keyword 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 <!-- 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.1 pydantic compiled: False install path: [...]/lib/python3.9/site-packages/pydantic python version: 3.9.2 (default, Feb 21 2021, 06:38:26) [Clang 7.1.0 (tags/RELEASE_710/final)] platform: macOS-10.14.6-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: --> The `BaseModel` metaclass ignores configuration settings specific to `BaseSettings` when these are passed as keyword arguments during class creation. They are passed on to `ABCMeta` which does not accept keyword arguments: ```py import pydantic class Foo(pydantic.BaseSettings, env_prefix='BAR_'): pass ``` Output: ``` Traceback (most recent call last): File "[...]/foo.py", line 3, in <module> class Foo(pydantic.BaseSettings, env_prefix='BAR_'): File "[...]/lib/python3.9/site-packages/pydantic/main.py", line 361, in __new__ cls = super().__new__(mcs, name, bases, new_namespace, **kwargs) File "/nix/store/cdifcrgj5phbvspzs02yglz35qql4i1x-python3-3.9.2/lib/python3.9/abc.py", line 85, in __new__ cls = super().__new__(mcls, name, bases, namespace, **kwargs) TypeError: Foo.__init_subclass__() takes no keyword arguments ```
0.0
4ec6c5290528c32155d9aea0d996ddbf9e34d776
[ "tests/test_main.py::test_class_kwargs_custom_config" ]
[ "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", "tests/test_main.py::test_model_export_dict_exclusion", "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_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_class_kwargs_config", "tests/test_main.py::test_class_kwargs_config_and_attr_conflict" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2021-03-16 12:50:06+00:00
mit
4,817
pydantic__pydantic-2536
diff --git a/pydantic/schema.py b/pydantic/schema.py --- a/pydantic/schema.py +++ b/pydantic/schema.py @@ -794,6 +794,7 @@ def field_singleton_schema( # noqa: C901 (ignore complexity) f_schema: Dict[str, Any] = {} if field.field_info is not None and field.field_info.const: f_schema['const'] = field.default + if is_literal_type(field_type): values = all_literal_values(field_type) @@ -810,8 +811,8 @@ def field_singleton_schema( # noqa: C901 (ignore complexity) # All values have the same type field_type = values[0].__class__ f_schema['enum'] = list(values) - - if lenient_issubclass(field_type, Enum): + add_field_type_to_schema(field_type, f_schema) + elif lenient_issubclass(field_type, Enum): enum_name = model_name_map[field_type] f_schema, schema_overrides = get_field_info_schema(field) f_schema.update(get_schema_ref(enum_name, ref_prefix, ref_template, schema_overrides))
pydantic/pydantic
9cc6d44682b95d02fc74242b2e51ccbb84329a28
diff --git a/tests/test_schema.py b/tests/test_schema.py --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -1784,6 +1784,22 @@ class Model(BaseModel): } +def test_literal_enum(): + class MyEnum(str, Enum): + FOO = 'foo' + BAR = 'bar' + + class Model(BaseModel): + kind: Literal[MyEnum.FOO] + + assert Model.schema() == { + 'title': 'Model', + 'type': 'object', + 'properties': {'kind': {'title': 'Kind', 'enum': ['foo'], 'type': 'string'}}, + 'required': ['kind'], + } + + def test_color_type(): class Model(BaseModel): color: Color
Schema generated for `Literal[MyEnum.MEMBER]` is too lax? ### 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 creating a model with a property typed as `Literal[MyEnum.MEMBER]`, Pydantic generates a schema that is too lax, describing the property as being any value of the enum instead of a specific one. Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.8.1 pydantic compiled: True install path: /tmp/tmp.iid8D0iv22/.venv/lib/python3.9/site-packages/pydantic python version: 3.9.2 (default, Feb 20 2021, 18:40:11) [GCC 10.2.0] platform: Linux-5.11.6-arch1-1-x86_64-with-glibc2.33 optional deps. installed: ['typing-extensions'] ``` ```py from typing import Literal from enum import Enum from pydantic import BaseModel class MyEnum(str, Enum): FOO = "foo" BAR = "bar" class ModelWithLiteralEnumMemberAndFullEnum(BaseModel): kind: Literal[MyEnum.FOO] possible_kinds: MyEnum # This property is there as a workaround for #2534 print(ModelWithLiteralEnumMemberAndFullEnum.schema_json()) # This schema is too lax ``` This gives the following schema: ```json { "title": "ModelWithLiteralEnumMemberAndFullEnum", "type": "object", "properties": { "kind": { "title": "Kind", "$ref": "#/definitions/MyEnum" }, "possible_kinds": { "$ref": "#/definitions/MyEnum" } }, "required": [ "kind", "possible_kinds" ], "definitions": { "MyEnum": { "title": "MyEnum", "description": "An enumeration.", "enum": [ "foo", "bar" ], "type": "string" } } } ``` On the other hand, when typing the property as `Literal[MyEnum.MEMBER.value]`, the correct JSON schema is generated, accepting only the specific value. This solution though has the drawback of placing the value in the object instead of the enum member (so you lose `is MyEnum.FOO` comparisons). ```py from typing import Literal from enum import Enum from pydantic import BaseModel class MyEnum(str, Enum): FOO = "foo" BAR = "bar" class ModelWithLiteralEnumValue(BaseModel): kind: Literal[MyEnum.FOO.value] print(ModelWithLiteralEnumValue.schema_json()) # But this one is specific about what value is accepted ``` which gives this schema: ```json { "title": "ModelWithLiteralEnumValue", "type": "object", "properties": { "kind": { "title": "Kind", "enum": [ "foo" ], "type": "string" } }, "required": [ "kind" ] } ``` This depends on #2534 being fixed, because we cannot even put a property typed as `Literal[MyEnum.MEMBER]` alone without the `.schema()` method crashing. You can also look at a more complete example in different Pydantic versions there: https://gist.github.com/nymous/686d38ba1aa150fefe6da6d78b1cb441 (same gist as #2534).
0.0
9cc6d44682b95d02fc74242b2e51ccbb84329a28
[ "tests/test_schema.py::test_literal_enum" ]
[ "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_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_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_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-03-16 22:05:28+00:00
mit
4,818
pydantic__pydantic-2549
diff --git a/pydantic/generics.py b/pydantic/generics.py --- a/pydantic/generics.py +++ b/pydantic/generics.py @@ -30,6 +30,15 @@ GenericModelT = TypeVar('GenericModelT', bound='GenericModel') TypeVarType = Any # since mypy doesn't allow the use of TypeVar as a type +Parametrization = Mapping[TypeVarType, Type[Any]] + +# _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: Dict[Type[Any], Parametrization] = {} + class GenericModel(BaseModel): __slots__ = () @@ -86,13 +95,15 @@ def __class_getitem__(cls: Type[GenericModelT], params: Union[Type[Any], Tuple[T create_model( model_name, __module__=model_module or cls.__module__, - __base__=cls, + __base__=(cls,) + tuple(cls.__parameterized_bases__(typevars_map)), __config__=None, __validators__=validators, **fields, ), ) + _assigned_parameters[created_model] = typevars_map + if called_globally: # create global reference and therefore allow pickling object_by_reference = None reference_name = model_name @@ -142,6 +153,70 @@ def __concrete_name__(cls: Type[Any], params: Tuple[Type[Any], ...]) -> str: params_component = ', '.join(param_names) return f'{cls.__name__}[{params_component}]' + @classmethod + def __parameterized_bases__(cls, typevars_map: Parametrization) -> Iterator[Type[Any]]: + """ + Returns unbound bases of cls parameterised to given type variables + + :param typevars_map: Dictionary of type applications for binding subclasses. + Given a generic class `Model` with 2 type variables [S, T] + and a concrete model `Model[str, int]`, + the value `{S: str, T: int}` would be passed to `typevars_map`. + :return: an iterator of generic sub classes, parameterised by `typevars_map` + and other assigned parameters of `cls` + + e.g.: + ``` + class A(GenericModel, Generic[T]): + ... + + class B(A[V], Generic[V]): + ... + + assert A[int] in B.__parameterized_bases__({V: int}) + ``` + """ + + def build_base_model( + base_model: Type[GenericModel], mapped_types: Parametrization + ) -> Iterator[Type[GenericModel]]: + base_parameters = tuple([mapped_types[param] for param in base_model.__parameters__]) + parameterized_base = base_model.__class_getitem__(base_parameters) + if parameterized_base is base_model or parameterized_base is cls: + # Avoid duplication in MRO + return + yield parameterized_base + + for base_model in cls.__bases__: + if not issubclass(base_model, GenericModel): + # not a class that can be meaningfully parameterized + continue + elif not getattr(base_model, '__parameters__', None): + # base_model is "GenericModel" (and has no __parameters__) + # or + # base_model is already concrete, and will be included transitively via cls. + continue + elif cls in _assigned_parameters: + if base_model in _assigned_parameters: + # cls is partially parameterised but not from base_model + # e.g. cls = B[S], base_model = A[S] + # B[S][int] should subclass A[int], (and will be transitively via B[int]) + # but it's not viable to consistently subclass types with arbitrary construction + # So don't attempt to include A[S][int] + continue + else: # base_model not in _assigned_parameters: + # cls is partially parameterized, base_model is original generic + # e.g. cls = B[str, T], base_model = B[S, T] + # Need to determine the mapping for the base_model parameters + mapped_types: Parametrization = { + key: typevars_map.get(value, value) for key, value in _assigned_parameters[cls].items() + } + yield from build_base_model(base_model, mapped_types) + else: + # cls is base generic, so base_class has a distinct base + # can construct the Parameterised base model using typevars_map directly + yield from build_base_model(base_model, typevars_map) + def replace_types(type_: Any, type_map: Mapping[Any, Any]) -> Any: """Return type with all occurrences of `type_map` keys recursively replaced with their values. diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -877,7 +877,7 @@ def create_model( __model_name: str, *, __config__: Optional[Type[BaseConfig]] = None, - __base__: Type['Model'], + __base__: Union[Type['Model'], Tuple[Type['Model'], ...]], __module__: str = __name__, __validators__: Dict[str, classmethod] = None, **field_definitions: Any, @@ -889,7 +889,7 @@ def create_model( __model_name: str, *, __config__: Optional[Type[BaseConfig]] = None, - __base__: Optional[Type['Model']] = None, + __base__: Union[None, Type['Model'], Tuple[Type['Model'], ...]] = None, __module__: str = __name__, __validators__: Dict[str, classmethod] = None, **field_definitions: Any, @@ -910,8 +910,10 @@ def create_model( if __base__ is not None: if __config__ is not None: raise ConfigError('to avoid confusion __config__ and __base__ cannot be used together') + if not isinstance(__base__, tuple): + __base__ = (__base__,) else: - __base__ = cast(Type['Model'], BaseModel) + __base__ = (cast(Type['Model'], BaseModel),) fields = {} annotations = {} @@ -942,7 +944,7 @@ def create_model( if __config__: namespace['Config'] = inherit_config(__config__, BaseConfig) - return type(__model_name, (__base__,), namespace) + return type(__model_name, __base__, namespace) _missing = object()
pydantic/pydantic
a35cde90af9caaa4d1670508255a38b6e361228a
OK, after some digging, I've figured out why this is happening. Due to how `create_model` is called in `GenericModel.__class_getitem__`, we have the following class relationships: * `ConcreteInnerClass[int] < ConcreteInnerClass[T]` * `BaseInnerClass[int] < BaseInnerClass[T]` * `ConcreteInnerClass[T] < BaseInnerClass[T]` But we are missing the following: * `ConcreteInnerClass[int] < BaseInnerClass[int]`
diff --git a/tests/test_generics.py b/tests/test_generics.py --- a/tests/test_generics.py +++ b/tests/test_generics.py @@ -1160,6 +1160,92 @@ class SomeGenericModel(GenericModel, Generic[T]): SomeGenericModel[str](the_alias='qwe') +@skip_36 +def test_generic_subclass(): + T = TypeVar('T') + + class A(GenericModel, Generic[T]): + ... + + class B(A[T], Generic[T]): + ... + + assert B[int].__name__ == 'B[int]' + assert issubclass(B[int], B) + assert issubclass(B[int], A[int]) + assert not issubclass(B[int], A[str]) + + +@skip_36 +def test_generic_subclass_with_partial_application(): + T = TypeVar('T') + S = TypeVar('S') + + class A(GenericModel, Generic[T]): + ... + + class B(A[S], Generic[T, S]): + ... + + PartiallyAppliedB = B[str, T] + assert issubclass(PartiallyAppliedB[int], A[int]) + assert not issubclass(PartiallyAppliedB[int], A[str]) + assert not issubclass(PartiallyAppliedB[str], A[int]) + + +@skip_36 +def test_multilevel_generic_binding(): + T = TypeVar('T') + S = TypeVar('S') + + class A(GenericModel, Generic[T, S]): + ... + + class B(A[str, T], Generic[T]): + ... + + assert B[int].__name__ == 'B[int]' + assert issubclass(B[int], A[str, int]) + assert not issubclass(B[str], A[str, int]) + + +@skip_36 +def test_generic_subclass_with_extra_type(): + T = TypeVar('T') + S = TypeVar('S') + + class A(GenericModel, Generic[T]): + ... + + class B(A[S], Generic[T, S]): + ... + + assert B[int, str].__name__ == 'B[int, str]', B[int, str].__name__ + assert issubclass(B[str, int], B) + assert issubclass(B[str, int], A[int]) + assert not issubclass(B[int, str], A[int]) + + +@skip_36 +def test_multi_inheritance_generic_binding(): + T = TypeVar('T') + + class A(GenericModel, Generic[T]): + ... + + class B(A[int], Generic[T]): + ... + + class C(B[str], Generic[T]): + ... + + assert C[float].__name__ == 'C[float]' + assert issubclass(C[float], B[str]) + assert not issubclass(C[float], B[int]) + assert issubclass(C[float], A[int]) + assert not issubclass(C[float], A[str]) + + @skip_36 def test_parse_generic_json(): T = TypeVar('T')
GenericModel - Recursive abstract class fails 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())"`: ``` pydantic version: 1.6.1 pydantic compiled: False install path: /wayfair/home/ch438l/pydantic/pydantic python version: 3.6.8 (default, Aug 10 2019, 06:54:07) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] platform: Linux-3.10.0-862.3.2.el7.x86_64-x86_64-with-centos-7.5.1804-Core optional deps. installed: ['typing-extensions', 'email-validator', 'devtools'] ``` If I try to define an attribute on a generic model to be a generic abstract class, then the model will fail to validate. Here's a failing test case: ```py @skip_36 def test_abstract_generic_type_recursion(): T = TypeVar('T') class BaseInnerClass(GenericModel, abc.ABC, Generic[T]): base_data: T @abc.abstractmethod def base_abstract(self) -> None: pass class ConcreteInnerClass(BaseInnerClass[T], Generic[T]): def base_abstract(self) -> None: return None class OuterClass(GenericModel, Generic[T]): inner_class: BaseInnerClass[T] OuterClass[int](inner_class=ConcreteInnerClass[int](base_data=2)) ``` It appears to be failing because the `isinstance(value, cls)` check is failing for the generic type.
0.0
a35cde90af9caaa4d1670508255a38b6e361228a
[ "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_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_multi_inheritance_generic_binding", "tests/test_generics.py::test_parse_generic_json" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-03-19 16:35:44+00:00
mit
4,819
pydantic__pydantic-2566
diff --git a/pydantic/fields.py b/pydantic/fields.py --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -458,17 +458,13 @@ def prepare(self) -> None: def _set_default_and_type(self) -> None: """ Set the default value, infer the type if needed and check if `None` value is valid. - - Note: to prevent side effects by calling the `default_factory` for nothing, we only call it - when we want to validate the default value i.e. when `validate_all` is set to True. """ if self.default_factory is not None: if self.type_ is Undefined: raise errors_.ConfigError( f'you need to set the type of field {self.name!r} when using `default_factory`' ) - if not self.model_config.validate_all: - return + return default_value = self.get_default()
pydantic/pydantic
7b7e70557bb80ef5f033e3e9caca68484aae78c5
I co-discovered this issue. 100% True Hi and thanks for reporting `BaseSettings` inherits from `BaseModel` with other defaults for the config including `validate_all` which is set to True by default. As explained in the [warning section in the doc](https://pydantic-docs.helpmanual.io/usage/models/#field-with-dynamic-default-value), to validate the default value of a field, we actually need to call the `default_factory`. I guess you could find a workaround in your default factory or set `validate_all = False` ```py class A(BaseSettings, validate_all=False): pass ``` We could also allow people to not validate values with `default_factory` Hope it helps in the meantime @PrettyWood Thank you, that works for now. It's still kind of strange though, I believe it should be possible to validate all values (including the default ones) on initialization. Might be better to hide this functionality under some option (`validate_on_init`), too.
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 @@ -1695,12 +1695,12 @@ class Model(BaseModel): Model() -def test_default_factory_side_effect(): - """It may call `default_factory` more than once when `validate_all` is set""" +def test_default_factory_called_once(): + """It should never call `default_factory` more than once even when `validate_all` is set""" v = 0 - def factory(): + def factory() -> int: nonlocal v v += 1 return v @@ -1712,7 +1712,20 @@ class Config: validate_all = True m1 = MyModel() - assert m1.id == 2 # instead of 1 + assert m1.id == 1 + + class MyBadModel(BaseModel): + id: List[str] = Field(default_factory=factory) + + class Config: + validate_all = True + + with pytest.raises(ValidationError) as exc_info: + MyBadModel() + assert v == 2 # `factory` has been called to run validation + assert exc_info.value.errors() == [ + {'loc': ('id',), 'msg': 'value is not a valid list', 'type': 'type_error.list'}, + ] def test_default_factory_validator_child():
BaseSettings descendants call default_factory 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 When importing `BaseSettings` descendant from another file, `default_factory` functors are always called for uninstantiated models. See the code snippet attached below. `def factory()` is called once on import, even though `B` is not even instantiated. Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.8.1 pydantic compiled: True install path: /usr/local/anaconda3/envs/dirty_3.9/lib/python3.9/site-packages/pydantic python version: 3.9.2 | packaged by conda-forge | (default, Feb 21 2021, 05:02:20) [Clang 11.0.1 ] platform: macOS-11.1-x86_64-i386-64bit optional deps. installed: ['typing-extensions'] ``` <!-- Where possible please include a self-contained code snippet describing your bug: --> The first file (`kek.py`): ```py from pydantic import BaseSettings, Field v = 0 def factory(): print('factory called') global v v += 1 return v class A(BaseSettings): pass class B(A): id: int = Field(default_factory=factory) class C(A): pass ``` The second file: ```py from kek import C ``` Expected output: empty. Actual output: `factory called`. It's also worth mentioning that `BaseModel` does not have the described behavior, importing the `BaseModel` descendants doesn't call `default_factory` functors.
0.0
7b7e70557bb80ef5f033e3e9caca68484aae78c5
[ "tests/test_edge_cases.py::test_default_factory_called_once" ]
[ "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_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_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" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2021-03-22 23:09:39+00:00
mit
4,820
pydantic__pydantic-2567
diff --git a/pydantic/networks.py b/pydantic/networks.py --- a/pydantic/networks.py +++ b/pydantic/networks.py @@ -298,7 +298,16 @@ class HttpUrl(AnyUrl): class PostgresDsn(AnyUrl): - allowed_schemes = {'postgres', 'postgresql'} + allowed_schemes = { + 'postgres', + 'postgresql', + 'postgresql+asyncpg', + 'postgresql+pg8000', + 'postgresql+psycopg2', + 'postgresql+psycopg2cffi', + 'postgresql+py-postgresql', + 'postgresql+pygresql', + } user_required = True
pydantic/pydantic
5549e8d37980f0c4b23e76c3e4cbdee147d30818
diff --git a/tests/test_networks.py b/tests/test_networks.py --- a/tests/test_networks.py +++ b/tests/test_networks.py @@ -18,7 +18,12 @@ 'https://example.org/whatever/next/', 'postgres://user:pass@localhost:5432/app', 'postgres://just-user@localhost:5432/app', + 'postgresql+asyncpg://user:pass@localhost:5432/app', + 'postgresql+pg8000://user:pass@localhost:5432/app', 'postgresql+psycopg2://postgres:postgres@localhost:5432/hatch', + 'postgresql+psycopg2cffi://user:pass@localhost:5432/app', + 'postgresql+py-postgresql://user:pass@localhost:5432/app', + 'postgresql+pygresql://user:pass@localhost:5432/app', 'foo-bar://example.org', 'foo.bar://example.org', 'foo0bar://example.org', @@ -333,6 +338,10 @@ class Model(BaseModel): assert Model(a='postgres://user:pass@localhost:5432/app').a == 'postgres://user:pass@localhost:5432/app' assert Model(a='postgresql://user:pass@localhost:5432/app').a == 'postgresql://user:pass@localhost:5432/app' + assert ( + Model(a='postgresql+asyncpg://user:pass@localhost:5432/app').a + == 'postgresql+asyncpg://user:pass@localhost:5432/app' + ) with pytest.raises(ValidationError) as exc_info: Model(a='http://example.org')
Can't use `postgresql+psycopg2://...` with `PostgresDsn ` ### 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 I'm expecting to be able to use a database connection url such as `postgresql+psycopg2://user:pass@localhost:5432/app` (a format [SQLAlchemy is supporting](https://docs.sqlalchemy.org/en/14/dialects/postgresql.html#dialect-postgresql-psycopg2-connect)). However, it doesn't seem to accept the `+psycopg2` part. Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.8.1 pydantic compiled: False install path: /Users/krisb/Code/fork/pydantic/pydantic python version: 3.7.10 (default, Apr 12 2021, 03:46:49) [Clang 12.0.0 (clang-1200.0.32.29)] platform: Darwin-20.3.0-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: --> Changed test https://github.com/samuelcolvin/pydantic/blob/7af90a8d6c1c406799ad95b81e353b386cde5745/tests/test_networks.py#L318-L318 to include ```py assert Model(a='postgresql+psycopg2://user:pass@localhost:5432/app').a == 'postgresql+psycopg2://user:pass@localhost:5432/app' ``` pytest error output: ``` ... > raise validation_error E pydantic.error_wrappers.ValidationError: 1 validation error for Model E a E URL scheme not permitted (type=value_error.url.scheme; allowed_schemes={'postgres', 'postgresql'}) pydantic/main.py:400: ValidationError ``` This is similar to https://github.com/samuelcolvin/pydantic/issues/1142, and a workaround for now is to use `AnyUrl` where this type of URL is supported.
0.0
5549e8d37980f0c4b23e76c3e4cbdee147d30818
[ "tests/test_networks.py::test_postgres_dsns" ]
[ "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_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_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_redis_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_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_test_patch": true, "is_lite": false }
2021-03-23 01:00:02+00:00
mit
4,821
pydantic__pydantic-2582
diff --git a/pydantic/typing.py b/pydantic/typing.py --- a/pydantic/typing.py +++ b/pydantic/typing.py @@ -1,5 +1,4 @@ import sys -from enum import Enum from typing import ( # type: ignore TYPE_CHECKING, AbstractSet, @@ -250,14 +249,6 @@ def display_as_type(v: Type[Any]) -> str: if not isinstance(v, typing_base) and not isinstance(v, GenericAlias) and not isinstance(v, type): v = v.__class__ - if isinstance(v, type) and issubclass(v, Enum): - if issubclass(v, int): - return 'int' - elif issubclass(v, str): - return 'str' - else: - return 'enum' - if isinstance(v, GenericAlias): # Generic alias are constructs like `list[int]` return str(v).replace('typing.', '')
pydantic/pydantic
68784f63c0219aeb2c2d816347c41222fa48cdd4
diff --git a/tests/test_generics.py b/tests/test_generics.py --- a/tests/test_generics.py +++ b/tests/test_generics.py @@ -1111,6 +1111,26 @@ class GModel(GenericModel, Generic[FieldType, ValueType]): assert m.dict() == {'field': {'foo': 'x'}} +@skip_36 +def test_generic_enums(): + T = TypeVar('T') + + class GModel(GenericModel, Generic[T]): + x: T + + class EnumA(str, Enum): + a = 'a' + + class EnumB(str, Enum): + b = 'b' + + class Model(BaseModel): + g_a: GModel[EnumA] + g_b: GModel[EnumB] + + assert set(Model.schema()['definitions']) == {'EnumA', 'EnumB', 'GModel_EnumA_', 'GModel_EnumB_'} + + @skip_36 def test_generic_with_user_defined_generic_field(): T = TypeVar('T') diff --git a/tests/test_utils.py b/tests/test_utils.py --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -6,7 +6,6 @@ import sys from copy import copy, deepcopy from distutils.version import StrictVersion -from enum import Enum from typing import Callable, Dict, List, NewType, Tuple, TypeVar, Union import pytest @@ -76,33 +75,6 @@ def test_display_as_type_generic_alias(): assert display_as_type(list[[Union[str, int]]]) == 'list[[Union[str, int]]]' -def test_display_as_type_enum(): - class SubField(Enum): - a = 1 - b = 'b' - - displayed = display_as_type(SubField) - assert displayed == 'enum' - - -def test_display_as_type_enum_int(): - class SubField(int, Enum): - a = 1 - b = 2 - - displayed = display_as_type(SubField) - assert displayed == 'int' - - -def test_display_as_type_enum_str(): - class SubField(str, Enum): - a = 'a' - b = 'b' - - displayed = display_as_type(SubField) - assert displayed == 'str' - - def test_lenient_issubclass(): class A(str): pass
Schema generation with GenericModel and multiple enums is broken since 1.8.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 Since pydantic 1.8.0 schema generation with `GenericModel` and multiple `Enum` fields using this GenericModel fails with a `KeyError`. I have tried the fix in https://github.com/samuelcolvin/pydantic/pull/2536 but this seems to be another corner case that has to be fixed. Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.8.1 pydantic compiled: True install path: /Users/philipp/.pyenv/versions/3.7.10/envs/[email protected]/lib/python3.7/site-packages/pydantic python version: 3.7.10 (default, Mar 4 2021, 21:37:12) [Clang 12.0.0 (clang-1200.0.32.29)] platform: Darwin-20.3.0-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: --> ```py from enum import Enum from typing import TypeVar, Generic, Optional from pydantic import BaseModel from pydantic.generics import GenericModel ConfigValueT = TypeVar("ConfigValueT") class ConfigOption(GenericModel, Generic[ConfigValueT]): value: ConfigValueT value_source: str class EnumA(str, Enum): a = "a" aa = "aa" class EnumB(str, Enum): b = "b" bb = "bb" class TestModel(BaseModel): option_a: ConfigOption[EnumA] option_b: ConfigOption[EnumB] # it also works with only `option_a` but not with multiple print(TestModel.schema_json()) # This works until 1.7.3 but crashes on 1.8+ ``` This results in a `KeyError`: ``` Traceback (most recent call last): File "test.py", line 29, in <module> print(TestModel.schema_json()) # This works until 1.7.3 but crashes on 1.8+ File "pydantic/main.py", line 715, in pydantic.main.BaseModel.schema_json File "pydantic/main.py", line 704, in pydantic.main.BaseModel.schema File "pydantic/schema.py", line 167, in pydantic.schema.model_schema File "pydantic/schema.py", line 548, in pydantic.schema.model_process_schema File "pydantic/schema.py", line 589, in pydantic.schema.model_type_schema File "pydantic/schema.py", line 241, in pydantic.schema.field_schema File "pydantic/schema.py", line 495, in pydantic.schema.field_type_schema File "pydantic/schema.py", line 839, in pydantic.schema.field_singleton_schema KeyError: <class '__main__.ConfigOption[str]'> ``` Thank you for your work on this amazing library!
0.0
68784f63c0219aeb2c2d816347c41222fa48cdd4
[ "tests/test_generics.py::test_generic_enums" ]
[ "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_with_user_defined_generic_field", "tests/test_generics.py::test_generic_annotated", "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_display_as_type_generic_alias", "tests/test_utils.py::test_lenient_issubclass", "tests/test_utils.py::test_lenient_issubclass_with_generic_aliases", "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_version_strict", "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_get_args[ConstrainedListValue-output_value0]", "tests/test_utils.py::test_get_args[ConstrainedList-output_value1]", "tests/test_utils.py::test_get_args[input_value2-output_value2]", "tests/test_utils.py::test_get_args[input_value3-output_value3]", "tests/test_utils.py::test_get_args[int-output_value4]", "tests/test_utils.py::test_get_args[input_value5-output_value5]", "tests/test_utils.py::test_get_args[input_value6-output_value6]", "tests/test_utils.py::test_get_args[input_value7-output_value7]", "tests/test_utils.py::test_get_args[input_value8-output_value8]", "tests/test_utils.py::test_resolve_annotations_no_module", "tests/test_utils.py::test_all_identical", "tests/test_utils.py::test_undefined_pickle" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2021-03-25 22:37:07+00:00
mit
4,822
pydantic__pydantic-2618
diff --git a/pydantic/errors.py b/pydantic/errors.py --- a/pydantic/errors.py +++ b/pydantic/errors.py @@ -48,6 +48,7 @@ 'TupleLengthError', 'ListMinLengthError', 'ListMaxLengthError', + 'ListUniqueItemsError', 'SetMinLengthError', 'SetMaxLengthError', 'FrozenSetMinLengthError', @@ -324,6 +325,11 @@ def __init__(self, *, limit_value: int) -> None: super().__init__(limit_value=limit_value) +class ListUniqueItemsError(PydanticValueError): + code = 'list.unique_items' + msg_template = 'the list has duplicated items' + + class SetMinLengthError(PydanticValueError): code = 'set.min_items' msg_template = 'ensure this value has at least {limit_value} items' diff --git a/pydantic/fields.py b/pydantic/fields.py --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -103,6 +103,7 @@ class FieldInfo(Representation): 'multiple_of', 'min_items', 'max_items', + 'unique_items', 'min_length', 'max_length', 'allow_mutation', @@ -123,6 +124,7 @@ class FieldInfo(Representation): 'multiple_of': None, 'min_items': None, 'max_items': None, + 'unique_items': None, 'allow_mutation': True, } @@ -143,6 +145,7 @@ def __init__(self, default: Any = Undefined, **kwargs: Any) -> 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.unique_items = kwargs.pop('unique_items', None) self.min_length = kwargs.pop('min_length', None) self.max_length = kwargs.pop('max_length', None) self.allow_mutation = kwargs.pop('allow_mutation', True) @@ -208,6 +211,7 @@ def Field( multiple_of: float = None, min_items: int = None, max_items: int = None, + unique_items: bool = None, min_length: int = None, max_length: int = None, allow_mutation: bool = True, @@ -241,6 +245,12 @@ def Field( 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_items: only applies to lists, requires the field to have a minimum number of + elements. The schema will have a ``minItems`` validation keyword + :param max_items: only applies to lists, requires the field to have a maximum number of + elements. The schema will have a ``maxItems`` validation keyword + :param max_items: only applies to lists, requires the field not to have duplicated + elements. The schema will have a ``uniqueItems`` 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 @@ -268,6 +278,7 @@ def Field( multiple_of=multiple_of, min_items=min_items, max_items=max_items, + unique_items=unique_items, min_length=min_length, max_length=max_length, allow_mutation=allow_mutation, diff --git a/pydantic/schema.py b/pydantic/schema.py --- a/pydantic/schema.py +++ b/pydantic/schema.py @@ -953,11 +953,9 @@ def get_annotation_from_field_info( :return: the same ``annotation`` if unmodified or a new annotation with validation in place """ constraints = field_info.get_constraints() - used_constraints: Set[str] = set() if constraints: annotation, used_constraints = get_annotation_with_constraints(annotation, field_info) - if validate_assignment: used_constraints.add('allow_mutation') @@ -1001,9 +999,18 @@ def go(type_: Any) -> Type[Any]: if is_union(origin): return Union[tuple(go(a) for a in args)] # type: ignore - if issubclass(origin, List) and (field_info.min_items is not None or field_info.max_items is not None): - used_constraints.update({'min_items', 'max_items'}) - return conlist(go(args[0]), min_items=field_info.min_items, max_items=field_info.max_items) + if issubclass(origin, List) and ( + field_info.min_items is not None + or field_info.max_items is not None + or field_info.unique_items is not None + ): + used_constraints.update({'min_items', 'max_items', 'unique_items'}) + return conlist( + go(args[0]), + min_items=field_info.min_items, + max_items=field_info.max_items, + unique_items=field_info.unique_items, + ) if issubclass(origin, Set) and (field_info.min_items is not None or field_info.max_items is not None): used_constraints.update({'min_items', 'max_items'}) diff --git a/pydantic/types.py b/pydantic/types.py --- a/pydantic/types.py +++ b/pydantic/types.py @@ -540,15 +540,18 @@ class ConstrainedList(list): # type: ignore min_items: Optional[int] = None max_items: Optional[int] = None + unique_items: Optional[bool] = None item_type: Type[T] # type: ignore @classmethod def __get_validators__(cls) -> 'CallableGenerator': yield cls.list_length_validator + if cls.unique_items: + yield cls.unique_items_validator @classmethod def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None: - update_not_none(field_schema, minItems=cls.min_items, maxItems=cls.max_items) + update_not_none(field_schema, minItems=cls.min_items, maxItems=cls.max_items, uniqueItems=cls.unique_items) @classmethod def list_length_validator(cls, v: 'Optional[List[T]]') -> 'Optional[List[T]]': @@ -566,10 +569,22 @@ 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]': + for i, value in enumerate(v, start=1): + if value in v[i:]: + raise errors.ListUniqueItemsError() + + return v -def conlist(item_type: Type[T], *, min_items: int = None, max_items: int = None) -> Type[List[T]]: + +def conlist( + item_type: Type[T], *, min_items: int = None, max_items: int = None, unique_items: bool = None +) -> Type[List[T]]: # __args__ is needed to conform to typing generics api - namespace = {'min_items': min_items, 'max_items': max_items, 'item_type': item_type, '__args__': (item_type,)} + namespace = dict( + min_items=min_items, max_items=max_items, unique_items=unique_items, item_type=item_type, __args__=(item_type,) + ) # We use new_class to be able to deal with Generic types return new_class('ConstrainedListValue', (ConstrainedList,), {}, lambda ns: ns.update(namespace))
pydantic/pydantic
afcd15522e6a8474270e5e028bc498baffac631a
As a workaround, maybe you could set the attribute type to a set? Then when a list gets passed in, it gets deduplicated automatically. Then you can override `json()` and `dict()` to convert it back to a list on the way out. @mdavis-xyz The idea of this feature is to validate that sequences have only unique items. Code below will show the idea: ```python from typing import Set from pydantic import BaseModel, Field class FooForm(BaseModel): tags: Set[int] foo = FooForm(tags=[1, 1, 2]) # tags attribute will be {1, 2} class BarForm(BaseModel): tags: Set[int] = Field(unique=True) bar = BarForm(tags=[1, 1, 2]) # will fail, because sequence has duplicate items ``` If you have any questions, feel free to ask. This is an interesting issue that clarifies some of the friction points with validation and casting within Pydantic. As a workaround, it's possible to add a validator with 'pre=True' to get the desired behavior. ```python from typing import Set, Sequence from pydantic import BaseModel, Field, validator def custom_to_set(xs: Sequence[int]) -> Set[int]: items = set([]) for item in xs: if item in items: raise ValueError(f"Duplicate item {item}") else: items.add(item) return items class Record(BaseModel): tags: Set[int] = Field(...) @validator('tags', pre=True) def validate_unique_tags(cls, value): # raise ValueError or a set return custom_to_set(value) def example() -> int: t1 = ['1', '2'] # Notice how liberal Pydantic is. This is not a validation error t2 = [1, 3, 1] # This now raises for t in [t1, t2]: print(Record(tags=t)) return 0 ``` Is this issue a bandaid for the fundamental loose casting/coercion model that Pydantic has adopted? https://github.com/samuelcolvin/pydantic/issues/1098 Your proposal does seem reasonable and clarifies the default behavior of `Set[T]` in a "strict" mode should raise a core validation error if the input sequence has any duplicates. However, this is not how Pydantic has approached validation. Perhaps it would be better to wait until Pydantic has a coherent "strict" model? With regards to the proposal, it's a bit counterintuitive to define a `Set[int]` and also set `Field(unique=True)` to get the validation to work "correctly". Similarly, `List[T] = Field(unique=True)` is counterintuitive because it's not clear why a `Set[T]` isn't being used. This case might be better solved by a custom validation/casting function with `pre=True`? @mpkocher This issue came up when I faced with an issue which I thought was a bug. I had a model and one of the fields had a type `Set[str]`, the model looked like: ```python class Form(BaseModel): tags: Set[int] ``` When one of the scripts tried to instantiate `Form` with duplicated items it simply cast sequence to a set, which was the wrong behavior for me script. After investigating I found that this is expected behavior, that why I create this PR) I agree with you that `List[T] = Field(unique=True)` can be a little bit confusing. Regarding #1098 it looks great and maybe it's better to return to this feature after `Strict Configuration` will be implemented. I'm running into similar friction points where the overly liberal casting yields surprising results.
diff --git a/tests/test_types.py b/tests/test_types.py --- a/tests/test_types.py +++ b/tests/test_types.py @@ -216,6 +216,39 @@ class ConListModelMin(BaseModel): ] +def test_constrained_list_not_unique_hashable_items(): + class ConListModelUnique(BaseModel): + v: conlist(int, unique_items=True) + + with pytest.raises(ValidationError) as exc_info: + ConListModelUnique(v=[1, 1, 2, 2, 2, 3]) + assert exc_info.value.errors() == [ + { + 'loc': ('v',), + 'msg': 'the list has duplicated items', + 'type': 'value_error.list.unique_items', + } + ] + + +def test_constrained_list_not_unique_unhashable_items(): + class ConListModelUnique(BaseModel): + v: conlist(Set[int], unique_items=True) + + m = ConListModelUnique(v=[{1}, {2}, {3}]) + assert m.v == [{1}, {2}, {3}] + + with pytest.raises(ValidationError) as exc_info: + ConListModelUnique(v=[{1}, {1}, {2}, {2}, {2}, {3}]) + assert exc_info.value.errors() == [ + { + 'loc': ('v',), + 'msg': 'the list has duplicated items', + 'type': 'value_error.list.unique_items', + } + ] + + def test_constrained_list_optional(): class Model(BaseModel): req: Optional[conlist(str, min_items=1)] = ... @@ -296,8 +329,8 @@ class ConListModel(BaseModel): def test_conlist(): class Model(BaseModel): - foo: List[int] = Field(..., min_items=2, max_items=4) - bar: conlist(str, min_items=1, max_items=4) = None + foo: List[int] = Field(..., min_items=2, max_items=4, unique_items=True) + bar: conlist(str, min_items=1, max_items=4, unique_items=False) = None assert Model(foo=[1, 2], bar=['spoon']).dict() == {'foo': [1, 2], 'bar': ['spoon']} @@ -307,12 +340,29 @@ class Model(BaseModel): with pytest.raises(ValidationError, match='ensure this value has at most 4 items'): Model(foo=list(range(5))) + with pytest.raises(ValidationError, match='the list has duplicated items'): + Model(foo=[1, 1, 2, 2]) + assert Model.schema() == { 'title': 'Model', 'type': 'object', 'properties': { - 'foo': {'title': 'Foo', 'type': 'array', 'items': {'type': 'integer'}, 'minItems': 2, 'maxItems': 4}, - 'bar': {'title': 'Bar', 'type': 'array', 'items': {'type': 'string'}, 'minItems': 1, 'maxItems': 4}, + 'foo': { + 'title': 'Foo', + 'type': 'array', + 'items': {'type': 'integer'}, + 'minItems': 2, + 'maxItems': 4, + 'uniqueItems': True, + }, + 'bar': { + 'title': 'Bar', + 'type': 'array', + 'items': {'type': 'string'}, + 'minItems': 1, + 'maxItems': 4, + 'uniqueItems': False, + }, }, 'required': ['foo'], }
Sequence constraint to enforce only unique items ### 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 feature/change is needed * [x] After submitting this, I commit to one of: * Look through open issues and helped at least one other person * Hit the "watch" button on this repo to receive notifications and I commit to help at least 2 people that ask questions in the future * Implement a Pull Request for a confirmed bug <!-- Sorry to sound so draconian, but every second saved replying to issues is time spend improving pydantic :-) --> # Feature Request Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.6.1 pydantic compiled: False install path: /Users/yuriikarabas/my-projects/pydantic/pydantic python version: 3.6.8 (v3.6.8:3c6b436a57, Dec 24 2018, 02:04:31) [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] platform: Darwin-19.6.0-x86_64-i386-64bit optional deps. installed: ['typing-extensions', 'email-validator', 'devtools'] ``` <!-- 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 feature hasn't been asked for before, or already implemented. --> <!-- Where possible please include a self-contained code snippet describing your feature request: --> The idea of this feature is to add the ability to validate that sequence types (like `list`, `tuple`, or `set`) contains only unique items. I think the best API for this feature will be something like this: ```python from typing import List from pydantic import BaseModel, EmailStr, Field class User(BaseModel): email: EmailStr class Form(BaseModel): users: List[User] = Field(unique=True) ``` In case when data contains duplicates, they will be available using `errors` method. For instance: ```python try: f = Form(users=[{'email': '[email protected]'}] * 2) except ValidationError as e: print(e.errors()) ``` Will print: ```python [ { 'loc': ('users',), 'msg': "value contains duplicate items [User(email='[email protected]')]", 'type': 'type_error.sequencenotunique', 'ctx': {'duplicates': [User(email='[email protected]')]} }, ] ``` Also, as an option, we can add a new generic type `Unique`. Usage will look like: ```python from pydantic import BaseModel, EmailStr, Unique class User(BaseModel): email: EmailStr class Form(BaseModel): users: Unique[User] ``` I have already implemented this feature in my fork. [link to commit](https://github.com/uriyyo/pydantic/commit/bb67a2e9f15da0d826ba48da117230284182c1b3)
0.0
afcd15522e6a8474270e5e028bc498baffac631a
[ "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_conlist" ]
[ "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_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_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[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_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_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2021-04-01 17:08:04+00:00
mit
4,823
pydantic__pydantic-2670
diff --git a/pydantic/main.py b/pydantic/main.py --- a/pydantic/main.py +++ b/pydantic/main.py @@ -360,8 +360,14 @@ def is_untouched(v: Any) -> bool: } or None, '__validators__': vg.validators, - '__pre_root_validators__': unique_list(pre_root_validators + pre_rv_new), - '__post_root_validators__': unique_list(post_root_validators + post_rv_new), + '__pre_root_validators__': unique_list( + pre_root_validators + pre_rv_new, + name_factory=lambda v: v.__name__, + ), + '__post_root_validators__': unique_list( + post_root_validators + post_rv_new, + name_factory=lambda skip_on_failure_and_v: skip_on_failure_and_v[1].__name__, + ), '__schema_cache__': {}, '__json_encoder__': staticmethod(json_encoder), '__custom_root_type__': _custom_root_type, diff --git a/pydantic/utils.py b/pydantic/utils.py --- a/pydantic/utils.py +++ b/pydantic/utils.py @@ -276,16 +276,25 @@ def to_camel(string: str) -> str: T = TypeVar('T') -def unique_list(input_list: Union[List[T], Tuple[T, ...]]) -> List[T]: +def unique_list( + input_list: Union[List[T], Tuple[T, ...]], + *, + name_factory: Callable[[T], str] = str, +) -> List[T]: """ Make a list unique while maintaining order. + We update the list if another one with the same name is set + (e.g. root validator overridden in subclass) """ - result = [] - unique_set = set() + result: List[T] = [] + result_names: List[str] = [] for v in input_list: - if v not in unique_set: - unique_set.add(v) + v_name = name_factory(v) + if v_name not in result_names: + result_names.append(v_name) result.append(v) + else: + result[result_names.index(v_name)] = v return result
pydantic/pydantic
b718e8e62680c2d7a42f1cf946094e1c0fe28c1d
I recently ran into this as well, and it certainly was unexpected to me. I ended up writing a small patch to the metaclass which removes overridden validators post-hoc. I post it below in case it is useful to others. ```python from pydantic import BaseModel from pydantic.main import ModelMetaclass def remove_overridden_validators(model: BaseModel) -> BaseModel: """ Currently a Pydantic bug prevents subclasses from overriding root validators. (see https://github.com/samuelcolvin/pydantic/issues/1895) This function inspects a Pydantic model and removes overriden root validators based of their `__name__`. Assumes that the latest entries in `__pre_root_validators__` and `__post_root_validators__` are earliest in the MRO, which seems to be the case. """ model.__pre_root_validators__ = list( {validator.__name__: validator for validator in model.__pre_root_validators__ }.values()) model.__post_root_validators__ = list( {validator.__name__: (skip_on_failure, validator) for skip_on_failure, validator in model.__post_root_validators__ }.values()) return model class PatchedModelMetaclass(ModelMetaclass): def __new__(*args, **kwargs): model = ModelMetaclass.__new__(*args, **kwargs) return remove_overridden_validators(model) ``` The following bit of code tests that it works as expected: ```python from pydantic import BaseModel, root_validator class A(BaseModel): # class A(BaseModel, metaclass=PatchedModelMetaclass): a: int @root_validator(pre=True) def pre_root(cls, values): print("pre rootA") return values @root_validator(pre=False) def post_root(cls, values): print("post rootA") return values class B(A): @root_validator(pre=True) def pre_root(cls, values): print("pre rootB") return values @root_validator(pre=False) def post_root(cls, values): print("post rootB") return values # This prints only from the validators in B if PatchedModelMetaclass is used B(a=1) ```
diff --git a/tests/test_validators.py b/tests/test_validators.py --- a/tests/test_validators.py +++ b/tests/test_validators.py @@ -1256,3 +1256,39 @@ def validate_foo(cls, v): with pytest.raises(RuntimeError, match='test error'): model.foo = 'raise_exception' assert model.foo == 'foo' + + +def test_overridden_root_validators(mocker): + validate_stub = mocker.stub(name='validate') + + class A(BaseModel): + x: str + + @root_validator(pre=True) + def pre_root(cls, values): + validate_stub('A', 'pre') + return values + + @root_validator(pre=False) + def post_root(cls, values): + validate_stub('A', 'post') + return values + + class B(A): + @root_validator(pre=True) + def pre_root(cls, values): + validate_stub('B', 'pre') + return values + + @root_validator(pre=False) + def post_root(cls, values): + validate_stub('B', 'post') + return values + + A(x='pika') + assert validate_stub.call_args_list == [mocker.call('A', 'pre'), mocker.call('A', 'post')] + + validate_stub.reset_mock() + + B(x='pika') + assert validate_stub.call_args_list == [mocker.call('B', 'pre'), mocker.call('B', 'post')]
Root validator called in superclass even if overridden in a subclass without calling super # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.6.1 pydantic compiled: True install path: /Users/jakub/.virtualenvs/server/lib/python3.8/site-packages/pydantic python version: 3.8.1 (default, Mar 13 2020, 20:31:03) [Clang 11.0.0 (clang-1100.0.33.17)] platform: macOS-10.15.5-x86_64-i386-64bit optional deps. installed: ['typing-extensions'] ``` Methods decorated with `root_validator` that are defined in a subclass do not override the method defined in the superclass. For methods decorated with `validator` they do override the method defined in the superclass properly. Context: I want to have a model that declares a bunch of fields and some default validators for these fields, which should be applied in every subclass, unless overridden. That works for fields decorated with `validator`, but for fields decorated with `root_validator` the validator in superclass gets called first. I couldn't find anything in the docs to disable calling the superclass validator when using the `root_validator` decorator. Also, I looked into the generic models (it seems that it would fit composition better than inheritance) and reusing validators (doesn't seem to be a good candidate to validate field contents because in my case the validation depends on the `exercise_type` and I would still have to define something like `_normalized_choices` in every subclass). ```py from __future__ import annotations from pydantic import BaseModel, root_validator, validator from typing import Union, List, Optional class ExerciseBase(BaseModel): text: Optional[str] = None choices: Optional[List[List[str]]] = None @root_validator def validate_choices(cls, values): print("ExerciseBase validate_choices") choices = values.get('choices') assert choices is None, 'Choices not allowed for this exercise type' return values class FillBlanksExercise(ExerciseBase): @root_validator def validate_choices(cls, values): print("FillBlanksExercise validate_choices") choices = values.get('choices') if choices is not None: text = values.get('text') number_of_blanks = text.count('____') assert {len(choice) for choice in choices} == {number_of_blanks}, 'Each choice must match number of blanks' return values EXERCISE_TYPES_MAPPING = { 'FillBlanksExercise': FillBlanksExercise, 'ChoiceExercise': ChoiceExercise, } exercise_data = { 'text': 'Python is a type of ____?', 'exercise_type': 'FillBlanksExercise', 'choices': [['snake'], ['bird'], ['fish'], ['dinosaur']], } exercise = FillBlanksExercise(**exercise_data) # ExerciseBase validate_choices # FillBlanksExercise validate_choices # Traceback (most recent call last): # File "/Users/jakub/Library/Application Support/JetBrains/PyCharm2020.2/scratches/scratch_2.py", line 85, in <module> # exercise = ExerciseBase.build(**exercise_data) # File "/Users/jakub/Library/Application Support/JetBrains/PyCharm2020.2/scratches/scratch_2.py", line 22, in build # return _class(**kwargs) # File "pydantic/main.py", line 346, in pydantic.main.BaseModel.__init__ # pydantic.error_wrappers.ValidationError: 1 validation error for FillBlanksExercise # __root__ # Choices not allowed for this exercise type (type=assertion_error) ```
0.0
b718e8e62680c2d7a42f1cf946094e1c0fe28c1d
[ "tests/test_validators.py::test_overridden_root_validators" ]
[ "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_field_that_is_being_validated_is_excluded_from_validator_values", "tests/test_validators.py::test_exceptions_in_field_validators_restore_original_field_value" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2021-04-13 21:25:00+00:00
mit
4,824
pydantic__pydantic-2672
diff --git a/pydantic/__init__.py b/pydantic/__init__.py --- a/pydantic/__init__.py +++ b/pydantic/__init__.py @@ -78,6 +78,8 @@ 'conlist', 'ConstrainedSet', 'conset', + 'ConstrainedFrozenSet', + 'confrozenset', 'ConstrainedStr', 'constr', 'PyObject', diff --git a/pydantic/errors.py b/pydantic/errors.py --- a/pydantic/errors.py +++ b/pydantic/errors.py @@ -36,7 +36,6 @@ 'IntegerError', 'FloatError', 'PathError', - '_PathValueError', 'PathNotExistsError', 'PathNotAFileError', 'PathNotADirectoryError', @@ -49,11 +48,14 @@ 'TupleLengthError', 'ListMinLengthError', 'ListMaxLengthError', + 'SetMinLengthError', + 'SetMaxLengthError', + 'FrozenSetMinLengthError', + 'FrozenSetMaxLengthError', 'AnyStrMinLengthError', 'AnyStrMaxLengthError', 'StrError', 'StrRegexError', - '_NumberBoundError', 'NumberNotGtError', 'NumberNotGeError', 'NumberNotLtError', @@ -338,6 +340,22 @@ def __init__(self, *, limit_value: int) -> None: super().__init__(limit_value=limit_value) +class FrozenSetMinLengthError(PydanticValueError): + code = 'frozenset.min_items' + msg_template = 'ensure this value has at least {limit_value} items' + + def __init__(self, *, limit_value: int) -> None: + super().__init__(limit_value=limit_value) + + +class FrozenSetMaxLengthError(PydanticValueError): + code = 'frozenset.max_items' + msg_template = 'ensure this value has at most {limit_value} items' + + def __init__(self, *, limit_value: int) -> None: + super().__init__(limit_value=limit_value) + + class AnyStrMinLengthError(PydanticValueError): code = 'any_str.min_length' msg_template = 'ensure this value has at least {limit_value} characters' diff --git a/pydantic/fields.py b/pydantic/fields.py --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -618,6 +618,13 @@ def _type_analysis(self) -> None: # noqa: C901 (ignore complexity) self.type_ = get_args(self.type_)[0] self.shape = SHAPE_SET elif issubclass(origin, FrozenSet): + # Create self validators + get_validators = getattr(self.type_, '__get_validators__', None) + if get_validators: + self.class_validators.update( + {f'frozenset_{i}': Validator(validator, pre=True) for i, validator in enumerate(get_validators())} + ) + self.type_ = get_args(self.type_)[0] self.shape = SHAPE_FROZENSET elif issubclass(origin, Deque): diff --git a/pydantic/networks.py b/pydantic/networks.py --- a/pydantic/networks.py +++ b/pydantic/networks.py @@ -12,8 +12,8 @@ from typing import ( TYPE_CHECKING, Any, + Collection, Dict, - FrozenSet, Generator, Optional, Pattern, @@ -123,7 +123,7 @@ class AnyUrl(str): strip_whitespace = True min_length = 1 max_length = 2 ** 16 - allowed_schemes: Optional[Set[str]] = None + allowed_schemes: Optional[Collection[str]] = None tld_required: bool = False user_required: bool = False host_required: bool = True @@ -249,7 +249,7 @@ def validate_parts(cls, parts: 'Parts') -> 'Parts': raise errors.UrlSchemeError() if cls.allowed_schemes and scheme.lower() not in cls.allowed_schemes: - raise errors.UrlSchemePermittedError(cls.allowed_schemes) + raise errors.UrlSchemePermittedError(set(cls.allowed_schemes)) port = parts['port'] if port is not None and int(port) > 65_535: @@ -383,7 +383,7 @@ def stricturl( max_length: int = 2 ** 16, tld_required: bool = True, host_required: bool = True, - allowed_schemes: Optional[Union[FrozenSet[str], Set[str]]] = None, + allowed_schemes: Optional[Collection[str]] = None, ) -> Type[AnyUrl]: # use kwargs then define conf in a dict to aid with IDE type hinting namespace = dict( diff --git a/pydantic/schema.py b/pydantic/schema.py --- a/pydantic/schema.py +++ b/pydantic/schema.py @@ -48,6 +48,7 @@ from .types import ( ConstrainedDecimal, ConstrainedFloat, + ConstrainedFrozenSet, ConstrainedInt, ConstrainedList, ConstrainedSet, @@ -57,6 +58,7 @@ conbytes, condecimal, confloat, + confrozenset, conint, conlist, conset, @@ -962,7 +964,7 @@ def go(type_: Any) -> Type[Any]: if ( is_literal_type(annotation) or isinstance(type_, ForwardRef) - or lenient_issubclass(type_, (ConstrainedList, ConstrainedSet)) + or lenient_issubclass(type_, (ConstrainedList, ConstrainedSet, ConstrainedFrozenSet)) ): return type_ origin = get_origin(type_) @@ -985,6 +987,10 @@ def go(type_: Any) -> Type[Any]: used_constraints.update({'min_items', 'max_items'}) return conset(go(args[0]), min_items=field_info.min_items, max_items=field_info.max_items) + if issubclass(origin, FrozenSet) and (field_info.min_items is not None or field_info.max_items is not None): + used_constraints.update({'min_items', 'max_items'}) + return confrozenset(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 @@ -1008,7 +1014,16 @@ def constraint_func(**kwargs: Any) -> Type[Any]: attrs = ('max_length', 'min_length', 'regex') constraint_func = conbytes elif issubclass(type_, numeric_types) and not issubclass( - type_, (ConstrainedInt, ConstrainedFloat, ConstrainedDecimal, ConstrainedList, ConstrainedSet, bool) + type_, + ( + ConstrainedInt, + ConstrainedFloat, + ConstrainedDecimal, + ConstrainedList, + ConstrainedSet, + ConstrainedFrozenSet, + bool, + ), ): # Is numeric type attrs = ('gt', 'lt', 'ge', 'le', 'multiple_of') diff --git a/pydantic/types.py b/pydantic/types.py --- a/pydantic/types.py +++ b/pydantic/types.py @@ -12,6 +12,7 @@ Callable, ClassVar, Dict, + FrozenSet, List, Optional, Pattern, @@ -36,6 +37,7 @@ constr_strip_whitespace, decimal_validator, float_validator, + frozenset_validator, int_validator, list_validator, number_multiple_validator, @@ -62,6 +64,8 @@ 'conlist', 'ConstrainedSet', 'conset', + 'ConstrainedFrozenSet', + 'confrozenset', 'ConstrainedStr', 'constr', 'PyObject', @@ -484,6 +488,48 @@ def conset(item_type: Type[T], *, min_items: int = None, max_items: int = None) return new_class('ConstrainedSetValue', (ConstrainedSet,), {}, lambda ns: ns.update(namespace)) +# This types superclass should be FrozenSet[T], but cython chokes on that... +class ConstrainedFrozenSet(frozenset): # type: ignore + # Needed for pydantic to detect that this is a set + __origin__ = frozenset + __args__: FrozenSet[Type[T]] # type: ignore + + min_items: Optional[int] = None + max_items: Optional[int] = None + item_type: Type[T] # type: ignore + + @classmethod + def __get_validators__(cls) -> 'CallableGenerator': + yield cls.frozenset_length_validator + + @classmethod + def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None: + update_not_none(field_schema, minItems=cls.min_items, maxItems=cls.max_items) + + @classmethod + def frozenset_length_validator(cls, v: 'Optional[FrozenSet[T]]') -> 'Optional[FrozenSet[T]]': + if v is None: + return None + + v = frozenset_validator(v) + v_len = len(v) + + if cls.min_items is not None and v_len < cls.min_items: + raise errors.FrozenSetMinLengthError(limit_value=cls.min_items) + + if cls.max_items is not None and v_len > cls.max_items: + raise errors.FrozenSetMaxLengthError(limit_value=cls.max_items) + + return v + + +def confrozenset(item_type: Type[T], *, min_items: int = None, max_items: int = None) -> Type[FrozenSet[T]]: + # __args__ is needed to conform to typing generics api + namespace = {'min_items': min_items, 'max_items': max_items, 'item_type': item_type, '__args__': [item_type]} + # We use new_class to be able to deal with Generic types + return new_class('ConstrainedFrozenSetValue', (ConstrainedFrozenSet,), {}, lambda ns: ns.update(namespace)) + + # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ LIST TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # This types superclass should be List[T], but cython chokes on that...
pydantic/pydantic
0d1ed534acd7bedbbbaae72772d1ff83b10aa7b9
Hello @snazzyfox Unfortunately we currently have some [custom logic](https://github.com/samuelcolvin/pydantic/blob/master/pydantic/schema.py#L820), which doesn't support `Frozenset` as the origin is `frozenset`. We could probably just add a `if issubclass(origin, frozenset) ...` and add the immutability in `conset` or duplicate some logic to have a `confrozenset` Thanks for taking a look! This totally makes sense. I think whether we create `confrozenset` or `conset(frozen=True)` depends on if we want to also duplicate the `ConstrainedSet` class. The code for frozen sets will most probably be almost identical, just with a different base class. If there's a way we can update/reuse the existing class, adding a immutable option to `conset` would make more sense.
diff --git a/tests/mypy/modules/success.py b/tests/mypy/modules/success.py --- a/tests/mypy/modules/success.py +++ b/tests/mypy/modules/success.py @@ -36,6 +36,7 @@ StrictInt, StrictStr, root_validator, + stricturl, validate_arguments, validator, ) @@ -242,6 +243,10 @@ class Config: validated.my_dir_path.absolute() validated.my_dir_path_str.absolute() +stricturl(allowed_schemes={'http'}) +stricturl(allowed_schemes=frozenset({'http'})) +stricturl(allowed_schemes=('s3', 's3n', 's3a')) + class Config(BaseConfig): title = 'Record' diff --git a/tests/test_schema.py b/tests/test_schema.py --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -28,7 +28,7 @@ import pytest from typing_extensions import Literal -from pydantic import BaseModel, Extra, Field, ValidationError, conlist, conset, validator +from pydantic import BaseModel, Extra, Field, ValidationError, confrozenset, conlist, conset, validator from pydantic.color import Color from pydantic.dataclasses import dataclass from pydantic.generics import GenericModel @@ -1460,6 +1460,7 @@ class Foo(BaseModel): ({'gt': 0}, Callable[[int], int]), ({'gt': 0}, conlist(int, min_items=4)), ({'gt': 0}, conset(int, min_items=4)), + ({'gt': 0}, confrozenset(int, min_items=4)), ], ) def test_unenforced_constraints_schema(kwargs, type_): diff --git a/tests/test_types.py b/tests/test_types.py --- a/tests/test_types.py +++ b/tests/test_types.py @@ -64,6 +64,7 @@ conbytes, condecimal, confloat, + confrozenset, conint, conlist, conset, @@ -529,6 +530,97 @@ class Model(BaseModel): assert Model().foo is None +def test_confrozenset(): + class Model(BaseModel): + foo: FrozenSet[int] = Field(..., min_items=2, max_items=4) + bar: confrozenset(str, min_items=1, max_items=4) = None + + m = Model(foo=[1, 2], bar=['spoon']) + assert m.dict() == {'foo': {1, 2}, 'bar': {'spoon'}} + assert isinstance(m.foo, frozenset) + assert isinstance(m.bar, frozenset) + + assert Model(foo=[1, 1, 1, 2, 2], bar=['spoon']).dict() == {'foo': {1, 2}, 'bar': {'spoon'}} + + with pytest.raises(ValidationError, match='ensure this value has at least 2 items'): + Model(foo=[1]) + + with pytest.raises(ValidationError, match='ensure this value has at most 4 items'): + Model(foo=list(range(5))) + + assert Model.schema() == { + 'title': 'Model', + 'type': 'object', + 'properties': { + 'foo': { + 'title': 'Foo', + 'type': 'array', + 'items': {'type': 'integer'}, + 'uniqueItems': True, + 'minItems': 2, + 'maxItems': 4, + }, + 'bar': { + 'title': 'Bar', + 'type': 'array', + 'items': {'type': 'string'}, + 'uniqueItems': True, + 'minItems': 1, + 'maxItems': 4, + }, + }, + 'required': ['foo'], + } + + with pytest.raises(ValidationError) as exc_info: + Model(foo=[1, 'x', 'y']) + errors = exc_info.value.errors() + assert len(errors) == 2 + assert all(error['msg'] == 'value is not a valid integer' for error in errors) + + with pytest.raises(ValidationError) as exc_info: + Model(foo=1) + assert exc_info.value.errors() == [ + {'loc': ('foo',), 'msg': 'value is not a valid frozenset', 'type': 'type_error.frozenset'} + ] + + +def test_confrozenset_not_required(): + class Model(BaseModel): + foo: Optional[FrozenSet[int]] = None + + assert Model(foo=None).foo is None + assert Model().foo is None + + +def test_constrained_frozenset_optional(): + class Model(BaseModel): + req: Optional[confrozenset(str, min_items=1)] = ... + opt: Optional[confrozenset(str, min_items=1)] + + assert Model(req=None).dict() == {'req': None, 'opt': None} + assert Model(req=None, opt=None).dict() == {'req': None, 'opt': None} + + with pytest.raises(ValidationError) as exc_info: + Model(req=frozenset(), opt=frozenset()) + assert exc_info.value.errors() == [ + { + 'loc': ('req',), + 'msg': 'ensure this value has at least 1 items', + 'type': 'value_error.frozenset.min_items', + 'ctx': {'limit_value': 1}, + }, + { + 'loc': ('opt',), + 'msg': 'ensure this value has at least 1 items', + 'type': 'value_error.frozenset.min_items', + 'ctx': {'limit_value': 1}, + }, + ] + + assert Model(req={'a'}, opt={'a'}).dict() == {'req': {'a'}, 'opt': {'a'}} + + class ConStringModel(BaseModel): v: constr(max_length=10) = 'foobar'
min_items not enforcable for FrozenSet # Bug Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.6.1 pydantic compiled: True install path: /home/snazzy/code/test-project/venv/lib/python3.8/site-packages/pydantic python version: 3.8.2 (default, Jul 16 2020, 14:00:26) [GCC 9.3.0] platform: Linux-5.4.0-42-generic-x86_64-with-glibc2.29 optional deps. installed: ['typing-extensions'] ``` ## Code Example This works fine: ```py from pydantic import BaseModel, Field from typing import Set class ModelOne(BaseModel): my_set: Set = Field(..., min_items=1) this_should_fail = ModelOne(my_set=set()) ``` Using `FrozenSet` instead of `Set` doesn't work: ```py from pydantic import BaseModel, Field from typing import FrozenSet class ModelTwo(BaseModel): my_frozen_set: FrozenSet = Field(..., min_items=1) ``` This causes an error at definition time: ``` Traceback (most recent call last): File "<input>", line 1, in <module> File "pydantic/main.py", line 252, in pydantic.main.ModelMetaclass.__new__ File "pydantic/fields.py", line 308, in pydantic.fields.ModelField.infer File "pydantic/schema.py", line 864, in pydantic.schema.get_annotation_from_field_info ValueError: On field "my_frozen_set" the following field constraints are set but not enforced: min_items. For more details see https://pydantic-docs.helpmanual.io/usage/schema/#unenforced-field-constraints ``` Since `FrozenSet` is simply the immutable version of `Set`, it should be possible to use `min_items` to validate the size of the set. --- Edit: The reason I expected `FrozenSet` to work the same way as mutable `Set` is because [the docs](https://pydantic-docs.helpmanual.io/usage/types/#typing-iterables) describe them in the exact same manner. Even though frozen sets are not mentioned in the [constrained types](https://pydantic-docs.helpmanual.io/usage/types/#constrained-types) section, it's a little natural to (wrongly) assume parallel functionalities are available for it.
0.0
0d1ed534acd7bedbbbaae72772d1ff83b10aa7b9
[ "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_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_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_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_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[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_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_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_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2021-04-13 21:56:38+00:00
mit
4,825
pydantic__pydantic-2711
diff --git a/pydantic/schema.py b/pydantic/schema.py --- a/pydantic/schema.py +++ b/pydantic/schema.py @@ -895,7 +895,8 @@ def encode_default(dft: Any) -> Any: return dft elif sequence_like(dft): t = dft.__class__ - return t(encode_default(v) for v in dft) + 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:
pydantic/pydantic
17eb82cd503a1e786e648d7b436c538779b6de9c
diff --git a/tests/test_schema.py b/tests/test_schema.py --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -15,6 +15,7 @@ Generic, Iterable, List, + NamedTuple, NewType, Optional, Set, @@ -2294,6 +2295,28 @@ class ModelModified(BaseModel): } +def test_namedtuple_default(): + class Coordinates(NamedTuple): + x: float + y: float + + class LocationBase(BaseModel): + coords: Coordinates = Coordinates(0, 0) + + assert LocationBase.schema() == { + 'title': 'LocationBase', + 'type': 'object', + 'properties': { + 'coords': { + 'title': 'Coords', + 'default': Coordinates(x=0, y=0), + 'type': 'array', + 'items': [{'title': 'X', 'type': 'number'}, {'title': 'Y', 'type': 'number'}], + } + }, + } + + @pytest.mark.skipif( sys.version_info < (3, 7), reason='schema generation for generic fields is not available in python < 3.7' )
schema_json() fails for optional namedtuple fields with default value ### 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 trying to generate a schema for a model with an optional `NamedTuple` field which have a default value, `schema_json()` fails when trying to unpack parameters for the tuple: ``` Traceback (most recent call last): File "<input>", line 1, in <module> File "pydantic/main.py", line 715, in pydantic.main.BaseModel.schema_json File "pydantic/main.py", line 704, in pydantic.main.BaseModel.schema File "pydantic/schema.py", line 167, in pydantic.schema.model_schema File "pydantic/schema.py", line 548, in pydantic.schema.model_process_schema File "pydantic/schema.py", line 589, in pydantic.schema.model_type_schema File "pydantic/schema.py", line 234, in pydantic.schema.field_schema File "pydantic/schema.py", line 202, in pydantic.schema.get_field_info_schema File "pydantic/schema.py", line 892, in genexpr TypeError: <lambda>() missing 1 required positional argument: 'y' ``` ```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) ... ``` Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.8.1 pydantic compiled: True install path: /venv/lib/python3.9/site-packages/pydantic python version: 3.9.0+ (default, Oct 20 2020, 08:43:38) [GCC 9.3.0] platform: Linux-5.4.0-72-generic-x86_64-with-glibc2.31 optional deps. installed: ['dotenv', 'typing-extensions'] ``` ```py from typing import List, Optional, NamedTuple from pydantic import BaseModel class Coordinates(NamedTuple): x: float y: float class LocationBase(BaseModel): name: str coords: Optional[Coordinates] = Coordinates(0, 0) zoom: Optional[int] = 10 LocationBase.schema_json() ```
0.0
17eb82cd503a1e786e648d7b436c538779b6de9c
[ "tests/test_schema.py::test_namedtuple_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_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_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-04-28 13:48:41+00:00
mit
4,826
pydantic__pydantic-2720
diff --git a/pydantic/config.py b/pydantic/config.py --- a/pydantic/config.py +++ b/pydantic/config.py @@ -38,21 +38,21 @@ class Extra(str, Enum): class BaseConfig: - title = None - anystr_lower = False - anystr_strip_whitespace = False - min_anystr_length = None - max_anystr_length = None - validate_all = False - extra = Extra.ignore - allow_mutation = True - frozen = False - allow_population_by_field_name = False - use_enum_values = False + title: Optional[str] = None + anystr_lower: bool = False + anystr_strip_whitespace: bool = False + min_anystr_length: int = 0 + max_anystr_length: Optional[int] = None + validate_all: bool = False + extra: Extra = Extra.ignore + allow_mutation: bool = True + frozen: bool = False + allow_population_by_field_name: bool = False + use_enum_values: bool = False fields: Dict[str, Union[str, Dict[str, str]]] = {} - validate_assignment = False + validate_assignment: bool = False error_msg_templates: Dict[str, str] = {} - arbitrary_types_allowed = False + arbitrary_types_allowed: bool = False orm_mode: bool = False getter_dict: Type[GetterDict] = GetterDict alias_generator: Optional[Callable[[str], str]] = None diff --git a/pydantic/validators.py b/pydantic/validators.py --- a/pydantic/validators.py +++ b/pydantic/validators.py @@ -193,7 +193,7 @@ def anystr_length_validator(v: 'StrBytes', config: 'BaseConfig') -> 'StrBytes': v_len = len(v) min_length = config.min_anystr_length - if min_length is not None and v_len < min_length: + if v_len < min_length: raise errors.AnyStrMinLengthError(limit_value=min_length) max_length = config.max_anystr_length @@ -470,11 +470,11 @@ def literal_validator(v: Any) -> Any: 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 - if min_length is not None and v_len < min_length: + min_length = field.type_.min_length if field.type_.min_length is not None else config.min_anystr_length + if v_len < min_length: raise errors.AnyStrMinLengthError(limit_value=min_length) - max_length = field.type_.max_length or config.max_anystr_length + max_length = field.type_.max_length if field.type_.max_length is not None else config.max_anystr_length if max_length is not None and v_len > max_length: raise errors.AnyStrMaxLengthError(limit_value=max_length)
pydantic/pydantic
bd61f1b6ee6cebfd997bf75cc47baa5f8d3df22e
diff --git a/tests/mypy/modules/success.py b/tests/mypy/modules/success.py --- a/tests/mypy/modules/success.py +++ b/tests/mypy/modules/success.py @@ -12,8 +12,10 @@ from pydantic import ( UUID1, + BaseConfig, BaseModel, DirectoryPath, + Extra, FilePath, FutureDate, Json, @@ -239,3 +241,9 @@ class Config: validated.my_file_path_str.absolute() validated.my_dir_path.absolute() validated.my_dir_path_str.absolute() + + +class Config(BaseConfig): + title = 'Record' + extra = Extra.ignore + max_anystr_length = 1234 diff --git a/tests/test_types.py b/tests/test_types.py --- a/tests/test_types.py +++ b/tests/test_types.py @@ -572,6 +572,24 @@ class Model(BaseModel): assert m.v == 'ABCD' +def test_constrained_str_max_length_0(): + class Model(BaseModel): + v: constr(max_length=0) + + m = Model(v='') + assert m.v == '' + with pytest.raises(ValidationError) as exc_info: + Model(v='qwe') + assert exc_info.value.errors() == [ + { + 'loc': ('v',), + 'msg': 'ensure this value has at most 0 characters', + 'type': 'value_error.any_str.max_length', + 'ctx': {'limit_value': 0}, + } + ] + + def test_module_import(): class PyObjectModel(BaseModel): module: PyObject = 'os.path'
Incomplete type annotations in BaseConfig yield mypy errors when Config is defined from BaseConfig ### 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 1. The `BaseConfig` is missing type annotations for a few fields. Inheriting from `BaseConfig` and setting values yields type errors from `mypy`. ```python from pydantic import BaseConfig, BaseModel, Extra class Record(BaseModel): alpha: str beta: str class Config(BaseConfig): title = "Record" extra = Extra.ignore max_anystr_length = 1234 ``` yields ```bash mypy --version && mypy example.py mypy 0.812 example.py:9: error: Incompatible types in assignment (expression has type "str", base class "BaseConfig" defined the type as "None") [assignment] example.py:11: error: Incompatible types in assignment (expression has type "int", base class "BaseConfig" defined the type as "None") [assignment] Found 2 errors in 1 file (checked 1 source file) ``` I believe the type annotations should be: ```python from typing import Union, Optional class BaseConfig: title: Optional[str] = None min_anystr_length: Optional[int] = None # can this just be int = 0 ? max_anystr_length: Optional[int] = None extra = Union[str, Extra] = Extra.ignore ``` Inheriting from `BaseConfig` is useful for autocomplete and avoids typos like the following. ```python from pydantic import BaseModel class Point(BaseModel): x: int y: int class Config: extras = "forbid" ``` 2. The [Config docs](https://pydantic-docs.helpmanual.io/usage/model_config/) look to be inconsistent with the default values defined in `BaseConfig`. - the default for `max_anystr_length` is listed as `2 ** 16` in the docs, however, `None` is defined in `BaseConfig` (i.e., there is no limit) - Setting `max_anystr_length = 0` ignores the validation completely and has a different semantic meaning than any other positive integer. In other words, `max_anystr_length = 0` is the same as `max_anystr_length = None`. - Similarly, the default for `min_anystr_length` is listed as `0` in the docs, but the listed default is `None` in `BaseConfig`. If these are semantically the same, then perhaps set `min_anystr_length:int = 0` as the default? - In general, it might be useful to clarify the truthyness of these `0` vs `None` values Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.8.1 pydantic compiled: False python version: 3.9.2 | packaged by conda-forge | (default, Feb 21 2021, 05:02:20) [Clang 11.0.1 ] platform: macOS-11.2.3-x86_64-i386-64bit optional deps. installed: ['typing-extensions'] ```
0.0
bd61f1b6ee6cebfd997bf75cc47baa5f8d3df22e
[ "tests/test_types.py::test_constrained_str_max_length_0" ]
[ "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_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_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_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[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_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_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_test_patch": true, "is_lite": false }
2021-05-01 07:09:46+00:00
mit
4,827
pydantic__pydantic-2761
diff --git a/pydantic/validators.py b/pydantic/validators.py --- a/pydantic/validators.py +++ b/pydantic/validators.py @@ -558,7 +558,10 @@ def pattern_validator(v: Any) -> Pattern[str]: def make_namedtuple_validator(namedtuple_cls: Type[NamedTupleT]) -> Callable[[Tuple[Any, ...]], NamedTupleT]: from .annotated_types import create_model_from_namedtuple - NamedTupleModel = create_model_from_namedtuple(namedtuple_cls) + NamedTupleModel = create_model_from_namedtuple( + namedtuple_cls, + __module__=namedtuple_cls.__module__, + ) namedtuple_cls.__pydantic_model__ = NamedTupleModel # type: ignore[attr-defined] def namedtuple_validator(values: Tuple[Any, ...]) -> NamedTupleT: @@ -579,7 +582,11 @@ def make_typeddict_validator( ) -> Callable[[Any], Dict[str, Any]]: from .annotated_types import create_model_from_typeddict - TypedDictModel = create_model_from_typeddict(typeddict_cls, __config__=config) + TypedDictModel = create_model_from_typeddict( + typeddict_cls, + __config__=config, + __module__=typeddict_cls.__module__, + ) typeddict_cls.__pydantic_model__ = TypedDictModel # type: ignore[attr-defined] def typeddict_validator(values: 'TypedDict') -> Dict[str, Any]:
pydantic/pydantic
5921d5ec96465c0b3ce5a3e0207843fabcd339a9
Hi @jameysharp Yep you're right but the workaround is easy (just not documented). Just like `dataclass` or `TypedDict`, _pydantic_ will attach a `BaseModel` to the main class under `__pydantic_model__`. So you should be able to make it work by running `Tup.__pydantic_model__.update_forward_refs()` (I'm traveling so can't check on my phone for sure) Oh, that's interesting. It doesn't work, but now I know things I didn't before. :grin: If I call `Tup.__pydantic_model__.update_forward_refs()` immediately after declaring the `NamedTuple`, it fails with `AttributeError: type object 'Tup' has no attribute '__pydantic_model__'`, which seems reasonable. If I call it after declaring the Pydantic model, then I get a different error (and a similar result in the real application I stripped this down from): `NameError: name 'PositiveInt' is not defined` So it doesn't seem to be resolving the names using the correct global scope. My current hypothesis is that the same thing is happening at model definition time, but the error is hidden then because it's indistinguishable from a forward reference, even though this isn't actually a forward reference. By contrast, declaring the `NamedTuple` field's type as `"int"` without future annotations, or as `int` with future annotations, works fine even without an `update_forward_refs` call, I assume because that name is bound in any scope. So I think there are multiple bugs here: 1. If people are expected to use `Foo.__pydantic_model__.update_forward_refs()`, then the `ConfigError` should say that instead of `Foo.update_forward_refs()`, and the documentation should cover that case. 2. Maybe the implicit `__pydantic_model__` needs to be tied to the same module as the class which it wraps, somehow? Yes it is added of course by pydantic once used in a BaseModel. A plain named tuple does not have this attribute so you need to call it after declaring your model. And for the context you're right locals are not the same. So in your case it should work with something like `Tup.__pydantic_model__.update_forward_refs(PositiveInt=PositiveInt)` We can (and should?) forward locals and stuff to resolve probably forward refs but it probably will never be perfect. So some doc and a better error message are probably a good idea as well But `PositiveInt` isn't a local here, it's imported in the module at global scope. The [Postponed Annotations](https://pydantic-docs.helpmanual.io/usage/postponed_annotations/) section of the documentation says that should work. That's why I think the synthesized `__pydantic_model__` is referencing the wrong `module.__dict__`. Yep I know I meant "we can forward more than just the module" sorry if I was not clear. As I told you I'm on my phone but if you want to change your local pydantic you can try to change https://github.com/samuelcolvin/pydantic/blob/master/pydantic/validators.py#L561 and set `__module__` like it's done for dataclass https://github.com/samuelcolvin/pydantic/blob/master/pydantic/dataclasses.py#L186 If you want to open a fix you're more than welcome 😉 If not I'll have a look and open a fix end of next week! Thanks for reporting!
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 @@ -11,7 +11,7 @@ import pytest from typing_extensions import TypedDict -from pydantic import BaseModel, ValidationError +from pydantic import BaseModel, PositiveInt, ValidationError if sys.version_info < (3, 9): try: @@ -123,6 +123,23 @@ class Model(BaseModel): ] +def test_namedtuple_postponed_annotation(): + """ + https://github.com/samuelcolvin/pydantic/issues/2760 + """ + + class Tup(NamedTuple): + v: 'PositiveInt' + + class Model(BaseModel): + t: Tup + + # The effect of issue #2760 is that this call raises a `ConfigError` even though the type declared on `Tup.v` + # references a binding in this module's global scope. + with pytest.raises(ValidationError): + Model.parse_obj({'t': [-1]}) + + def test_typeddict(): class TD(TypedDict): a: int @@ -253,3 +270,14 @@ class Model(BaseModel): }, }, } + + +def test_typeddict_postponed_annotation(): + class DataTD(TypedDict): + v: 'PositiveInt' + + class Model(BaseModel): + t: DataTD + + with pytest.raises(ValidationError): + Model.parse_obj({'t': {'v': -1}})
NamedTuple doesn't resolve postponed annotations ### 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.8.1 pydantic compiled: False install path: /nix/store/1f6nk37c7df54cm8b3rlnn6pidaa3mrp-python3.8-pydantic-1.8.1/lib/python3.8/site-packages/pydantic python version: 3.8.8 (default, Feb 19 2021, 11:04:50) [GCC 9.3.0] platform: Linux-5.4.114-x86_64-with optional deps. installed: ['typing-extensions'] ``` Here's the smallest program I could come up with that fails under `from __future__ import annotations` but works without it: ```py from __future__ import annotations from pydantic import BaseModel, PositiveInt from typing import NamedTuple class Tup(NamedTuple): v: PositiveInt class Mod(BaseModel): t: Tup print(Mod.parse_obj({"t": [3]})) ``` The call to `parse_obj` raises this exception: `pydantic.errors.ConfigError: field "v" not yet prepared so type is still a ForwardRef, you might need to call Tup.update_forward_refs().` But there is no `update_forward_refs` on `NamedTuple` instances. Just using a base `int` in the `NamedTuple` doesn't exhibit the same problem, but of course it also doesn't check the constraints I want. My current workaround is to just not use `from __future__ import annotations` in the module where I declare and use the `NamedTuple`, but I was hoping to use the new style consistently throughout the project.
0.0
5921d5ec96465c0b3ce5a3e0207843fabcd339a9
[ "tests/test_annotated_types.py::test_namedtuple_postponed_annotation" ]
[ "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_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_test_patch": true, "is_lite": false }
2021-05-08 23:51:13+00:00
mit
4,828
pydantic__pydantic-2794
diff --git a/pydantic/schema.py b/pydantic/schema.py --- a/pydantic/schema.py +++ b/pydantic/schema.py @@ -951,7 +951,7 @@ def get_annotation_with_constraints(annotation: Any, field_info: FieldInfo) -> T def go(type_: Any) -> Type[Any]: if ( - is_literal_type(annotation) + is_literal_type(type_) or isinstance(type_, ForwardRef) or lenient_issubclass(type_, (ConstrainedList, ConstrainedSet)) ):
pydantic/pydantic
b718e8e62680c2d7a42f1cf946094e1c0fe28c1d
diff --git a/tests/test_validators.py b/tests/test_validators.py --- a/tests/test_validators.py +++ b/tests/test_validators.py @@ -2,7 +2,7 @@ from datetime import datetime from enum import Enum from itertools import product -from typing import Dict, List, Optional, Tuple +from typing import Dict, List, Optional, Tuple, Union import pytest from typing_extensions import Literal @@ -1202,6 +1202,15 @@ class Model(BaseModel): ] +def test_union_literal_with_constraints(): + class Model(BaseModel, validate_assignment=True): + x: Union[Literal[42], Literal['pika']] = Field(allow_mutation=False) + + m = Model(x=42) + with pytest.raises(TypeError): + m.x += 1 + + def test_field_that_is_being_validated_is_excluded_from_validator_values(mocker): check_values = mocker.MagicMock()
passing `max_items` in `Field` with a `List[Literal["something"]` field raises `TypeError` ### 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.8.2 pydantic compiled: True install path: /home/ubuntu/.local/lib/python3.8/site-packages/pydantic python version: 3.8.5 (default, May 27 2021, 13:30:53) [GCC 9.3.0] platform: Linux-5.4.72-microsoft-standard-WSL2-x86_64-with-glibc2.29 optional deps. installed: ['typing-extensions'] ``` passing `max_items` raises an error only when the field type is `List[Literal["something"]`. expectation: passing `max_items` would not raise an error or would raise a more readable error ```py Python 3.8.5 (default, May 27 2021, 13:30:53) [GCC 9.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> from pydantic import BaseModel, Field >>> from typing import List, Literal >>> class MyModel(BaseModel): ... it: List[Literal["hi", "hello"]] = Field(max_items=2) ... Traceback (most recent call last): File "<stdin>", line 1, in <module> File "pydantic/main.py", line 299, in pydantic.main.ModelMetaclass.__new__ File "pydantic/fields.py", line 410, in pydantic.fields.ModelField.infer File "pydantic/schema.py", line 920, in pydantic.schema.get_annotation_from_field_info File "pydantic/schema.py", line 1015, in pydantic.schema.get_annotation_with_constraints File "pydantic/schema.py", line 967, in pydantic.schema.get_annotation_with_constraints.go File "pydantic/schema.py", line 965, in pydantic.schema.get_annotation_with_constraints.go File "/usr/lib/python3.8/typing.py", line 774, in __subclasscheck__ return issubclass(cls, self.__origin__) TypeError: issubclass() arg 1 must be a class >>> class MyModel(BaseModel): ... it: List[Literal["hi", "hello"]] = Field(description="here") ... >>> class MyModel(BaseModel): ... it: List[str] = Field(max_items=2) ... ``` Thanks for all help and the work you are doing with this library. We truly appreciate it.
0.0
b718e8e62680c2d7a42f1cf946094e1c0fe28c1d
[ "tests/test_validators.py::test_union_literal_with_constraints" ]
[ "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_field_that_is_being_validated_is_excluded_from_validator_values", "tests/test_validators.py::test_exceptions_in_field_validators_restore_original_field_value" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2021-05-14 11:53:10+00:00
mit
4,829
pydantic__pydantic-2806
diff --git a/pydantic/fields.py b/pydantic/fields.py --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -1,8 +1,9 @@ -from collections import defaultdict, deque +from collections import Counter as CollectionCounter, defaultdict, deque from collections.abc import Hashable as CollectionsHashable, Iterable as CollectionsIterable from typing import ( TYPE_CHECKING, Any, + Counter, DefaultDict, Deque, Dict, @@ -292,6 +293,7 @@ def Field( SHAPE_DEQUE = 11 SHAPE_DICT = 12 SHAPE_DEFAULTDICT = 13 +SHAPE_COUNTER = 14 SHAPE_NAME_LOOKUP = { SHAPE_LIST: 'List[{}]', SHAPE_SET: 'Set[{}]', @@ -302,9 +304,10 @@ def Field( SHAPE_DEQUE: 'Deque[{}]', SHAPE_DICT: 'Dict[{}]', SHAPE_DEFAULTDICT: 'DefaultDict[{}]', + SHAPE_COUNTER: 'Counter[{}]', } -MAPPING_LIKE_SHAPES: Set[int] = {SHAPE_DEFAULTDICT, SHAPE_DICT, SHAPE_MAPPING} +MAPPING_LIKE_SHAPES: Set[int] = {SHAPE_DEFAULTDICT, SHAPE_DICT, SHAPE_MAPPING, SHAPE_COUNTER} class ModelField(Representation): @@ -630,6 +633,10 @@ def _type_analysis(self) -> None: # noqa: C901 (ignore complexity) self.key_field = self._create_sub_type(get_args(self.type_)[0], 'key_' + self.name, for_keys=True) self.type_ = get_args(self.type_)[1] self.shape = SHAPE_DEFAULTDICT + elif issubclass(origin, Counter): + self.key_field = self._create_sub_type(get_args(self.type_)[0], 'key_' + self.name, for_keys=True) + self.type_ = int + self.shape = SHAPE_COUNTER elif issubclass(origin, Dict): self.key_field = self._create_sub_type(get_args(self.type_)[0], 'key_' + self.name, for_keys=True) self.type_ = get_args(self.type_)[1] @@ -900,6 +907,8 @@ def _validate_mapping_like( return result, None elif self.shape == SHAPE_DEFAULTDICT: return defaultdict(self.type_, result), None + elif self.shape == SHAPE_COUNTER: + return CollectionCounter(result), None else: return self._get_mapping_value(v, result), None
pydantic/pydantic
257908628f8bd29910744c632e847fde332d35a9
this is not a bug but a feature request.
diff --git a/tests/test_main.py b/tests/test_main.py --- a/tests/test_main.py +++ b/tests/test_main.py @@ -2,7 +2,7 @@ from collections import defaultdict from copy import deepcopy from enum import Enum -from typing import Any, Callable, ClassVar, DefaultDict, Dict, List, Mapping, Optional, Type, get_type_hints +from typing import Any, Callable, ClassVar, Counter, DefaultDict, Dict, List, Mapping, Optional, Type, get_type_hints from uuid import UUID, uuid4 import pytest @@ -1987,6 +1987,30 @@ class Model(BaseModel): assert repr(m) == "Model(x=defaultdict(<class 'str'>, {1: '', 'a': ''}))" +def test_typing_coercion_counter(): + class Model(BaseModel): + x: Counter[str] + + assert Model.__fields__['x'].type_ is int + assert repr(Model(x={'a': 10})) == "Model(x=Counter({'a': 10}))" + + +def test_typing_counter_value_validation(): + class Model(BaseModel): + x: Counter[str] + + with pytest.raises(ValidationError) as exc_info: + Model(x={'a': 'a'}) + + assert exc_info.value.errors() == [ + { + 'loc': ('x', 'a'), + 'msg': 'value is not a valid integer', + 'type': 'type_error.integer', + } + ] + + def test_class_kwargs_config(): class Base(BaseModel, extra='forbid', alias_generator=str.upper): a: int
typing.Counter is not supported ### 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.7 pydantic compiled: True install path: /home/user/app/.venv/lib/python3.8/site-packages/pydantic python version: 3.8.6 (default, Sep 25 2020, 09:36:53) [GCC 10.2.0] platform: Linux-5.9.0-1-amd64-x86_64-with-glibc2.29 optional deps. installed: ['typing-extensions'] ``` Minimal example: ```python from typing import Counter from pydantic import BaseModel class ProcessedDoc(BaseModel): named_entities: Counter[str] ``` Result: ```text Traceback (most recent call last): File "<stdin>", line 1, in <module> File "pydantic/main.py", line 262, in pydantic.main.ModelMetaclass.__new__ File "pydantic/fields.py", line 315, in pydantic.fields.ModelField.infer File "pydantic/fields.py", line 284, in pydantic.fields.ModelField.__init__ File "pydantic/fields.py", line 356, in pydantic.fields.ModelField.prepare File "pydantic/fields.py", line 492, in pydantic.fields.ModelField._type_analysis IndexError: tuple index out of range ```
0.0
257908628f8bd29910744c632e847fde332d35a9
[ "tests/test_main.py::test_typing_coercion_counter", "tests/test_main.py::test_typing_counter_value_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_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_hunks" ], "has_test_patch": true, "is_lite": false }
2021-05-17 12:19:49+00:00
mit
4,830
pydantic__pydantic-2811
diff --git a/pydantic/schema.py b/pydantic/schema.py --- a/pydantic/schema.py +++ b/pydantic/schema.py @@ -31,6 +31,7 @@ from .fields import ( MAPPING_LIKE_SHAPES, + SHAPE_DEQUE, SHAPE_FROZENSET, SHAPE_GENERIC, SHAPE_ITERABLE, @@ -437,7 +438,15 @@ def field_type_schema( definitions = {} nested_models: Set[str] = set() f_schema: Dict[str, Any] - if field.shape in {SHAPE_LIST, SHAPE_TUPLE_ELLIPSIS, SHAPE_SEQUENCE, SHAPE_SET, SHAPE_FROZENSET, SHAPE_ITERABLE}: + if field.shape in { + SHAPE_LIST, + SHAPE_TUPLE_ELLIPSIS, + SHAPE_SEQUENCE, + SHAPE_SET, + SHAPE_FROZENSET, + SHAPE_ITERABLE, + SHAPE_DEQUE, + }: items_schema, f_definitions, f_nested_models = field_singleton_schema( field, by_alias=by_alias,
pydantic/pydantic
5ccbdcb5904f35834300b01432a665c75dc02296
diff --git a/tests/test_schema.py b/tests/test_schema.py --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -10,6 +10,7 @@ from typing import ( Any, Callable, + Deque, Dict, FrozenSet, Generic, @@ -556,6 +557,18 @@ class Model(BaseModel): assert Model.schema() == base_schema +def test_deque(): + class Model(BaseModel): + a: Deque[str] + + assert Model.schema() == { + 'title': 'Model', + 'type': 'object', + 'properties': {'a': {'title': 'A', 'type': 'array', 'items': {'type': 'string'}}}, + 'required': ['a'], + } + + def test_bool(): class Model(BaseModel): a: bool
Cannot generate a JSON schema for a models with `Deque` 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.8.2 pydantic compiled: False install path: /home/sergej/Projects/pydantic/pydantic python version: 3.8.5 (default, Jan 27 2021, 15:41:15) [GCC 9.3.0] platform: Linux-5.4.0-72-generic-x86_64-with-glibc2.29 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: --> ### Description The `AssertionError` occurs on JSON schema generation if `Deque` field used in the Pydantic model. ### Example ```python from typing import Deque from pydantic import BaseModel class Model(BaseModel): a: Deque[str] Model.schema() ``` ### Output ```python Traceback (most recent call last): File "/home/sergej/Projects/pydantic/test_deque.py", line 10, in <module> Model.schema() File "/home/sergej/Projects/pydantic/pydantic/main.py", line 720, in schema s = model_schema(cls, by_alias=by_alias, ref_template=ref_template) File "/home/sergej/Projects/pydantic/pydantic/schema.py", line 168, in model_schema m_schema, m_definitions, nested_models = model_process_schema( File "/home/sergej/Projects/pydantic/pydantic/schema.py", line 557, in model_process_schema m_schema, m_definitions, nested_models = model_type_schema( File "/home/sergej/Projects/pydantic/pydantic/schema.py", line 598, in model_type_schema f_schema, f_definitions, f_nested_models = field_schema( File "/home/sergej/Projects/pydantic/pydantic/schema.py", line 242, in field_schema f_schema, f_definitions, f_nested_models = field_type_schema( File "/home/sergej/Projects/pydantic/pydantic/schema.py", line 503, in field_type_schema assert field.shape in {SHAPE_SINGLETON, SHAPE_GENERIC}, field.shape AssertionError: 11 ```
0.0
5ccbdcb5904f35834300b01432a665c75dc02296
[ "tests/test_schema.py::test_deque" ]
[ "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_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_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-05-18 19:11:32+00:00
mit
4,831
pydantic__pydantic-3138
diff --git a/pydantic/fields.py b/pydantic/fields.py --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -554,13 +554,13 @@ def _type_analysis(self) -> None: # noqa: C901 (ignore complexity) if isinstance(self.type_, type) and isinstance(None, self.type_): self.allow_none = True return - if origin is Annotated: + elif origin is Annotated: self.type_ = get_args(self.type_)[0] self._type_analysis() return - if origin is Callable: + elif origin is Callable: return - if is_union(origin): + elif is_union(origin): types_ = [] for type_ in get_args(self.type_): if type_ is NoneType: @@ -580,8 +580,7 @@ def _type_analysis(self) -> None: # noqa: C901 (ignore complexity) else: self.sub_fields = [self._create_sub_type(t, f'{self.name}_{display_as_type(t)}') for t in types_] return - - if issubclass(origin, Tuple): # type: ignore + elif issubclass(origin, Tuple): # type: ignore # origin == Tuple without item type args = get_args(self.type_) if not args: # plain tuple @@ -599,8 +598,7 @@ def _type_analysis(self) -> None: # noqa: C901 (ignore complexity) self.shape = SHAPE_TUPLE self.sub_fields = [self._create_sub_type(t, f'{self.name}_{i}') for i, t in enumerate(args)] return - - if issubclass(origin, List): + elif issubclass(origin, List): # Create self validators get_validators = getattr(self.type_, '__get_validators__', None) if get_validators: @@ -636,6 +634,11 @@ def _type_analysis(self) -> None: # noqa: C901 (ignore complexity) elif issubclass(origin, Sequence): self.type_ = get_args(self.type_)[0] self.shape = SHAPE_SEQUENCE + # priority to most common mapping: dict + elif origin is dict or origin is Dict: + self.key_field = self._create_sub_type(get_args(self.type_)[0], 'key_' + self.name, for_keys=True) + self.type_ = get_args(self.type_)[1] + self.shape = SHAPE_DICT elif issubclass(origin, DefaultDict): self.key_field = self._create_sub_type(get_args(self.type_)[0], 'key_' + self.name, for_keys=True) self.type_ = get_args(self.type_)[1] @@ -644,10 +647,6 @@ def _type_analysis(self) -> None: # noqa: C901 (ignore complexity) self.key_field = self._create_sub_type(get_args(self.type_)[0], 'key_' + self.name, for_keys=True) self.type_ = int self.shape = SHAPE_COUNTER - elif issubclass(origin, Dict): - self.key_field = self._create_sub_type(get_args(self.type_)[0], 'key_' + self.name, for_keys=True) - self.type_ = get_args(self.type_)[1] - self.shape = SHAPE_DICT elif issubclass(origin, Mapping): self.key_field = self._create_sub_type(get_args(self.type_)[0], 'key_' + self.name, for_keys=True) self.type_ = get_args(self.type_)[1]
pydantic/pydantic
7421579480148cdfbd7752b17b49a3dbbc7557bc
diff --git a/tests/test_main.py b/tests/test_main.py --- a/tests/test_main.py +++ b/tests/test_main.py @@ -2,7 +2,20 @@ from collections import defaultdict from copy import deepcopy from enum import Enum -from typing import Any, Callable, ClassVar, Counter, DefaultDict, Dict, List, Mapping, Optional, Type, get_type_hints +from typing import ( + Any, + Callable, + ClassVar, + Counter, + DefaultDict, + Dict, + List, + Mapping, + Optional, + Type, + TypeVar, + get_type_hints, +) from uuid import UUID, uuid4 import pytest @@ -1976,6 +1989,27 @@ class Model(BaseModel): assert repr(m) == "Model(x={'one': 1, 'two': 2})" [email protected](sys.version_info < (3, 7), reason='generic classes need 3.7') +def test_typing_non_coercion_of_dict_subclasses(): + KT = TypeVar('KT') + VT = TypeVar('VT') + + class MyDict(Dict[KT, VT]): + def __repr__(self): + return f'MyDict({super().__repr__()})' + + class Model(BaseModel): + a: MyDict + b: MyDict[str, int] + c: Dict[str, int] + d: Mapping[str, int] + + assert ( + repr(Model(a=MyDict({'a': 1}), b=MyDict({'a': '1'}), c=MyDict({'a': '1'}), d=MyDict({'a': '1'}))) + == "Model(a=MyDict({'a': 1}), b=MyDict({'a': 1}), c={'a': 1}, d=MyDict({'a': 1}))" + ) + + def test_typing_coercion_defaultdict(): class Model(BaseModel): x: DefaultDict[int, str]
AttributeError: name with frozendict[..., ...] and subclass (maybe Mapping+GenericAlias issue?) # Bug Using a [`frozendict`](https://github.com/Marco-Sulla/python-frozendict) as a model field works normally/correctly but when subscripted (eg: `frozendict[str, int]`), pydantic errors in some weird ways: - the output has a `dict` (similar to #2311 and others, except even converting to `frozendict` explicitly or in a `@validator` doesn't work) - on model subclasses, the `field.outer_type_` seems to be botched and missing attributes (but works fine on the original defining class) ```py # pip3 install frozendict from frozendict import frozendict from pydantic import BaseModel class Base(BaseModel): a: frozendict b: frozendict[str, int] class Sub(Base): pass def inspect(m: BaseModel): print(f"\t{m.__name__}\n") print(m(a=frozendict(a=1), b=frozendict(b=1))) print(m.__fields__) print(m.__fields__["b"].outer_type_) # This doesn't error, but the sub-typed variant is replaced with a dict and the Field is a Mapping inspect(Base) # This errors when inspecting `b` ModelField.outer_type_, seemingly trying to access an uninitialized .name inspect(Sub) ``` outputs ``` Base a=frozendict({'a': 1}) b={'b': 1} {'a': ModelField(name='a', type=frozendict, required=True), 'b': ModelField(name='b', type=Mapping[str, int], required=True)} frozendict.core.frozendict[str, int] Sub a=frozendict({'a': 1}) b={'b': 1} {'a': ModelField(name='a', type=frozendict, required=True), 'b': ModelField(name='b', type=Mapping[str, int], required=True)} Traceback (most recent call last): File "/tmp/pydantic_error.py", line 25, in <module> inspect(Sub) File "/tmp/pydantic_error.py", line 19, in inspect print(m.__fields__["b"].outer_type_) File "pydantic/utils.py", line 396, in pydantic.utils.Representation.__repr__ File "pydantic/utils.py", line 375, in genexpr File "pydantic/utils.py", line 375, in genexpr File "pydantic/fields.py", line 951, in pydantic.fields.ModelField.__repr_args__ AttributeError: name ``` The `type(frozendict[str, int])` is a `GenericAlias` and otherwise seems to be normal: ``` >>> type(frozendict[str, str]) <class 'types.GenericAlias'> >>> get_origin(frozendict[str, str]) <class 'frozendict.core.frozendict'> >>> get_args(frozendict[str, str]) (<class 'str'>, <class 'str'>) >>> >>> >>> type(dict[str, str]) <class 'types.GenericAlias'> >>> get_origin(dict[str, str]) <class 'dict'> >>> get_args(dict[str, str]) (<class 'str'>, <class 'str'>) ``` ### 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 Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.8.2 pydantic compiled: True install path: /Users/jacobhayes/src/github.com/replicahq/artigraph/.wt/type-dispatch/.direnv/python-3.9.6/lib/python3.9/site-packages/pydantic python version: 3.9.6 (default, Jul 20 2021, 13:51:27) [Clang 12.0.5 (clang-1205.0.22.9)] platform: macOS-11.4-x86_64-i386-64bit optional deps. installed: ['typing-extensions'] ```
0.0
7421579480148cdfbd7752b17b49a3dbbc7557bc
[ "tests/test_main.py::test_typing_non_coercion_of_dict_subclasses" ]
[ "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_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-08-26 08:17:33+00:00
mit
4,832
pydantic__pydantic-3176
diff --git a/pydantic/decorator.py b/pydantic/decorator.py --- a/pydantic/decorator.py +++ b/pydantic/decorator.py @@ -220,15 +220,15 @@ class CustomConfig: class DecoratorBaseModel(BaseModel): @validator(self.v_args_name, check_fields=False, allow_reuse=True) - def check_args(cls, v: List[Any]) -> List[Any]: - if takes_args: + def check_args(cls, v: Optional[List[Any]]) -> Optional[List[Any]]: + if takes_args or v is None: return v raise TypeError(f'{pos_args} positional arguments expected but {pos_args + len(v)} given') @validator(self.v_kwargs_name, check_fields=False, allow_reuse=True) - def check_kwargs(cls, v: Dict[str, Any]) -> Dict[str, Any]: - if takes_kwargs: + def check_kwargs(cls, v: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: + if takes_kwargs or v is None: return v plural = '' if len(v) == 1 else 's' @@ -236,13 +236,19 @@ def check_kwargs(cls, v: Dict[str, Any]) -> Dict[str, Any]: raise TypeError(f'unexpected keyword argument{plural}: {keys}') @validator(V_POSITIONAL_ONLY_NAME, check_fields=False, allow_reuse=True) - def check_positional_only(cls, v: List[str]) -> None: + def check_positional_only(cls, v: Optional[List[str]]) -> None: + if v is None: + return + plural = '' if len(v) == 1 else 's' keys = ', '.join(map(repr, v)) raise TypeError(f'positional-only argument{plural} passed as keyword argument{plural}: {keys}') @validator(V_DUPLICATE_KWARGS, check_fields=False, allow_reuse=True) - def check_duplicate_kwargs(cls, v: List[str]) -> None: + def check_duplicate_kwargs(cls, v: Optional[List[str]]) -> None: + if v is None: + return + plural = '' if len(v) == 1 else 's' keys = ', '.join(map(repr, v)) raise TypeError(f'multiple values for argument{plural}: {keys}')
pydantic/pydantic
63e42db921b2be17b695a9aa3b19f71798774f42
diff --git a/tests/test_decorator.py b/tests/test_decorator.py --- a/tests/test_decorator.py +++ b/tests/test_decorator.py @@ -1,6 +1,7 @@ import asyncio import inspect import sys +from datetime import datetime, timezone from pathlib import Path from typing import List @@ -399,3 +400,30 @@ def func(s: str, count: int, *, separator: bytes = b''): func.validate(['qwe'], 2) stub.assert_not_called() + + +def test_validate_all(): + @validate_arguments(config=dict(validate_all=True)) + def foo(dt: datetime = Field(default_factory=lambda: 946684800)): + return dt + + assert foo() == datetime(2000, 1, 1, tzinfo=timezone.utc) + assert foo(0) == datetime(1970, 1, 1, tzinfo=timezone.utc) + + +@skip_pre_38 +def test_validate_all_positional(create_module): + module = create_module( + # language=Python + """ +from datetime import datetime + +from pydantic import Field, validate_arguments + +@validate_arguments(config=dict(validate_all=True)) +def foo(dt: datetime = Field(default_factory=lambda: 946684800), /): + return dt +""" + ) + assert module.foo() == datetime(2000, 1, 1, tzinfo=timezone.utc) + assert module.foo(0) == datetime(1970, 1, 1, tzinfo=timezone.utc)
underscore_attrs_are_private and validate_all not compatible with validate_arguments Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.8.2 pydantic compiled: True install path: /home/xxx/.conda/envs/py38/lib/python3.8/site-packages/pydantic python version: 3.8.5 (default, Sep 4 2020, 07:30:14) [GCC 7.3.0] platform: Linux-4.18.0-80.el8.x86_64-x86_64-with-glibc2.10 optional deps. installed: ['typing-extensions'] ``` `underscore_attrs_are_private` not work with `validate_arguments` just like it not work with `create_model` #3134 . When I define a function decorated by `validate_arguments` with `validate_all` been set `True`, It will raise `ValidationError`: ```py from datetime import datetime from pydantic import validate_arguments, Field @validate_arguments(config={'validate_all': True}) def foo(dt: datetime = Field(default_factory=lambda : 42)): print(type(dt)) foo() ``` ``` --------------------------------------------------------------------------- ValidationError Traceback (most recent call last) <ipython-input-4-6c97ede6fd47> in <module> 7 print(type(dt)) 8 ----> 9 foo() ~/.conda/envs/py38/lib/python3.8/site-packages/pydantic/decorator.cpython-38-x86_64-linux-gnu.so in pydantic.decorator.validate_arguments.validate.wrapper_function() ~/.conda/envs/py38/lib/python3.8/site-packages/pydantic/decorator.cpython-38-x86_64-linux-gnu.so in pydantic.decorator.ValidatedFunction.call() ~/.conda/envs/py38/lib/python3.8/site-packages/pydantic/decorator.cpython-38-x86_64-linux-gnu.so in pydantic.decorator.ValidatedFunction.init_model_instance() ~/.conda/envs/py38/lib/python3.8/site-packages/pydantic/main.cpython-38-x86_64-linux-gnu.so in pydantic.main.BaseModel.__init__() ValidationError: 3 validation errors for Foo v__duplicate_kwargs object of type 'NoneType' has no len() (type=type_error) args object of type 'NoneType' has no len() (type=type_error) kwargs object of type 'NoneType' has no len() (type=type_error) ```
0.0
63e42db921b2be17b695a9aa3b19f71798774f42
[ "tests/test_decorator.py::test_validate_all", "tests/test_decorator.py::test_validate_all_positional" ]
[ "tests/test_decorator.py::test_args", "tests/test_decorator.py::test_wrap", "tests/test_decorator.py::test_kwargs", "tests/test_decorator.py::test_untyped", "tests/test_decorator.py::test_var_args_kwargs[True]", "tests/test_decorator.py::test_var_args_kwargs[False]", "tests/test_decorator.py::test_field_can_provide_factory", "tests/test_decorator.py::test_annotated_field_can_provide_factory", "tests/test_decorator.py::test_positional_only", "tests/test_decorator.py::test_args_name", "tests/test_decorator.py::test_v_args", "tests/test_decorator.py::test_async", "tests/test_decorator.py::test_string_annotation", "tests/test_decorator.py::test_item_method", "tests/test_decorator.py::test_class_method", "tests/test_decorator.py::test_config_title", "tests/test_decorator.py::test_config_title_cls", "tests/test_decorator.py::test_config_fields", "tests/test_decorator.py::test_config_arbitrary_types_allowed", "tests/test_decorator.py::test_validate" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2021-09-05 22:08:17+00:00
mit
4,833
pydantic__pydantic-3177
diff --git a/pydantic/decorator.py b/pydantic/decorator.py --- a/pydantic/decorator.py +++ b/pydantic/decorator.py @@ -254,6 +254,6 @@ def check_duplicate_kwargs(cls, v: Optional[List[str]]) -> None: raise TypeError(f'multiple values for argument{plural}: {keys}') class Config(CustomConfig): - extra = Extra.forbid + extra = getattr(CustomConfig, 'extra', Extra.forbid) self.model = create_model(to_camel(self.raw_function.__name__), __base__=DecoratorBaseModel, **fields)
pydantic/pydantic
c4e793b76741625e0c717560f79fc101f0054aa8
diff --git a/tests/test_decorator.py b/tests/test_decorator.py --- a/tests/test_decorator.py +++ b/tests/test_decorator.py @@ -6,9 +6,9 @@ from typing import List import pytest -from typing_extensions import Annotated +from typing_extensions import Annotated, TypedDict -from pydantic import BaseModel, Field, ValidationError, validate_arguments +from pydantic import BaseModel, Extra, Field, ValidationError, validate_arguments from pydantic.decorator import ValidatedFunction from pydantic.errors import ConfigError @@ -427,3 +427,20 @@ def foo(dt: datetime = Field(default_factory=lambda: 946684800), /): ) assert module.foo() == datetime(2000, 1, 1, tzinfo=timezone.utc) assert module.foo(0) == datetime(1970, 1, 1, tzinfo=timezone.utc) + + +def test_validate_extra(): + class TypedTest(TypedDict): + y: str + + @validate_arguments(config={'extra': Extra.allow}) + def test(other: TypedTest): + return other + + assert test(other={'y': 'b', 'z': 'a'}) == {'y': 'b', 'z': 'a'} + + @validate_arguments(config={'extra': Extra.ignore}) + def test(other: TypedTest): + return other + + assert test(other={'y': 'b', 'z': 'a'}) == {'y': 'b'}
"extra" config not respected for TypedDicts in functions ### 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/msharma216/.local/lib/python3.8/site-packages/pydantic python version: 3.8.0 (default, Feb 25 2021, 22:10:10) [GCC 8.4.0] platform: Linux-4.4.0-19041-Microsoft-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: --> When trying to use the `validate_arguments` decorator, I face the issue of getting validation errors for an extra attribute for a TypedDict as below: ```py from typing_extensions import TypedDict from pydantic import validate_arguments, Extra class TypedTest(TypedDict): y: str @validate_arguments(config={'extra': Extra.allow}) def test(other: TypedTest): pass test(other={'y': 'b', 'z': 'a'}) ``` Output: ``` pydantic.error_wrappers.ValidationError: 1 validation error for Test other -> z extra fields not permitted (type=value_error.extra) ``` Expected: No errors Anything I have missed that would let this validation pass for extra attributes in the TypedDict? Thanks very much!
0.0
c4e793b76741625e0c717560f79fc101f0054aa8
[ "tests/test_decorator.py::test_validate_extra" ]
[ "tests/test_decorator.py::test_args", "tests/test_decorator.py::test_wrap", "tests/test_decorator.py::test_kwargs", "tests/test_decorator.py::test_untyped", "tests/test_decorator.py::test_var_args_kwargs[True]", "tests/test_decorator.py::test_var_args_kwargs[False]", "tests/test_decorator.py::test_field_can_provide_factory", "tests/test_decorator.py::test_annotated_field_can_provide_factory", "tests/test_decorator.py::test_positional_only", "tests/test_decorator.py::test_args_name", "tests/test_decorator.py::test_v_args", "tests/test_decorator.py::test_async", "tests/test_decorator.py::test_string_annotation", "tests/test_decorator.py::test_item_method", "tests/test_decorator.py::test_class_method", "tests/test_decorator.py::test_config_title", "tests/test_decorator.py::test_config_title_cls", "tests/test_decorator.py::test_config_fields", "tests/test_decorator.py::test_config_arbitrary_types_allowed", "tests/test_decorator.py::test_validate", "tests/test_decorator.py::test_validate_all", "tests/test_decorator.py::test_validate_all_positional" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2021-09-05 22:34:35+00:00
mit
4,834