Skip to content

Commit

Permalink
Explicitly raise an error if field names clashes with types
Browse files Browse the repository at this point in the history
  • Loading branch information
Viicos committed Nov 28, 2023
1 parent 2e459bb commit f0059dd
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
8 changes: 8 additions & 0 deletions pydantic/fields.py
Expand Up @@ -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
Expand Down
14 changes: 14 additions & 0 deletions tests/test_fields.py
Expand Up @@ -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:
Expand Down

0 comments on commit f0059dd

Please sign in to comment.