Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add syntactic sugar for attr.ib(default=attr.Factory) #356

Merged
merged 6 commits into from
Mar 14, 2018
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions docs/examples.rst
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,16 @@ The method receives the partially initialized instance which enables you to base
C(x=1, y=2)


And since the case of ``attr.ib(default=attr.Factory(f))`` is so common, ``attrs`` also comes with syntactic sugar for that case:

.. doctest::

>>> @attr.s
... class C(object):
... x = attr.ib(factory=list)
>>> C()
C(x=[])

.. _examples_validators:

Validators
Expand Down
4 changes: 4 additions & 0 deletions src/attr/_make.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,10 @@ def attrib(default=NOTHING, validator=None,
"The `default` and `factory` arguments are mutually "
"exclusive."
)
if not callable(factory):
raise ValueError(
"The `factory` argument must be a callable."
)
default = Factory(factory)

This comment was marked as spam.


if metadata is None:
Expand Down
14 changes: 13 additions & 1 deletion tests/test_make.py
Original file line number Diff line number Diff line change
Expand Up @@ -535,7 +535,7 @@ class C(object):

assert Factory(list) == attr.fields(C).x.default

def test_factory_mutex(self):
def test_sugar_factory_mutex(self):
"""
Passing both default and factory raises ValueError.
"""
Expand All @@ -546,6 +546,18 @@ class C(object):

assert "mutually exclusive" in ei.value.args[0]

def test_sugar_callable(self):
"""
Factory has to be a callable to prevent people from passing Factory
into it.
"""
with pytest.raises(ValueError) as ei:

This comment was marked as spam.

This comment was marked as spam.

This comment was marked as spam.

@attr.s
class C(object):
x = attr.ib(factory=Factory(list))

assert "must be a callable" in ei.value.args[0]


@attr.s
class GC(object):
Expand Down