internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: pydantic/pydantic

Issue:
__str__ and __repr__ are squashed on child classes
After #884, a child class of a model does not inherit its parent's `__str__` and `__repr__` overloads.

```py
import pydantic

class Foo(pydantic.BaseModel):
    x: int = 3
    y: float = 4.2

    def __str__(self):
        return str(self.y + self.x)


f = Foo()
# Expected: 7.2
# Observed: 7.2
print(str(f))


class Bar(Foo):
    z: bool = False


b = Bar()

# Expected: 7.2
# Observed: x=3 y=4.2 z=False
print(str(b))
```

* OS: **Ubuntu 19.10**
* Python version `import sys; print(sys.version)`: **3.7.5** (default, Nov 20 2019, 09:21:52) [GCC 9.2.1 20191008]
* Pydantic version `import pydantic; print(pydantic.VERSION)`: **1.1.1**


Discussion:

Resolving patch:
diff --git a/pydantic/main.py b/pydantic/main.py
--- a/pydantic/main.py
+++ b/pydantic/main.py
@@ -238,12 +238,6 @@ def __new__(mcs, name, bases, namespace, **kwargs):  # noqa C901
             '__schema_cache__': {},
             '__json_encoder__': staticmethod(json_encoder),
             '__custom_root_type__': _custom_root_type,
-            # equivalent of inheriting from Representation
-            '__repr_name__': Representation.__repr_name__,
-            '__repr_str__': Representation.__repr_str__,
-            '__pretty__': Representation.__pretty__,
-            '__str__': Representation.__str__,
-            '__repr__': Representation.__repr__,
             **{n: v for n, v in namespace.items() if n not in fields},
         }
         return super().__new__(mcs, name, bases, new_namespace, **kwargs)
@@ -265,6 +259,12 @@ class BaseModel(metaclass=ModelMetaclass):
 
     Config = BaseConfig
     __slots__ = ('__dict__', '__fields_set__')
+    # equivalent of inheriting from Representation
+    __repr_name__ = Representation.__repr_name__
+    __repr_str__ = Representation.__repr_str__
+    __pretty__ = Representation.__pretty__
+    __str__ = Representation.__str__
+    __repr__ = Representation.__repr__
 
     def __init__(__pydantic_self__, **data: Any) -> None:
         # Uses something other than `self` the first arg to allow "self" as a settable attribute


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
@@ -1357,3 +1357,37 @@ class Config:
 
     assert m.dict(exclude_none=True) == {'a': 'a', 'b': 'b'}
     assert m.dict() == {'a': 'a', 'b': 'b', 'c': None}
+
+
+def test_str_method_inheritance():
+    import pydantic
+
+    class Foo(pydantic.BaseModel):
+        x: int = 3
+        y: int = 4
+
+        def __str__(self):
+            return str(self.y + self.x)
+
+    class Bar(Foo):
+        z: bool = False
+
+    assert str(Foo()) == '7'
+    assert str(Bar()) == '7'
+
+
+def test_repr_method_inheritance():
+    import pydantic
+
+    class Foo(pydantic.BaseModel):
+        x: int = 3
+        y: int = 4
+
+        def __repr__(self):
+            return repr(self.y + self.x)
+
+    class Bar(Foo):
+        z: bool = False
+
+    assert repr(Foo()) == '7'
+    assert repr(Bar()) == '7'
Repository: pydantic/pydantic

Issue:
v1.2 change in optional behaviour
from @bartv on #990

It seems that this change caused a regression in the latest release. The behavior between static and dynamic classes is different now.

```py
from typing import Optional

from pydantic import create_model, BaseModel


def test_optional_value():
    class Test(BaseModel):
        field1: str
        field2: Optional[str]

    Test(field1="a", field2="b")
    Test(field1="a")


def test_dynamic_optional_value():
    fields = {'field1': (str, ...), 'field2': (Optional[str], ...)}
    Test = create_model("Test", __base__=BaseModel, **fields)

    Test(field1="a", field2="b")
    Test(field1="a")
```

With pydantic 1.1.1 both test cases succeed, with pydantic 1.2 the dynamic test case fails.

Is this expected? Based on the changelog and the documentation I am inclined to think it is not. Should I open a separate bug?

_Originally posted by @bartv in https://github.com/samuelcolvin/pydantic/issues/990#issuecomment-559708568_


Discussion:
Thanks for reporting and sorry about creating the regression.

We should have noticed this.

I suspect that releasing #1031 as part of a patch release was a mistake. It should have been part of v2.

There are two problems here:

### change in optional behaviour

The meaning of `foobar: Optional[int] = ...` has changed in v1.2 which is not backwards compatible. (See [here](https://pydantic-docs.helpmanual.io/usage/models/#required-fields) for an explanation. We knew this but thought it was a price worth paying. I think that was a mistake I will document this better.

### create_model

This has affected `create_model()` where you can't create an annotation only field, and instead have to use an ellipsis.

I don't see a sensible work around here without more breaking changes. I think the best solution is to use

```py
fields = {'field1': (str, ...), 'field2': (Optional[str], None)}
```

Which is presumably the behaviour you want?
In summary I think the best we can do here is better documentation.

If anyone disagrees and has any clever suggestions of workarounds, please let us know.

Resolving patch:
diff --git a/docs/examples/models_required_fields.py b/docs/examples/models_required_fields.py
new file mode 100644
--- /dev/null
+++ b/docs/examples/models_required_fields.py
@@ -0,0 +1,6 @@
+from pydantic import BaseModel, Field
+
+class Model(BaseModel):
+    a: int
+    b: int = ...
+    c: int = Field(...)


Test patch:
Repository: pydantic/pydantic

Issue:
Settings inheritance with ENV prefix does not work
# Bug

* OS: ubuntu 18.04
* Python version `import sys; print(sys.version)`: 3.7.5 (default, Nov  7 2019, 10:50:52) 
* Pydantic version `import pydantic; print(pydantic.VERSION)`: `1.0b1` or `1.2`, but works fine with `0.32`

```py
import os
from pydantic import BaseSettings


class MyBaseSettings(BaseSettings):
    var: int = 10


class MySubSettings(MyBaseSettings):
    class Config:
        env_prefix = 'PREFIX_'


os.environ['PREFIX_VAR'] = '2'
k = MySubSettings()
print(k.var)  # 10, but should be 2
```

We expect that `k.var` will be equal to 2, but it has default value 10.
It's reproduced since 1.0b1.


Discussion:
I'm looking into this, but I'm afraid the solution isn't trivial.

Weird that this got 11 :+1: and 2 :eyes: in 2 hours. Any idea why this happened?

Resolving patch:
diff --git a/pydantic/env_settings.py b/pydantic/env_settings.py
--- a/pydantic/env_settings.py
+++ b/pydantic/env_settings.py
@@ -66,7 +66,7 @@ class Config:
         @classmethod
         def prepare_field(cls, field: ModelField) -> None:
             env_names: Iterable[str]
-            env = field.field_info.extra.pop('env', None)
+            env = field.field_info.extra.get('env')
             if env is None:
                 if field.has_alias:
                     warnings.warn(
diff --git a/pydantic/fields.py b/pydantic/fields.py
--- a/pydantic/fields.py
+++ b/pydantic/fields.py
@@ -280,6 +280,7 @@ def infer(
     def set_config(self, config: Type['BaseConfig']) -> None:
         self.model_config = config
         info_from_config = config.get_field_info(self.name)
+        config.prepare_field(self)
         if info_from_config:
             self.field_info.alias = info_from_config.get('alias') or self.field_info.alias or self.name
             self.alias = cast(str, self.field_info.alias)


Test patch:
diff --git a/tests/test_settings.py b/tests/test_settings.py
--- a/tests/test_settings.py
+++ b/tests/test_settings.py
@@ -376,3 +376,18 @@ class SubSettings(Settings):
     assert SubSettings().dict() == {'foo': 'fff', 'bar': 'bbb', 'spam': 'spam default'}
     env.set('spam', 'sss')
     assert SubSettings().dict() == {'foo': 'fff', 'bar': 'bbb', 'spam': 'sss'}
+
+
+def test_prefix_on_parent(env):
+    class MyBaseSettings(BaseSettings):
+        var: str = 'old'
+
+    class MySubSettings(MyBaseSettings):
+        class Config:
+            env_prefix = 'PREFIX_'
+
+    assert MyBaseSettings().dict() == {'var': 'old'}
+    assert MySubSettings().dict() == {'var': 'old'}
+    env.set('PREFIX_VAR', 'new')
+    assert MyBaseSettings().dict() == {'var': 'old'}
+    assert MySubSettings().dict() == {'var': 'new'}
Repository: pydantic/pydantic

Issue:
cls is None in validator when validate_assignment is True
# Bug

When we set config value `validate_assignment` to True and define custom validator for a field, and try to set value for the field, we get None in `cls` argument in the validator method instead of expected model class object. In my case I want to store some data in model class object that I want to use for validation and I cannot get it via `cls` because `cls` is None. Of course I can use model class object directly, but this behavior is ambiguous and looks like a bug anyway.

Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`:
```
         pydantic version: 1.3
        pydantic compiled: False
             install path: C:\Users\espdev\AppData\Local\pypoetry\Cache\virtualenvs\ms3eI9mF-py3.8\Lib\site-packages\pydantic
           python version: 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 23:11:46) [MSC v.1916 64 bit (AMD64)]
                 platform: Windows-10-10.0.18362-SP0
 optional deps. installed: []
```

A minimal example:

```py
from pydantic import BaseModel, StrictStr, validator

class Model(BaseModel):
    name: StrictStr

    class Config:
        validate_assignment = True

    @validator('name')
    def _validate_foo(cls, value):
        if cls is None:
            raise ValueError('cls is None')
        return value

if __name__ == '__main__':
    m = Model(name='hello')  # OK
    m.name = 'goodbye'       # <-- ValidationError "cls is None"
```
```
pydantic.error_wrappers.ValidationError: 1 validation error for Model
name
  cls is None (type=value_error)
```



Discussion:

Resolving patch:
diff --git a/pydantic/main.py b/pydantic/main.py
--- a/pydantic/main.py
+++ b/pydantic/main.py
@@ -284,7 +284,7 @@ def __setattr__(self, name, value):
         elif self.__config__.validate_assignment:
             known_field = self.__fields__.get(name, None)
             if known_field:
-                value, error_ = known_field.validate(value, self.dict(exclude={name}), loc=name)
+                value, error_ = known_field.validate(value, self.dict(exclude={name}), loc=name, cls=self.__class__)
                 if error_:
                     raise ValidationError([error_], type(self))
         self.__dict__[name] = value


Test patch:
diff --git a/tests/test_validators.py b/tests/test_validators.py
--- a/tests/test_validators.py
+++ b/tests/test_validators.py
@@ -1017,3 +1017,24 @@ def example_root_validator(cls, values):
     with pytest.raises(ValidationError):
         ModelB(a='a')
     assert not b_called
+
+
+def test_assignment_validator_cls():
+    validator_calls = 0
+
+    class Model(BaseModel):
+        name: str
+
+        class Config:
+            validate_assignment = True
+
+        @validator('name')
+        def check_foo(cls, value):
+            nonlocal validator_calls
+            validator_calls += 1
+            assert cls == Model
+            return value
+
+    m = Model(name='hello')
+    m.name = 'goodbye'
+    assert validator_calls == 2
Repository: pydantic/pydantic

Issue:
Mypy does not allow using the root validator with arguments other than pre or _func
# Bug

Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`:
```
             pydantic version: 1.4
            pydantic compiled: True
                 install path: /home/[username]/Desktop/[project]/env/lib/python3.6/site-packages/pydantic
               python version: 3.6.9 (default, Nov  7 2019, 10:44:02)  [GCC 8.3.0]
                     platform: Linux-5.3.0-26-generic-x86_64-with-Ubuntu-18.04-bionic
     optional deps. installed: ['typing-extensions']

```
Code:
```py
    @root_validator(pre=False, skip_on_failure=True)
    def test_validator(cls, values):
        return values
```
Output:
```
test.py:5: error: No overload variant of "root_validator" matches argument types "bool", "bool"
test.py:5: note: Possible overload variants:
test.py:5: note:     def root_validator(_func: Callable[..., Any]) -> classmethod
test.py:5: note:     def root_validator(*, pre: bool = ...) -> Callable[[Callable[..., Any]], classmethod]
```


Discussion:
It seems like the tests are not checked with mypy.

Resolving patch:
diff --git a/pydantic/class_validators.py b/pydantic/class_validators.py
--- a/pydantic/class_validators.py
+++ b/pydantic/class_validators.py
@@ -103,7 +103,9 @@ def root_validator(_func: AnyCallable) -> classmethod:
 
 
 @overload
-def root_validator(*, pre: bool = False) -> Callable[[AnyCallable], classmethod]:
+def root_validator(
+    *, pre: bool = False, allow_reuse: bool = False, skip_on_failure: bool = False
+) -> Callable[[AnyCallable], classmethod]:
     ...
 
 


Test patch:
diff --git a/tests/mypy/modules/success.py b/tests/mypy/modules/success.py
--- a/tests/mypy/modules/success.py
+++ b/tests/mypy/modules/success.py
@@ -33,7 +33,7 @@ def check_age(cls, value: int) -> int:
     def root_check(cls, values: Dict[str, Any]) -> Dict[str, Any]:
         return values
 
-    @root_validator(pre=True)
+    @root_validator(pre=True, allow_reuse=False, skip_on_failure=False)
     def pre_root_check(cls, values: Dict[str, Any]) -> Dict[str, Any]:
         return values
Repository: pydantic/pydantic

Issue:
Same NameEmail field instances are not equal
# Bug

Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`:
```
             pydantic version: 1.5.1
            pydantic compiled: True
                 install path: /Users/***/.local/share/virtualenvs/tempenv-42b2286175873/lib/python3.7/site-packages/pydantic
               python version: 3.7.4 (default, Jul 22 2019, 11:21:52)  [Clang 10.0.1 (clang-1001.0.46.4)]
                     platform: Darwin-18.7.0-x86_64-i386-64bit
     optional deps. installed: ['email-validator']
```

I'm assuming that equality should be enforced on field types such as `NameEmail`. At the moment it seems that instances that appear to be equal are generating different hashes. Unsure if this is desired, but I would argue it shouldn't be.

```py
import pydantic

# will raise an AssertionError
assert pydantic.NameEmail("test", "test@test.com") == pydantic.NameEmail("test", "test@test.com")
```



Discussion:
Thanks for reporting.

Happy to accept a PR to add a proper `__eq__` method to `NameEmail`

Resolving patch:
diff --git a/pydantic/networks.py b/pydantic/networks.py
--- a/pydantic/networks.py
+++ b/pydantic/networks.py
@@ -329,6 +329,9 @@ def __init__(self, name: str, email: str):
         self.name = name
         self.email = email
 
+    def __eq__(self, other: Any) -> bool:
+        return isinstance(other, NameEmail) and (self.name, self.email) == (other.name, other.email)
+
     @classmethod
     def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:
         field_schema.update(type='string', format='name-email')


Test patch:
diff --git a/tests/test_networks.py b/tests/test_networks.py
--- a/tests/test_networks.py
+++ b/tests/test_networks.py
@@ -453,3 +453,5 @@ class Model(BaseModel):
 
     assert str(Model(v=NameEmail('foo bar', 'foobaR@example.com')).v) == 'foo bar <foobaR@example.com>'
     assert str(Model(v='foo bar  <foobaR@example.com>').v) == 'foo bar <foobaR@example.com>'
+    assert NameEmail('foo bar', 'foobaR@example.com') == NameEmail('foo bar', 'foobaR@example.com')
+    assert NameEmail('foo bar', 'foobaR@example.com') != NameEmail('foo bar', 'different@example.com')
Repository: pydantic/pydantic

Issue:
Add datamodel-code-generator link in pydantic document site.
# Question

@samuelcolvin 
I want to add a link of `datamodel-code-generator` to the pydnatic document site. 
Where should I put the link?

link:
https://github.com/koxudaxi/datamodel-code-generator
https://koxudaxi.github.io/datamodel-code-generator/

## Related issues
https://github.com/samuelcolvin/pydantic/issues/643
https://github.com/samuelcolvin/pydantic/issues/1452


Discussion:
Yes, great.

I would put it under the pycharm plugin.

Maybe one day we'll need a new sub-menu with add-ons, plugins and extensions. But for now a new item in the main menu is fine.

Thanks so much.

Resolving patch:
diff --git a/docs/examples/generate_models_person_model.py b/docs/examples/generate_models_person_model.py
new file mode 100644
--- /dev/null
+++ b/docs/examples/generate_models_person_model.py
@@ -0,0 +1,19 @@
+# generated by datamodel-codegen:
+#   filename:  person.json
+#   timestamp: 2020-05-19T15:07:31+00:00
+from __future__ import annotations
+from typing import Any, List, Optional
+from pydantic import BaseModel, Field, conint
+
+
+class Pet(BaseModel):
+    name: Optional[str] = None
+    age: Optional[int] = None
+
+
+class Person(BaseModel):
+    first_name: str = Field(..., description="The person's first name.")
+    last_name: str = Field(..., description="The person's last name.")
+    age: Optional[conint(ge=0)] = Field(None, description='Age in years.')
+    pets: Optional[List[Pet]] = None
+    comment: Optional[Any] = None


Test patch:
Repository: pydantic/pydantic

Issue:
[docs] Clarify parse_file takes file name not file object
# Problem

I'm new to pydantic.
I was reading the documentation about `parse_file`,

> parse_file()
>    like parse_raw() but for files; cf. helper function

Based on this, I assumed you use it like:

```
with open('myfile.json', 'r') as f:
   MyModel.parse_file(f)
```
Which means you can use it with `BytesIO` or `StringIO`.

But that's not the case. It takes a file *path*, not a file-like object.

# Solution

In the "Model Properties" section, change

> parse_file()
>    like parse_raw() but for files; cf. helper function

to


> parse_file()
>    like parse_raw() but for file paths; cf. helper function

In the helper function section, change

> parse_file: this reads a file and passes the contents to parse_raw. If content_type is omitted, it is inferred from the file's extension.

to

> parse_file: this takes in a file path and reads the file, then passes the contents to parse_raw. If content_type is omitted, it is inferred from the file's extension.

Then append to the code sample to provide an example of `parse_file`:

```
file_path = 'data.json'
with open(file_path, 'w') as f:
   f.write('{"id": 123, "name": "James"}')
m = user.parse_file(file_path)
```
[docs] Clarify parse_file takes file name not file object
# Problem

I'm new to pydantic.
I was reading the documentation about `parse_file`,

> parse_file()
>    like parse_raw() but for files; cf. helper function

Based on this, I assumed you use it like:

```
with open('myfile.json', 'r') as f:
   MyModel.parse_file(f)
```
Which means you can use it with `BytesIO` or `StringIO`.

But that's not the case. It takes a file *path*, not a file-like object.

# Solution

In the "Model Properties" section, change

> parse_file()
>    like parse_raw() but for files; cf. helper function

to


> parse_file()
>    like parse_raw() but for file paths; cf. helper function

In the helper function section, change

> parse_file: this reads a file and passes the contents to parse_raw. If content_type is omitted, it is inferred from the file's extension.

to

> parse_file: this takes in a file path and reads the file, then passes the contents to parse_raw. If content_type is omitted, it is inferred from the file's extension.

Then append to the code sample to provide an example of `parse_file`:

```
file_path = 'data.json'
with open(file_path, 'w') as f:
   f.write('{"id": 123, "name": "James"}')
m = user.parse_file(file_path)
```


Discussion:

Resolving patch:
diff --git a/docs/examples/models_parse.py b/docs/examples/models_parse.py
--- a/docs/examples/models_parse.py
+++ b/docs/examples/models_parse.py
@@ -30,3 +30,9 @@ class User(BaseModel):
     pickle_data, content_type='application/pickle', allow_pickle=True
 )
 print(m)
+
+path = 'data.json'
+with open(path, 'w') as f:
+    f.write('{"id": 123, "name": "James"}')
+m = User.parse_file(path)
+print(m)


Test patch:
Repository: pydantic/pydantic

Issue:
Can't use ~ in dotenv file in Settings
@HenryDashwood The issue here is that you use `~/.env`, which is not directly resolved by `pathlib.Path`.
You could change it to

```python
   class Config:
        env_file = os.path.expanduser('~/.env')
```

Maybe we could add `expanduser` directly in the code when `env_path` is created

_Originally posted by @PrettyWood in https://github.com/samuelcolvin/pydantic/issues/1368#issuecomment-669312462_


Discussion:

Resolving patch:
diff --git a/pydantic/env_settings.py b/pydantic/env_settings.py
--- a/pydantic/env_settings.py
+++ b/pydantic/env_settings.py
@@ -58,7 +58,7 @@ def _build_environ(
         env_file = _env_file if _env_file != env_file_sentinel else self.__config__.env_file
         env_file_encoding = _env_file_encoding if _env_file_encoding is not None else self.__config__.env_file_encoding
         if env_file is not None:
-            env_path = Path(env_file)
+            env_path = Path(env_file).expanduser()
             if env_path.is_file():
                 env_vars = {
                     **read_env_file(


Test patch:
diff --git a/tests/test_settings.py b/tests/test_settings.py
--- a/tests/test_settings.py
+++ b/tests/test_settings.py
@@ -1,4 +1,6 @@
 import os
+import uuid
+from pathlib import Path
 from typing import Dict, List, Optional, Set
 
 import pytest
@@ -547,6 +549,28 @@ class Config:
     assert s.pika == 'p!±@'
 
 
+@pytest.fixture
+def home_tmp():
+    tmp_filename = f'{uuid.uuid4()}.env'
+    home_tmp_path = Path.home() / tmp_filename
+    yield home_tmp_path, tmp_filename
+    home_tmp_path.unlink()
+
+
+@pytest.mark.skipif(not dotenv, reason='python-dotenv not installed')
+def test_env_file_home_directory(home_tmp):
+    home_tmp_path, tmp_filename = home_tmp
+    home_tmp_path.write_text('pika=baz')
+
+    class Settings(BaseSettings):
+        pika: str
+
+        class Config:
+            env_file = f'~/{tmp_filename}'
+
+    assert Settings().pika == 'baz'
+
+
 @pytest.mark.skipif(not dotenv, reason='python-dotenv not installed')
 def test_env_file_none(tmp_path):
     p = tmp_path / '.env'