mirror of
https://github.com/kennethreitz/pydantic.git
synced 2026-06-05 23:00:18 +00:00
Force fields.Undefined to be a singleton objectIn various places of the code, we compare directly to fields.Undefinedsince we assume it to be constant.When new models get created however, the object is deepcopied andis no longer identical with the original object.We therefore add __copy__ and __deepcopy__ methods to ensurethat the copied objects are actually the same original object. (#1981)
This commit is contained in:
@@ -0,0 +1 @@
|
||||
Force `fields.Undefined` to be a singleton object, fixing inherited generic model schemas
|
||||
@@ -40,11 +40,19 @@ from .validators import constant_validator, dict_validator, find_validators, val
|
||||
|
||||
Required: Any = Ellipsis
|
||||
|
||||
T = TypeVar('T')
|
||||
|
||||
|
||||
class UndefinedType:
|
||||
def __repr__(self) -> str:
|
||||
return 'PydanticUndefined'
|
||||
|
||||
def __copy__(self: T) -> T:
|
||||
return self
|
||||
|
||||
def __deepcopy__(self: T, _: Any) -> T:
|
||||
return self
|
||||
|
||||
|
||||
Undefined = UndefinedType()
|
||||
|
||||
|
||||
@@ -410,6 +410,26 @@ def test_custom_schema():
|
||||
assert schema['properties']['a'].get('description') == 'Custom'
|
||||
|
||||
|
||||
@skip_36
|
||||
def test_child_schema():
|
||||
|
||||
T = TypeVar('T')
|
||||
|
||||
class Model(GenericModel, Generic[T]):
|
||||
a: T
|
||||
|
||||
class Child(Model[T], Generic[T]):
|
||||
pass
|
||||
|
||||
schema = Child[int].schema()
|
||||
assert schema == {
|
||||
'title': 'Child[int]',
|
||||
'type': 'object',
|
||||
'properties': {'a': {'title': 'A', 'type': 'integer'}},
|
||||
'required': ['a'],
|
||||
}
|
||||
|
||||
|
||||
@skip_36
|
||||
def test_custom_generic_naming():
|
||||
T = TypeVar('T')
|
||||
|
||||
+6
-1
@@ -1,7 +1,7 @@
|
||||
import os
|
||||
import re
|
||||
import string
|
||||
from copy import deepcopy
|
||||
from copy import copy, deepcopy
|
||||
from distutils.version import StrictVersion
|
||||
from enum import Enum
|
||||
from typing import NewType, Union
|
||||
@@ -296,6 +296,11 @@ def test_undefined_repr():
|
||||
assert repr(Undefined) == 'PydanticUndefined'
|
||||
|
||||
|
||||
def test_undefined_copy():
|
||||
copy(Undefined) is Undefined
|
||||
deepcopy(Undefined) is Undefined
|
||||
|
||||
|
||||
def test_get_model():
|
||||
class A(BaseModel):
|
||||
a: str
|
||||
|
||||
Reference in New Issue
Block a user