Skip to content

Commit

Permalink
support self argument, fix #629
Browse files Browse the repository at this point in the history
  • Loading branch information
samuelcolvin committed Jul 1, 2019
1 parent 3cdbbae commit 9f6c4f1
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
1 change: 1 addition & 0 deletions HISTORY.rst
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ v0.30 (unreleased)
* clarify, that self-referencing models require python 3.7+, #616 by @vlcinsky
* fix truncate for types, #611 by @dmontagu
* fix schema generation with multiple/circular references to the same model, #621 by @tiangolo and @wongpat
* support ``self`` as a field name in ``parse_obj``, #631 by @samuelcolvin

v0.29 (2019-06-19)
..................
Expand Down
7 changes: 6 additions & 1 deletion pydantic/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,12 @@ def parse_obj(cls: Type['Model'], obj: Mapping[Any, Any]) -> 'Model':
except (TypeError, ValueError) as e:
exc = TypeError(f'{cls.__name__} expected dict not {type(obj).__name__}')
raise ValidationError([ErrorWrapper(exc, loc='__obj__')]) from e
return cls(**obj)

m = cls.__new__(cls)
values, fields_set, _ = validate_model(m, obj)
object.__setattr__(m, '__values__', values)
object.__setattr__(m, '__fields_set__', fields_set)
return m

@classmethod
def parse_raw(
Expand Down
15 changes: 15 additions & 0 deletions tests/test_edge_cases.py
Original file line number Diff line number Diff line change
Expand Up @@ -880,3 +880,18 @@ class Spam(BaseModel):
assert Spam(c=Foo(a='123')).dict() == {'c': {'a': 123}}
with pytest.raises(ValidationError):
Spam(c=Bar(b='123'))


def test_self():
class Model(BaseModel):
self: str

m = Model.parse_obj(dict(self='some value'))
assert m.dict() == {'self': 'some value'}
assert m.self == 'some value'
assert m.schema() == {
'title': 'Model',
'type': 'object',
'properties': {'self': {'title': 'Self', 'type': 'string'}},
'required': ['self'],
}

0 comments on commit 9f6c4f1

Please sign in to comment.