Repository: pydantic/pydantic

Issue:
Non-primitive type (object) defaults are shared between instances
  Hi,

If you use any non-primitive type as a default and create a model so that the default is used (i.e. not specifying the field in the serialized data) then you will end up having the same instance across all the instances (that were initized with the default). Now, in hindshight it's not surprising, because this is what happens when you have such a default for a function parameter, but the documentation is misleading as it contains an example suggesting you could do this:
```
class User(BaseModel):
    id: int
    name = 'John Doe'
    signup_ts: datetime = None
    friends: List[int] = []
```

While if now you create two users:
```
u1, u2 = [User(id=i) for i in range(2)]
```

You'll have `u1.friends is u2.friends`. This one is easy to step aside by always providing a friends list, but in my case I wanted to use a defaultdict, which, it seems can be fixed with validators (using always=True, and also copying the values from the dict created by pydantic) but it would be nice to be able to use factory functions for a more declarative style. E.g. if you know FactoryBoy, something like that. (Though, probably one should still have a converting validator if there is actually data for that field.)

But at least the documentation should be fixed.


Discussion:
I guess the correct solution is to duplicate the default for each instance such that `u1.friends is not u2.frineds`.

I'll work on a PR when I have the time.

Resolving patch:
diff --git a/pydantic/main.py b/pydantic/main.py
--- a/pydantic/main.py
+++ b/pydantic/main.py
@@ -137,6 +137,9 @@ def __new__(mcs, name, bases, namespace):
         return super().__new__(mcs, name, bases, new_namespace)
 
 
+_missing = object()
+
+
 class BaseModel(metaclass=MetaModel):
     # populated by the metaclass, defined here to help IDEs only
     __fields__ = {}
@@ -261,18 +264,18 @@ def _process_values(self, input_data: dict) -> Dict[str, Any]:  # noqa: C901 (ig
         errors = []
 
         for name, field in self.__fields__.items():
-            value = input_data.get(field.alias, ...)
-            if value is ... and self.__config__.allow_population_by_alias and field.alt_alias:
-                value = input_data.get(field.name, ...)
+            value = input_data.get(field.alias, _missing)
+            if value is _missing and self.__config__.allow_population_by_alias and field.alt_alias:
+                value = input_data.get(field.name, _missing)
 
-            if value is ...:
+            if value is _missing:
                 if self.__config__.validate_all or field.validate_always:
-                    value = field.default
+                    value = deepcopy(field.default)
                 else:
                     if field.required:
                         errors.append(ErrorWrapper(MissingError(), loc=field.alias, config=self.__config__))
                     else:
-                        values[name] = field.default
+                        values[name] = deepcopy(field.default)
                     continue
 
             v_, errors_ = field.validate(value, values, loc=field.alias, cls=self.__class__)


Test patch:
diff --git a/tests/test_main.py b/tests/test_main.py
--- a/tests/test_main.py
+++ b/tests/test_main.py
@@ -1,5 +1,5 @@
 from enum import Enum
-from typing import Any
+from typing import Any, List
 
 import pytest
 
@@ -452,3 +452,12 @@ class Model(BaseModel):
     assert m.foo == {'a', 'b'}
     assert m.bar == ('c', 'd')
     assert m.dict() == {'foo': {'a', 'b'}, 'bar': ('c', 'd')}
+
+
+def test_default_copy():
+    class User(BaseModel):
+        friends: List[int] = []
+
+    u1 = User()
+    u2 = User()
+    assert u1.friends is not u2.friends