Repository: samuelcolvin/pydantic
Pull request #2071 (2020-10-29 15:38:19)

Update type annotation for create_model function
<!-- Thank you for your contribution! -->
<!-- Unless your change is trivial, please create an issue to discuss the change before creating a PR -->
<!-- See https://pydantic-docs.helpmanual.io/contributing/ for help on Contributing -->

## Update type annotation for create_model function

Updated `create_model` return type annotation to return type which inherits from `__base__` argument.

For instance, before this PR mypy will fail on the code below:
```python
from pydantic import BaseModel, create_model

class Point(BaseModel):
    x: int
    y: int

NewPoint = create_model('NewPoint', __base__=Point)

point = NewPoint.parse_obj(...)
point.x = 10  # mypy will fail here
```

<!-- Please give a short summary of the changes. -->

<!-- ## Related issue number -->

<!-- Are there any issues opened that will be resolved by merging this change? -->

## Checklist

* [x] Unit tests for the changes exist
* [x] Tests pass on CI and coverage remains at 100%
* [x] Documentation reflects the changes where applicable
* [x] `changes/<pull request or issue id>-<github username>.md` file added describing change
  (see [changes/README.md](https://github.com/samuelcolvin/pydantic/blob/master/changes/README.md) for details)


codecov[bot]: # [Codecov](https://codecov.io/gh/samuelcolvin/pydantic/pull/2071?src=pr&el=h1) Report
> Merging [#2071](https://codecov.io/gh/samuelcolvin/pydantic/pull/2071?src=pr&el=desc) into [master](https://codecov.io/gh/samuelcolvin/pydantic/commit/8dcc87cf422c8344ca565c8ee23b7119bc100949?el=desc) will **decrease** coverage by `3.07%`.
> The diff coverage is `n/a`.


```diff
@@             Coverage Diff             @@
##            master    #2071      +/-   ##
===========================================
- Coverage   100.00%   96.92%   -3.08%     
===========================================
  Files           21       21              
  Lines         4096     4096              
  Branches       821      821              
===========================================
- Hits          4096     3970     -126     
- Misses           0      112     +112     
- Partials         0       14      +14     
```


| [Impacted Files](https://codecov.io/gh/samuelcolvin/pydantic/pull/2071?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [pydantic/generics.py](https://codecov.io/gh/samuelcolvin/pydantic/pull/2071/diff?src=pr&el=tree#diff-cHlkYW50aWMvZ2VuZXJpY3MucHk=) | `41.30% <0.00%> (-58.70%)` | :arrow_down: |
| [pydantic/typing.py](https://codecov.io/gh/samuelcolvin/pydantic/pull/2071/diff?src=pr&el=tree#diff-cHlkYW50aWMvdHlwaW5nLnB5) | `73.98% <0.00%> (-26.02%)` | :arrow_down: |
| [pydantic/decorator.py](https://codecov.io/gh/samuelcolvin/pydantic/pull/2071/diff?src=pr&el=tree#diff-cHlkYW50aWMvZGVjb3JhdG9yLnB5) | `87.42% <0.00%> (-12.58%)` | :arrow_down: |
| [pydantic/version.py](https://codecov.io/gh/samuelcolvin/pydantic/pull/2071/diff?src=pr&el=tree#diff-cHlkYW50aWMvdmVyc2lvbi5weQ==) | `88.23% <0.00%> (-11.77%)` | :arrow_down: |
| [pydantic/fields.py](https://codecov.io/gh/samuelcolvin/pydantic/pull/2071/diff?src=pr&el=tree#diff-cHlkYW50aWMvZmllbGRzLnB5) | `97.90% <0.00%> (-2.10%)` | :arrow_down: |
| [pydantic/env\_settings.py](https://codecov.io/gh/samuelcolvin/pydantic/pull/2071/diff?src=pr&el=tree#diff-cHlkYW50aWMvZW52X3NldHRpbmdzLnB5) | `97.93% <0.00%> (-2.07%)` | :arrow_down: |
| [pydantic/error\_wrappers.py](https://codecov.io/gh/samuelcolvin/pydantic/pull/2071/diff?src=pr&el=tree#diff-cHlkYW50aWMvZXJyb3Jfd3JhcHBlcnMucHk=) | `98.86% <0.00%> (-1.14%)` | :arrow_down: |
| [pydantic/networks.py](https://codecov.io/gh/samuelcolvin/pydantic/pull/2071/diff?src=pr&el=tree#diff-cHlkYW50aWMvbmV0d29ya3MucHk=) | `99.22% <0.00%> (-0.78%)` | :arrow_down: |
| [pydantic/utils.py](https://codecov.io/gh/samuelcolvin/pydantic/pull/2071/diff?src=pr&el=tree#diff-cHlkYW50aWMvdXRpbHMucHk=) | `99.29% <0.00%> (-0.71%)` | :arrow_down: |
| [pydantic/types.py](https://codecov.io/gh/samuelcolvin/pydantic/pull/2071/diff?src=pr&el=tree#diff-cHlkYW50aWMvdHlwZXMucHk=) | `99.58% <0.00%> (-0.42%)` | :arrow_down: |

------

[Continue to review full report at Codecov](https://codecov.io/gh/samuelcolvin/pydantic/pull/2071?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/samuelcolvin/pydantic/pull/2071?src=pr&el=footer). Last update [8dcc87c...211264c](https://codecov.io/gh/samuelcolvin/pydantic/pull/2071?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).


Patch:
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index b411771f7..b9630e829 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -72,7 +72,7 @@ jobs:
       run: make test
 
     - run: coverage xml
-    - uses: codecov/codecov-action@v1.0.13
+    - uses: codecov/codecov-action@v1.0.14
       with:
         file: ./coverage.xml
         env_vars: COMPILED,DEPS,PYTHON,OS
@@ -87,7 +87,7 @@ jobs:
       run: make test
 
     - run: coverage xml
-    - uses: codecov/codecov-action@v1.0.13
+    - uses: codecov/codecov-action@v1.0.14
       with:
         file: ./coverage.xml
         env_vars: COMPILED,DEPS,PYTHON,OS
@@ -105,7 +105,7 @@ jobs:
       run: make test
 
     - run: coverage xml
-    - uses: codecov/codecov-action@v1.0.13
+    - uses: codecov/codecov-action@v1.0.14
       with:
         file: ./coverage.xml
         env_vars: COMPILED,DEPS,PYTHON,OS
@@ -143,7 +143,7 @@ jobs:
 
     - run: coverage xml
 
-    - uses: codecov/codecov-action@v1.0.13
+    - uses: codecov/codecov-action@v1.0.14
       with:
         file: ./coverage.xml
         env_vars: COMPILED,DEPS,PYTHON,OS
diff --git a/HISTORY.md b/HISTORY.md
index 21c03f41b..692c8e2c2 100644
--- a/HISTORY.md
+++ b/HISTORY.md
@@ -1,3 +1,9 @@
+## v1.7.2 (2020-11-01)
+
+* fix slow `GenericModel` concrete model creation, allow `GenericModel` concrete name reusing in module, #2078 by @MrMrRobat
+* keep the order of the fields when `validate_assignment` is set, #2073 by @PrettyWood
+* forward all the params of the stdlib `dataclass` when converted into _pydantic_ `dataclass`, #2065 by @PrettyWood
+
 ## v1.7.1 (2020-10-28)
 
 Thank you to pydantic's sponsors:
diff --git a/changes/1975-mdavis-xyz.md b/changes/1975-mdavis-xyz.md
new file mode 100644
index 000000000..82cf2eb29
--- /dev/null
+++ b/changes/1975-mdavis-xyz.md
@@ -0,0 +1,1 @@
+Add `NonNegativeInt`, `NonPositiveInt`, `NonNegativeFloat`, `NonPositiveFloat`
diff --git a/changes/2045-PrettyWood.md b/changes/2045-PrettyWood.md
new file mode 100644
index 000000000..1fdf47c1e
--- /dev/null
+++ b/changes/2045-PrettyWood.md
@@ -0,0 +1,1 @@
+add default encoder for `Pattern` type
\ No newline at end of file
diff --git a/changes/2071-uriyyo.md b/changes/2071-uriyyo.md
new file mode 100644
index 000000000..36b9a6aa1
--- /dev/null
+++ b/changes/2071-uriyyo.md
@@ -0,0 +1,1 @@
+Updated `create_model` return type annotation to return type which inherits from `__base__` argument.
\ No newline at end of file
diff --git a/changes/2090-PrettyWood.md b/changes/2090-PrettyWood.md
new file mode 100644
index 000000000..2e2e56f55
--- /dev/null
+++ b/changes/2090-PrettyWood.md
@@ -0,0 +1,1 @@
+Ignore `__doc__` as private attribute when `Config.underscore_attrs_are_private` is set
\ No newline at end of file
diff --git a/docs/build/schema_mapping.py b/docs/build/schema_mapping.py
index f9731c0a0..578172746 100755
--- a/docs/build/schema_mapping.py
+++ b/docs/build/schema_mapping.py
@@ -382,6 +382,20 @@ table = [
         'JSON Schema Validation',
         ''
     ],
+    [
+        'NonNegativeInt',
+        'integer',
+        {'minimum': 0},
+        'JSON Schema Validation',
+        ''
+    ],
+    [
+        'NonPositiveInt',
+        'integer',
+        {'maximum': 0},
+        'JSON Schema Validation',
+        ''
+    ],
     [
         'ConstrainedFloat',
         'number',
@@ -413,6 +427,20 @@ table = [
         'JSON Schema Validation',
         ''
     ],
+    [
+        'NonNegativeFloat',
+        'number',
+        {'minimum': 0},
+        'JSON Schema Validation',
+        ''
+    ],
+    [
+        'NonPositiveFloat',
+        'number',
+        {'maximum': 0},
+        'JSON Schema Validation',
+        ''
+    ],
     [
         'ConstrainedDecimal',
         'number',
diff --git a/docs/examples/dataclasses_stdlib_with_basemodel.py b/docs/examples/dataclasses_stdlib_with_basemodel.py
index 35ff1e883..92b494891 100644
--- a/docs/examples/dataclasses_stdlib_with_basemodel.py
+++ b/docs/examples/dataclasses_stdlib_with_basemodel.py
@@ -5,14 +5,20 @@ from typing import Optional
 from pydantic import BaseModel, ValidationError
 
 
+@dataclasses.dataclass(frozen=True)
+class User:
+    name: str
+
+
 @dataclasses.dataclass
 class File:
     filename: str
-    last_modification_time: Optional[datetime]
+    last_modification_time: Optional[datetime] = None
 
 
 class Foo(BaseModel):
     file: File
+    user: Optional[User] = None
 
 
 file = File(
@@ -25,3 +31,9 @@ try:
     Foo(file=file)
 except ValidationError as e:
     print(e)
+
+foo = Foo(file=File(filename='myfile'), user=User(name='pika'))
+try:
+    foo.user.name = 'bulbi'
+except dataclasses.FrozenInstanceError as e:
+    print(e)
diff --git a/docs/examples/types_constrained.py b/docs/examples/types_constrained.py
index c97fe24ae..53addddb1 100644
--- a/docs/examples/types_constrained.py
+++ b/docs/examples/types_constrained.py
@@ -6,6 +6,10 @@ from pydantic import (
     NegativeInt,
     PositiveFloat,
     PositiveInt,
+    NonNegativeFloat,
+    NonNegativeInt,
+    NonPositiveFloat,
+    NonPositiveInt,
     conbytes,
     condecimal,
     confloat,
@@ -29,12 +33,16 @@ class Model(BaseModel):
     mod_int: conint(multiple_of=5)
     pos_int: PositiveInt
     neg_int: NegativeInt
+    non_neg_int: NonNegativeInt
+    non_pos_int: NonPositiveInt
 
     big_float: confloat(gt=1000, lt=1024)
     unit_interval: confloat(ge=0, le=1)
     mod_float: confloat(multiple_of=0.5)
     pos_float: PositiveFloat
     neg_float: NegativeFloat
+    non_neg_float: NonNegativeFloat
+    non_pos_float: NonPositiveFloat
 
     short_list: conlist(int, min_items=1, max_items=4)
     short_set: conset(int, min_items=1, max_items=4)
diff --git a/docs/usage/dataclasses.md b/docs/usage/dataclasses.md
index 54dbcbbf3..536d91205 100644
--- a/docs/usage/dataclasses.md
+++ b/docs/usage/dataclasses.md
@@ -71,8 +71,9 @@ _(This script is complete, it should run "as is")_
 
 ### Use of stdlib dataclasses with `BaseModel`
 
-Bear in mind that stdlib dataclasses (nested or not) are **automatically converted** into _pydantic_ dataclasses
-when mixed with `BaseModel`!
+Bear in mind that stdlib dataclasses (nested or not) are **automatically converted** into _pydantic_
+dataclasses when mixed with `BaseModel`! Furthermore the generated _pydantic_ dataclass will have
+the **exact same configuration** (`order`, `frozen`, ...) as the original one.
 
 ```py
 {!.tmp_examples/dataclasses_stdlib_with_basemodel.py!}
diff --git a/docs/usage/settings.md b/docs/usage/settings.md
index a06ea52d4..9f9c50580 100644
--- a/docs/usage/settings.md
+++ b/docs/usage/settings.md
@@ -135,7 +135,7 @@ Placing secret values in files is a common pattern to provide sensitive configur
 A secret file follows the same principal as a dotenv file except it only contains a single value and the file name 
 is used as the key. A secret file will look like the following:
 
-`/var/run/db_password`:
+`/var/run/database_password`:
 ```
 super_secret_database_password
 ```
diff --git a/pydantic/__init__.py b/pydantic/__init__.py
index 5cfc0583f..7b8a609b6 100644
--- a/pydantic/__init__.py
+++ b/pydantic/__init__.py
@@ -76,10 +76,14 @@ __all__ = [
     'conint',
     'PositiveInt',
     'NegativeInt',
+    'NonNegativeInt',
+    'NonPositiveInt',
     'ConstrainedFloat',
     'confloat',
     'PositiveFloat',
     'NegativeFloat',
+    'NonNegativeFloat',
+    'NonPositiveFloat',
     'ConstrainedDecimal',
     'condecimal',
     'UUID1',
diff --git a/pydantic/dataclasses.py b/pydantic/dataclasses.py
index 28e2f9509..0d28e1b20 100644
--- a/pydantic/dataclasses.py
+++ b/pydantic/dataclasses.py
@@ -220,6 +220,9 @@ def make_dataclass_validator(_cls: Type[Any], config: Type['BaseConfig']) -> 'Ca
     """
     Create a pydantic.dataclass from a builtin dataclass to add type validation
     and yield the validators
+    It retrieves the parameters of the dataclass and forwards them to the newly created dataclass
     """
-    cls = dataclass(_cls, config=config)
+    dataclass_params = _cls.__dataclass_params__
+    stdlib_dataclass_parameters = {param: getattr(dataclass_params, param) for param in dataclass_params.__slots__}
+    cls = dataclass(_cls, config=config, **stdlib_dataclass_parameters)
     yield from _get_validators(cls)
diff --git a/pydantic/generics.py b/pydantic/generics.py
index 852cc545f..76be7599b 100644
--- a/pydantic/generics.py
+++ b/pydantic/generics.py
@@ -1,9 +1,7 @@
 import sys
-from types import FrameType, ModuleType
 from typing import (
     TYPE_CHECKING,
     Any,
-    Callable,
     ClassVar,
     Dict,
     Generic,
@@ -62,12 +60,12 @@ class GenericModel(BaseModel):
         model_name = cls.__concrete_name__(params)
         validators = gather_all_validators(cls)
         fields = _build_generic_fields(cls.__fields__, concrete_type_hints, typevars_map)
-        model_module = get_caller_module_name() or cls.__module__
+        model_module, called_globally = get_caller_frame_info()
         created_model = cast(
             Type[GenericModel],  # casting ensures mypy is aware of the __concrete__ and __parameters__ attributes
             create_model(
                 model_name,
-                __module__=model_module,
+                __module__=model_module or cls.__module__,
                 __base__=cls,
                 __config__=None,
                 __validators__=validators,
@@ -75,13 +73,13 @@ class GenericModel(BaseModel):
             ),
         )
 
-        if is_call_from_module():  # create global reference and therefore allow pickling
-            object_in_module = sys.modules[model_module].__dict__.setdefault(model_name, created_model)
-            if object_in_module is not created_model:
-                # this should not ever happen because of _generic_types_cache, but just in case
-                raise TypeError(f'{model_name!r} already defined above, please consider reusing it') from NameError(
-                    f'Name conflict: {model_name!r} in {model_module!r} is already used by {object_in_module!r}'
-                )
+        if called_globally:  # create global reference and therefore allow pickling
+            object_by_reference = None
+            reference_name = model_name
+            reference_module_globals = sys.modules[created_model.__module__].__dict__
+            while object_by_reference is not created_model:
+                object_by_reference = reference_module_globals.setdefault(reference_name, created_model)
+                reference_name += '_'
 
         created_model.Config = cls.Config
         concrete = all(not _is_typevar(v) for v in concrete_type_hints.values())
@@ -143,34 +141,19 @@ def _is_typevar(v: Any) -> bool:
     return isinstance(v, TypeVar)
 
 
-def get_caller_module_name() -> Optional[str]:
-    """
-    Used inside a function to get its caller module name
-
-    Will only work against non-compiled code, therefore used only in pydantic.generics
-    """
-    import inspect
-
-    try:
-        previous_caller_frame = inspect.stack()[2].frame
-    except IndexError as e:
-        raise RuntimeError('This function must be used inside another function') from e
-
-    getmodule = cast(Callable[[FrameType, str], Optional[ModuleType]], inspect.getmodule)
-    previous_caller_module = getmodule(previous_caller_frame, previous_caller_frame.f_code.co_filename)
-    return previous_caller_module.__name__ if previous_caller_module is not None else None
-
-
-def is_call_from_module() -> bool:
+def get_caller_frame_info() -> Tuple[Optional[str], bool]:
     """
     Used inside a function to check whether it was called globally
 
     Will only work against non-compiled code, therefore used only in pydantic.generics
-    """
-    import inspect
 
+    :returns Tuple[module_name, called_globally]
+    """
     try:
-        previous_caller_frame = inspect.stack()[2].frame
-    except IndexError as e:
+        previous_caller_frame = sys._getframe(2)
+    except ValueError as e:
         raise RuntimeError('This function must be used inside another function') from e
-    return previous_caller_frame.f_locals is previous_caller_frame.f_globals
+    except AttributeError:  # sys module does not have _getframe function, so there's nothing we can do about it
+        return None, False
+    frame_globals = previous_caller_frame.f_globals
+    return frame_globals.get('__name__'), previous_caller_frame.f_locals is frame_globals
diff --git a/pydantic/json.py b/pydantic/json.py
index 9ce9d57d5..143ae877b 100644
--- a/pydantic/json.py
+++ b/pydantic/json.py
@@ -5,7 +5,7 @@ from enum import Enum
 from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network
 from pathlib import Path
 from types import GeneratorType
-from typing import Any, Callable, Dict, Type, Union
+from typing import Any, Callable, Dict, Pattern, Type, Union
 from uuid import UUID
 
 from .color import Color
@@ -54,6 +54,9 @@ def pydantic_encoder(obj: Any) -> Any:
     elif is_dataclass(obj):
         return asdict(obj)
 
+    if isinstance(obj, Pattern):
+        return obj.pattern
+
     # Check the class type and its superclasses for a matching encoder
     for base in obj.__class__.__mro__[:-1]:
         try:
diff --git a/pydantic/main.py b/pydantic/main.py
index 22a18dd10..b63c6cbaf 100644
--- a/pydantic/main.py
+++ b/pydantic/main.py
@@ -384,14 +384,14 @@ class BaseModel(Representation, metaclass=ModelMetaclass):
 
             known_field = self.__fields__.get(name, None)
             if known_field:
-                original_value = self.__dict__.pop(name)
-                try:
-                    value, error_ = known_field.validate(value, self.__dict__, loc=name, cls=self.__class__)
-                    if error_:
-                        raise ValidationError([error_], self.__class__)
-                except Exception:
-                    self.__dict__[name] = original_value
-                    raise
+                # We want to
+                # - make sure validators are called without the current value for this field inside `values`
+                # - keep other values (e.g. submodels) untouched (using `BaseModel.dict()` will change them into dicts)
+                # - keep the order of the fields
+                dict_without_original_value = {k: v for k, v in self.__dict__.items() if k != name}
+                value, error_ = known_field.validate(value, dict_without_original_value, loc=name, cls=self.__class__)
+                if error_:
+                    raise ValidationError([error_], self.__class__)
                 else:
                     new_values[name] = value
 
@@ -870,11 +870,11 @@ def create_model(
     __model_name: str,
     *,
     __config__: Type[BaseConfig] = None,
-    __base__: Type[BaseModel] = None,
+    __base__: Type['Model'] = None,
     __module__: str = __name__,
     __validators__: Dict[str, classmethod] = None,
     **field_definitions: Any,
-) -> Type[BaseModel]:
+) -> Type['Model']:
     """
     Dynamically create a model.
     :param __model_name: name of the created model
@@ -887,11 +887,12 @@ def create_model(
         `foobar=(str, ...)` or `foobar=123`, or, for complex use-cases, in the format
         `<name>=<FieldInfo>`, e.g. `foo=Field(default_factory=datetime.utcnow, alias='bar')`
     """
-    if __base__:
+
+    if __base__ is not None:
         if __config__ is not None:
             raise ConfigError('to avoid confusion __config__ and __base__ cannot be used together')
     else:
-        __base__ = BaseModel
+        __base__ = cast(Type['Model'], BaseModel)
 
     fields = {}
     annotations = {}
diff --git a/pydantic/types.py b/pydantic/types.py
index 9c462e124..9c3279b99 100644
--- a/pydantic/types.py
+++ b/pydantic/types.py
@@ -63,10 +63,14 @@ __all__ = [
     'conint',
     'PositiveInt',
     'NegativeInt',
+    'NonNegativeInt',
+    'NonPositiveInt',
     'ConstrainedFloat',
     'confloat',
     'PositiveFloat',
     'NegativeFloat',
+    'NonNegativeFloat',
+    'NonPositiveFloat',
     'ConstrainedDecimal',
     'condecimal',
     'UUID1',
@@ -379,6 +383,14 @@ class NegativeInt(ConstrainedInt):
     lt = 0
 
 
+class NonPositiveInt(ConstrainedInt):
+    le = 0
+
+
+class NonNegativeInt(ConstrainedInt):
+    ge = 0
+
+
 class StrictInt(ConstrainedInt):
     strict = True
 
@@ -440,6 +452,14 @@ class NegativeFloat(ConstrainedFloat):
     lt = 0
 
 
+class NonPositiveFloat(ConstrainedFloat):
+    le = 0
+
+
+class NonNegativeFloat(ConstrainedFloat):
+    ge = 0
+
+
 class StrictFloat(ConstrainedFloat):
     strict = True
 
diff --git a/pydantic/utils.py b/pydantic/utils.py
index 4592223d1..e3e613ca3 100644
--- a/pydantic/utils.py
+++ b/pydantic/utils.py
@@ -631,4 +631,10 @@ def is_valid_field(name: str) -> bool:
 
 
 def is_valid_private_name(name: str) -> bool:
-    return not is_valid_field(name) and name not in {'__annotations__', '__classcell__', '__module__', '__qualname__'}
+    return not is_valid_field(name) and name not in {
+        '__annotations__',
+        '__classcell__',
+        '__doc__',
+        '__module__',
+        '__qualname__',
+    }
diff --git a/pydantic/version.py b/pydantic/version.py
index ca0ced71f..cd81ee5f2 100644
--- a/pydantic/version.py
+++ b/pydantic/version.py
@@ -1,6 +1,6 @@
 __all__ = 'VERSION', 'version_info'
 
-VERSION = '1.7.1'
+VERSION = '1.7.2'
 
 
 def version_info() -> str:


Test patch:
diff --git a/tests/mypy/modules/plugin_success.py b/tests/mypy/modules/plugin_success.py
index af4b8e376..c173bc9e0 100644
--- a/tests/mypy/modules/plugin_success.py
+++ b/tests/mypy/modules/plugin_success.py
@@ -1,6 +1,6 @@
 from typing import ClassVar, Optional, Union
 
-from pydantic import BaseModel, Field
+from pydantic import BaseModel, Field, create_model
 from pydantic.dataclasses import dataclass
 
 
@@ -133,3 +133,9 @@ class NestedModel(BaseModel):
 
 
 _ = NestedModel.Model
+
+
+DynamicModel = create_model('DynamicModel', __base__=Model)
+
+dynamic_model = DynamicModel(x=1, y='y')
+dynamic_model.x = 2
diff --git a/tests/test_dataclasses.py b/tests/test_dataclasses.py
index 061b73d09..e213ff567 100644
--- a/tests/test_dataclasses.py
+++ b/tests/test_dataclasses.py
@@ -777,3 +777,21 @@ def test_dataclass_arbitrary():
             arbitrary_types_allowed = True
 
     TestModel(a=ArbitraryType(), b=(ArbitraryType(), [ArbitraryType()]))
+
+
+def test_forward_stdlib_dataclass_params():
+    @dataclasses.dataclass(frozen=True)
+    class Item:
+        name: str
+
+    class Example(BaseModel):
+        item: Item
+        other: str
+
+        class Config:
+            arbitrary_types_allowed = True
+
+    e = Example(item=Item(name='pika'), other='bulbi')
+    e.other = 'bulbi2'
+    with pytest.raises(dataclasses.FrozenInstanceError):
+        e.item.name = 'pika2'
diff --git a/tests/test_generics.py b/tests/test_generics.py
index a37c2a8e5..ecd39b8f3 100644
--- a/tests/test_generics.py
+++ b/tests/test_generics.py
@@ -5,7 +5,7 @@ from typing import Any, ClassVar, Dict, Generic, List, Optional, Tuple, Type, Ty
 import pytest
 
 from pydantic import BaseModel, Field, ValidationError, root_validator, validator
-from pydantic.generics import GenericModel, _generic_types_cache, get_caller_module_name
+from pydantic.generics import GenericModel, _generic_types_cache
 
 skip_36 = pytest.mark.skipif(sys.version_info < (3, 7), reason='generics only supported for python 3.7 and above')
 
@@ -686,8 +686,7 @@ def test_generic_model_redefined_without_cache_fail(create_module):
     def module():
         from typing import Generic, TypeVar
 
-        import pytest
-
+        from pydantic import BaseModel
         from pydantic.generics import GenericModel, _generic_types_cache
 
         t = TypeVar('t')
@@ -695,86 +694,65 @@ def test_generic_model_redefined_without_cache_fail(create_module):
         class MyGeneric(GenericModel, Generic[t]):
             value: t
 
-        concrete = MyGeneric[t]
-        _generic_types_cache.clear()
-        with pytest.raises(
-            TypeError, match=r"'MyGeneric\[t\]' already defined above, please consider reusing it"
-        ) as exc_info:
-            MyGeneric[t]
-
-        cause = exc_info.value.__cause__
-        assert isinstance(cause, NameError), cause
-        expected_message = f"Name conflict: 'MyGeneric[t]' in {__name__!r} is already used by {concrete!r}"
-        assert cause.args[0] == expected_message, f'{cause.args[0]} != {expected_message}'
-
-
-def test_get_caller_module_name(create_module):
-    @create_module
-    def module():
-        from pydantic.generics import get_caller_module_name
-
-        def get_current_module_name():
-            return get_caller_module_name()
+        class Model(BaseModel):
+            ...
 
-        assert get_current_module_name() == __name__
+        concrete = MyGeneric[Model]
+        _generic_types_cache.clear()
+        second_concrete = MyGeneric[Model]
 
+        class Model(BaseModel):  # same name, but type different, so it's not in cache
+            ...
 
-def test_get_caller_module_name_not_found(mocker):
-    mocker.patch('inspect.getmodule', return_value=None)
-    assert get_caller_module_name() is None
+        third_concrete = MyGeneric[Model]
+        assert concrete is not second_concrete
+        assert concrete is not third_concrete
+        assert second_concrete is not third_concrete
+        assert globals()['MyGeneric[Model]'] is concrete
+        assert globals()['MyGeneric[Model]_'] is second_concrete
+        assert globals()['MyGeneric[Model]__'] is third_concrete
 
 
-def test_is_call_from_module(create_module):
+def test_get_caller_frame_info(create_module):
     @create_module
     def module():
-        from pydantic.generics import is_call_from_module
+        from pydantic.generics import get_caller_frame_info
 
         def function():
-            assert is_call_from_module()
+            assert get_caller_frame_info() == (__name__, True)
 
             another_function()
 
         def another_function():
-            assert not is_call_from_module()
+            assert get_caller_frame_info() == (__name__, False)
             third_function()
 
         def third_function():
-            assert not is_call_from_module()
+            assert get_caller_frame_info() == (__name__, False)
 
         function()
 
 
-def test_is_call_from_module_called_in_module(create_module):
+def test_get_caller_frame_info_called_from_module(create_module):
     @create_module
     def module():
         from unittest.mock import patch
 
         import pytest
 
-        from pydantic.generics import is_call_from_module
-
-        with pytest.raises(RuntimeError, match='This function must be used inside another function') as exc_info:
-            with patch('inspect.stack', new=lambda: [..., ...]):
-                is_call_from_module()
-
-        e = exc_info.value
-        assert isinstance(e.__cause__, IndexError)
-        assert isinstance(e.__context__, IndexError)
-
+        from pydantic.generics import get_caller_frame_info
 
-def test_get_caller_module_called_from_module(create_module):
-    @create_module
-    def module():
-        from unittest.mock import patch
-
-        import pytest
+        with pytest.raises(RuntimeError, match='This function must be used inside another function'):
+            with patch('sys._getframe', side_effect=ValueError('getframe_exc')):
+                get_caller_frame_info()
 
-        from pydantic.generics import get_caller_module_name
 
-        with pytest.raises(RuntimeError, match='This function must be used inside another function') as exc_info:
-            with patch('inspect.stack', new=lambda: [..., ...]):
-                get_caller_module_name()
+def test_get_caller_frame_info_when_sys_getframe_undefined():
+    from pydantic.generics import get_caller_frame_info
 
-        e = exc_info.value
-        assert isinstance(e.__cause__, IndexError)
-        assert isinstance(e.__context__, IndexError)
+    getframe = sys._getframe
+    del sys._getframe
+    try:
+        assert get_caller_frame_info() == (None, False)
+    finally:  # just to make sure we always setting original attribute back
+        sys._getframe = getframe
diff --git a/tests/test_json.py b/tests/test_json.py
index cf916f6ae..07bfc04f7 100644
--- a/tests/test_json.py
+++ b/tests/test_json.py
@@ -1,5 +1,6 @@
 import datetime
 import json
+import re
 import sys
 from dataclasses import dataclass as vanilla_dataclass
 from decimal import Decimal
@@ -51,6 +52,7 @@ class MyEnum(Enum):
         (Decimal('12.34'), '12.34'),
         (create_model('BarModel', a='b', c='d')(), '{"a": "b", "c": "d"}'),
         (MyEnum.foo, '"bar"'),
+        (re.compile('^regex$'), '"^regex$"'),
     ],
 )
 def test_encoding(input, output):
diff --git a/tests/test_private_attributes.py b/tests/test_private_attributes.py
index 48be872e2..21f52090b 100644
--- a/tests/test_private_attributes.py
+++ b/tests/test_private_attributes.py
@@ -55,6 +55,8 @@ def test_private_attribute_factory():
 
 def test_private_attribute_annotation():
     class Model(BaseModel):
+        """The best model"""
+
         __foo__: str
 
         class Config:
@@ -63,6 +65,7 @@ def test_private_attribute_annotation():
     assert Model.__slots__ == {'__foo__'}
     assert repr(Model.__foo__) == "<member '__foo__' of 'Model' objects>"
     assert Model.__private_attributes__ == {'__foo__': PrivateAttr(Undefined)}
+    assert repr(Model.__doc__) == "'The best model'"
 
     m = Model()
     with pytest.raises(AttributeError):
diff --git a/tests/test_schema.py b/tests/test_schema.py
index 9da7d14cc..13d92585a 100644
--- a/tests/test_schema.py
+++ b/tests/test_schema.py
@@ -42,6 +42,10 @@ from pydantic.types import (
     NoneBytes,
     NoneStr,
     NoneStrBytes,
+    NonNegativeFloat,
+    NonNegativeInt,
+    NonPositiveFloat,
+    NonPositiveInt,
     PositiveFloat,
     PositiveInt,
     PyObject,
@@ -754,6 +758,8 @@ def test_secret_types(field_type, inner_type):
         (conint(multiple_of=5), {'multipleOf': 5}),
         (PositiveInt, {'exclusiveMinimum': 0}),
         (NegativeInt, {'exclusiveMaximum': 0}),
+        (NonNegativeInt, {'minimum': 0}),
+        (NonPositiveInt, {'maximum': 0}),
     ],
 )
 def test_special_int_types(field_type, expected_schema):
@@ -780,6 +786,8 @@ def test_special_int_types(field_type, expected_schema):
         (confloat(multiple_of=5), {'multipleOf': 5}),
         (PositiveFloat, {'exclusiveMinimum': 0}),
         (NegativeFloat, {'exclusiveMaximum': 0}),
+        (NonNegativeFloat, {'minimum': 0}),
+        (NonPositiveFloat, {'maximum': 0}),
         (ConstrainedDecimal, {}),
         (condecimal(gt=5, lt=10), {'exclusiveMinimum': 5, 'exclusiveMaximum': 10}),
         (condecimal(ge=5, le=10), {'minimum': 5, 'maximum': 10}),
diff --git a/tests/test_types.py b/tests/test_types.py
index 7e4c7e0bd..b07d1408d 100644
--- a/tests/test_types.py
+++ b/tests/test_types.py
@@ -43,6 +43,10 @@ from pydantic import (
     NameEmail,
     NegativeFloat,
     NegativeInt,
+    NonNegativeFloat,
+    NonNegativeInt,
+    NonPositiveFloat,
+    NonPositiveInt,
     PositiveFloat,
     PositiveInt,
     PyObject,
@@ -1178,15 +1182,17 @@ def test_int_validation():
     class Model(BaseModel):
         a: PositiveInt = None
         b: NegativeInt = None
-        c: conint(gt=4, lt=10) = None
-        d: conint(ge=0, le=10) = None
-        e: conint(multiple_of=5) = None
+        c: NonNegativeInt = None
+        d: NonPositiveInt = None
+        e: conint(gt=4, lt=10) = None
+        f: conint(ge=0, le=10) = None
+        g: conint(multiple_of=5) = None
 
-    m = Model(a=5, b=-5, c=5, d=0, e=25)
-    assert m == {'a': 5, 'b': -5, 'c': 5, 'd': 0, 'e': 25}
+    m = Model(a=5, b=-5, c=0, d=0, e=5, f=0, g=25)
+    assert m == {'a': 5, 'b': -5, 'c': 0, 'd': 0, 'e': 5, 'f': 0, 'g': 25}
 
     with pytest.raises(ValidationError) as exc_info:
-        Model(a=-5, b=5, c=-5, d=11, e=42)
+        Model(a=-5, b=5, c=-5, d=5, e=-5, f=11, g=42)
     assert exc_info.value.errors() == [
         {
             'loc': ('a',),
@@ -1202,18 +1208,30 @@ def test_int_validation():
         },
         {
             'loc': ('c',),
+            'msg': 'ensure this value is greater than or equal to 0',
+            'type': 'value_error.number.not_ge',
+            'ctx': {'limit_value': 0},
+        },
+        {
+            'loc': ('d',),
+            'msg': 'ensure this value is less than or equal to 0',
+            'type': 'value_error.number.not_le',
+            'ctx': {'limit_value': 0},
+        },
+        {
+            'loc': ('e',),
             'msg': 'ensure this value is greater than 4',
             'type': 'value_error.number.not_gt',
             'ctx': {'limit_value': 4},
         },
         {
-            'loc': ('d',),
+            'loc': ('f',),
             'msg': 'ensure this value is less than or equal to 10',
             'type': 'value_error.number.not_le',
             'ctx': {'limit_value': 10},
         },
         {
-            'loc': ('e',),
+            'loc': ('g',),
             'msg': 'ensure this value is a multiple of 5',
             'type': 'value_error.number.not_multiple',
             'ctx': {'multiple_of': 5},
@@ -1225,15 +1243,17 @@ def test_float_validation():
     class Model(BaseModel):
         a: PositiveFloat = None
         b: NegativeFloat = None
-        c: confloat(gt=4, lt=12.2) = None
-        d: confloat(ge=0, le=9.9) = None
-        e: confloat(multiple_of=0.5) = None
+        c: NonNegativeFloat = None
+        d: NonPositiveFloat = None
+        e: confloat(gt=4, lt=12.2) = None
+        f: confloat(ge=0, le=9.9) = None
+        g: confloat(multiple_of=0.5) = None
 
-    m = Model(a=5.1, b=-5.2, c=5.3, d=9.9, e=2.5)
-    assert m.dict() == {'a': 5.1, 'b': -5.2, 'c': 5.3, 'd': 9.9, 'e': 2.5}
+    m = Model(a=5.1, b=-5.2, c=0, d=0, e=5.3, f=9.9, g=2.5)
+    assert m.dict() == {'a': 5.1, 'b': -5.2, 'c': 0, 'd': 0, 'e': 5.3, 'f': 9.9, 'g': 2.5}
 
     with pytest.raises(ValidationError) as exc_info:
-        Model(a=-5.1, b=5.2, c=-5.3, d=9.91, e=4.2)
+        Model(a=-5.1, b=5.2, c=-5.1, d=5.1, e=-5.3, f=9.91, g=4.2)
     assert exc_info.value.errors() == [
         {
             'loc': ('a',),
@@ -1249,18 +1269,30 @@ def test_float_validation():
         },
         {
             'loc': ('c',),
+            'msg': 'ensure this value is greater than or equal to 0',
+            'type': 'value_error.number.not_ge',
+            'ctx': {'limit_value': 0},
+        },
+        {
+            'loc': ('d',),
+            'msg': 'ensure this value is less than or equal to 0',
+            'type': 'value_error.number.not_le',
+            'ctx': {'limit_value': 0},
+        },
+        {
+            'loc': ('e',),
             'msg': 'ensure this value is greater than 4',
             'type': 'value_error.number.not_gt',
             'ctx': {'limit_value': 4},
         },
         {
-            'loc': ('d',),
+            'loc': ('f',),
             'msg': 'ensure this value is less than or equal to 9.9',
             'type': 'value_error.number.not_le',
             'ctx': {'limit_value': 9.9},
         },
         {
-            'loc': ('e',),
+            'loc': ('g',),
             'msg': 'ensure this value is a multiple of 0.5',
             'type': 'value_error.number.not_multiple',
             'ctx': {'multiple_of': 0.5},
diff --git a/tests/test_validators.py b/tests/test_validators.py
index 9097c17d2..62a68b031 100644
--- a/tests/test_validators.py
+++ b/tests/test_validators.py
@@ -5,7 +5,7 @@ from typing import Dict, List, Optional, Tuple
 
 import pytest
 
-from pydantic import BaseModel, ConfigError, Extra, ValidationError, errors, validator
+from pydantic import BaseModel, ConfigError, Extra, Field, ValidationError, errors, validator
 from pydantic.class_validators import make_generic_validator, root_validator
 from pydantic.typing import Literal
 
@@ -1162,7 +1162,8 @@ def test_field_that_is_being_validated_is_excluded_from_validator_values(mocker)
 
     class Model(BaseModel):
         foo: str
-        bar: str
+        bar: str = Field(alias='pika')
+        baz: str
 
         class Config:
             validate_assignment = True
@@ -1170,12 +1171,27 @@ def test_field_that_is_being_validated_is_excluded_from_validator_values(mocker)
         @validator('foo')
         def validate_foo(cls, v, values):
             check_values({**values})
+            return v
+
+        @validator('bar')
+        def validate_bar(cls, v, values):
+            check_values({**values})
+            return v
 
-    model = Model(foo='foo_value', bar='bar_value')
+    model = Model(foo='foo_value', pika='bar_value', baz='baz_value')
     check_values.reset_mock()
 
+    assert list(dict(model).items()) == [('foo', 'foo_value'), ('bar', 'bar_value'), ('baz', 'baz_value')]
+
     model.foo = 'new_foo_value'
-    check_values.assert_called_once_with({'bar': 'bar_value'})
+    check_values.assert_called_once_with({'bar': 'bar_value', 'baz': 'baz_value'})
+    check_values.reset_mock()
+
+    model.bar = 'new_bar_value'
+    check_values.assert_called_once_with({'foo': 'new_foo_value', 'baz': 'baz_value'})
+
+    # ensure field order is the same
+    assert list(dict(model).items()) == [('foo', 'new_foo_value'), ('bar', 'new_bar_value'), ('baz', 'baz_value')]
 
 
 def test_exceptions_in_field_validators_restore_original_field_value():