Skip to content

Commit

Permalink
Fix :: avoid mutating Field default value
Browse files Browse the repository at this point in the history
  • Loading branch information
PrettyWood committed Apr 22, 2020
1 parent 1f071f1 commit b0f0821
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 2 deletions.
1 change: 1 addition & 0 deletions changes/1412-prettywood.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Avoid mutating `Field` default value
4 changes: 2 additions & 2 deletions pydantic/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,7 @@ def infer(
required: 'BoolUndefined' = Undefined
if value is Required:
required = True
field_info.default = None
value = None
elif value is not Undefined:
required = False
field_info.alias = field_info.alias or field_info_from_config.get('alias')
Expand All @@ -312,7 +312,7 @@ def infer(
type_=annotation,
alias=field_info.alias,
class_validators=class_validators,
default=field_info.default,
default=value,
default_factory=field_info.default_factory,
required=required,
model_config=config,
Expand Down
15 changes: 15 additions & 0 deletions tests/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -1095,3 +1095,18 @@ class Foo(BaseModel):
assert f.foo is None
assert f.bar is None
assert f.baz is None


def test_reuse_same_field():
required_field = Field(...)

class Model1(BaseModel):
required: str = required_field

class Model2(BaseModel):
required: str = required_field

with pytest.raises(ValidationError):
Model1.parse_obj({})
with pytest.raises(ValidationError):
Model2.parse_obj({})

0 comments on commit b0f0821

Please sign in to comment.