diff --git a/pydantic/fields.py b/pydantic/fields.py index 461fe0d..e8ed386 100644 --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -63,6 +63,9 @@ class Field: if self.type_ is None: raise ConfigError(f'unable to infer type for attribute "{self.name}"') + if not self.required and not self.validate_always and self.default is None: + self.allow_none = True + # typing interface is horrible, we have to do some ugly checks origin = getattr(self.type_, '__origin__', None) if origin not in (None, Union): diff --git a/tests/test_main.py b/tests/test_main.py index de95d28..1e1a199 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -223,3 +223,11 @@ def test_unable_to_infer(): class InvalidDefinitionModel(BaseModel): x = None assert exc_info.value.args[0] == 'unable to infer type for attribute "x"' + + +def test_not_required(): + class Model(BaseModel): + a: float = None + assert Model(a=12.2).a == 12.2 + assert Model().a is None + assert Model(a=None).a is None