From f0059dd4db8d3f78e47386630a00868c80bada80 Mon Sep 17 00:00:00 2001 From: Viicos <65306057+Viicos@users.noreply.github.com> Date: Tue, 28 Nov 2023 18:51:04 +0100 Subject: [PATCH] Explicitly raise an error if field names clashes with types --- pydantic/fields.py | 8 ++++++++ tests/test_fields.py | 14 ++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/pydantic/fields.py b/pydantic/fields.py index 849215b3a1..e93a9aa270 100644 --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -321,6 +321,14 @@ class MyModel(pydantic.BaseModel): Returns: A field object with the passed values. """ + + if annotation is default: + raise RuntimeError( + 'Error when building FieldInfo from annotated attribute. ' + "Make sure you don't have any field name clashing with a type annotation " + '(e.g. `date: date = Field(None)`).' + ) + final = False if _typing_extra.is_finalvar(annotation): final = True diff --git a/tests/test_fields.py b/tests/test_fields.py index 0220dce853..6f84388ee5 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -17,6 +17,20 @@ def test_field_info_annotation_keyword_argument(): assert e.value.args == ('"annotation" is not permitted as a Field keyword argument',) +def test_field_info_annotated_attribute_name_clashing(): + """This tests that `FieldInfo.from_annotated_attribute` will raise a `RuntimeError` if attribute names clashes + with a type. + """ + + with pytest.raises(RuntimeError): + + class SubModel(BaseModel): + a: int = 1 + + class Model(BaseModel): + SubModel: SubModel = Field() + + def test_init_var_field(): @pydantic.dataclasses.dataclass class Foo: