Skip to content

Commit 6d28b9d

Browse files
author
python-desert
authored
Add support for attrs factories taking self.
2 parents 847edb5 + 6ce75ce commit 6d28b9d

File tree

4 files changed

+34
-4
lines changed

4 files changed

+34
-4
lines changed

CHANGELOG.rst

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,17 @@
1+
2020.01.05 (2020-01-05)
2+
-----------------------
3+
4+
5+
Changes
6+
^^^^^^^
7+
8+
- Add support for attrs factories that take ``self`` (``attr.Factory(..., takes_self=True)``).
9+
`#27 <https://github.com/python-desert/desert/issues/27>`_
10+
11+
12+
----
13+
14+
115
2020.01.04 (2020-01-04)
216
-----------------------
317

src/desert/_make.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -319,16 +319,16 @@ def _get_field_default(field: t.Union[dataclasses.Field, attr.Attribute]):
319319
"""
320320
if isinstance(field, dataclasses.Field):
321321
if field.default_factory != dataclasses.MISSING:
322-
return field.default_factory
323-
elif field.default is dataclasses.MISSING:
322+
return dataclasses.MISSING
323+
if field.default is dataclasses.MISSING:
324324
return marshmallow.missing
325325
return field.default
326326
elif isinstance(field, attr.Attribute):
327327
if field.default == attr.NOTHING:
328328
return marshmallow.missing
329329
if isinstance(field.default, attr.Factory):
330330
if field.default.takes_self:
331-
raise NotImplementedError("Takes self not implemented")
331+
return attr.NOTHING
332332
return field.default.factory
333333
return field.default
334334
else:

src/desert/_version.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
__version__ = "2020.01.04"
1+
__version__ = "2020.01.05"

tests/test_make.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -414,3 +414,19 @@ def test_only_raises():
414414

415415
with pytest.raises(ValueError):
416416
desert._make.only([1, 2])
417+
418+
419+
def test_takes_self():
420+
"""Attrs default factories are constructed after instance creation."""
421+
422+
@attr.s
423+
class C:
424+
x: int = attr.ib()
425+
y: int = attr.ib()
426+
427+
@y.default
428+
def _(self):
429+
return self.x + 1
430+
431+
schema = desert.schema(C)
432+
assert schema.load({"x": 1}) == C(x=1, y=2)

0 commit comments

Comments
 (0)