Repository: pydantic/pydantic

Issue:
Dynamic defaults set using default_factory show up in exported JSON schema
# Question

Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`:
```
             pydantic version: 1.5.1
            pydantic compiled: False
                 install path: [home]/repos/fastapi-test/.venv/lib/python3.8/site-packages/pydantic
               python version: 3.8.2 (default, Apr  8 2020, 14:31:25)  [GCC 9.3.0]
         
```
Hello!
I'm currently developing an API using FastAPI, and, by extension, Pydantic.
There are a few fields which require dynamic default values, e.g. `created_date`, and per https://github.com/samuelcolvin/pydantic/issues/866 I've been using `default_factory` to do so. However, when a field has a default value defined using a factory, the dynamic value shows up in the generated JSON schema, which might not be desirable?

Example:
```py
from datetime import datetime, timezone
from uuid import uuid4
from pydantic import BaseModel, Field


class SchemaTest(BaseModel):
    uuid = Field(default_factory=uuid4)
    created_date: datetime = Field(
        default_factory=lambda: datetime.now(timezone.utc)
    )
print(SchemaTest.schema_json(indent=2))
```
The above outputs

```json
{
  "title": "SchemaTest",
  "type": "object",
  "properties": {
    "created_date": {
      "title": "Created Date",
      "default": "2020-05-15T10:04:18.692173+00:00",
      "type": "string",
      "format": "date-time"
    },
    "uuid": {
      "title": "Uuid",
      "default": "79a35356-4619-49da-9bbe-4be75a696485",
      "type": "string",
      "format": "uuid"
    }
  }
}

```
These values are of course different each time the schema is generated.
I understand why it happens, but I'm not sure it's entirely correct to expose the value in the JSON schema like this. It's worth noting that this is not a problem when using the "old" method of setting defaults via a validator. 

Please let me know if I'm missing something, or that this is indeed appropriate behavior. Thanks for developing such a great tool!


Discussion:

Resolving patch:
diff --git a/pydantic/fields.py b/pydantic/fields.py
--- a/pydantic/fields.py
+++ b/pydantic/fields.py
@@ -296,7 +296,7 @@ def infer(
 
         if isinstance(value, FieldInfo):
             field_info = value
-            value = field_info.default_factory() if field_info.default_factory is not None else field_info.default
+            value = None if field_info.default_factory is not None else field_info.default
         else:
             field_info = FieldInfo(value, **field_info_from_config)
         required: 'BoolUndefined' = Undefined
@@ -341,7 +341,19 @@ 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.
         """
+
+        # 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 None:
+                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
+
         default_value = self.get_default()
+
         if default_value is not None and self.type_ is None:
             self.type_ = default_value.__class__
             self.outer_type_ = self.type_


Test patch:
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
@@ -1531,3 +1531,23 @@ class Model(BaseModel):
 
     Model(v=None)
     Model()
+
+
+def test_default_factory_side_effect():
+    """It may call `default_factory` more than once when `validate_all` is set"""
+
+    v = 0
+
+    def factory():
+        nonlocal v
+        v += 1
+        return v
+
+    class MyModel(BaseModel):
+        id: int = Field(default_factory=factory)
+
+        class Config:
+            validate_all = True
+
+    m1 = MyModel()
+    assert m1.id == 2  # instead of 1
diff --git a/tests/test_main.py b/tests/test_main.py
--- a/tests/test_main.py
+++ b/tests/test_main.py
@@ -5,7 +5,7 @@
 
 import pytest
 
-from pydantic import BaseModel, Extra, Field, NoneBytes, NoneStr, Required, ValidationError, constr
+from pydantic import BaseModel, ConfigError, Extra, Field, NoneBytes, NoneStr, Required, ValidationError, constr
 
 
 def test_success():
@@ -52,26 +52,32 @@ def test_ultra_simple_repr():
         assert m.to_string() == 'a=10.2 b=10'
 
 
-def test_default_dict_repr():
+def test_default_factory_field():
     def myfunc():
         return 1
 
     class Model(BaseModel):
         a: int = Field(default_factory=myfunc)
-        b = Field(default_factory=myfunc)
 
     m = Model()
-    assert str(m) == 'a=1 b=1'
-    assert repr(m) == 'Model(a=1, b=1)'
+    assert str(m) == 'a=1'
     assert (
         repr(m.__fields__['a']) == "ModelField(name='a', type=int, required=False, default_factory='<function myfunc>')"
     )
-    assert (
-        repr(m.__fields__['b']) == "ModelField(name='b', type=int, required=False, default_factory='<function myfunc>')"
-    )
-    assert dict(m) == {'a': 1, 'b': 1}
-    assert m.dict() == {'a': 1, 'b': 1}
-    assert m.json() == '{"a": 1, "b": 1}'
+    assert dict(m) == {'a': 1}
+    assert m.json() == '{"a": 1}'
+
+
+def test_default_factory_no_type_field():
+    def myfunc():
+        return 1
+
+    with pytest.raises(ConfigError) as e:
+
+        class Model(BaseModel):
+            a = Field(default_factory=myfunc)
+
+    assert str(e.value) == "you need to set the type of field 'a' when using `default_factory`"
 
 
 def test_comparing():
@@ -1088,6 +1094,46 @@ class FunctionModel(BaseModel):
     assert m.uid is uuid4
 
 
+def test_default_factory_called_once():
+    """It should call only once the given factory by default"""
+
+    class Seq:
+        def __init__(self):
+            self.v = 0
+
+        def __call__(self):
+            self.v += 1
+            return self.v
+
+    class MyModel(BaseModel):
+        id: int = Field(default_factory=Seq())
+
+    m1 = MyModel()
+    assert m1.id == 1
+    m2 = MyModel()
+    assert m2.id == 2
+    assert m1.id == 1
+
+
+def test_default_factory_called_once_2():
+    """It should call only once the given factory by default"""
+
+    v = 0
+
+    def factory():
+        nonlocal v
+        v += 1
+        return v
+
+    class MyModel(BaseModel):
+        id: int = Field(default_factory=factory)
+
+    m1 = MyModel()
+    assert m1.id == 1
+    m2 = MyModel()
+    assert m2.id == 2
+
+
 @pytest.mark.skipif(sys.version_info < (3, 7), reason='field constraints are set but not enforced with python 3.6')
 def test_none_min_max_items():
     # None default