-
-
Notifications
You must be signed in to change notification settings - Fork 382
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
This just adds a function that makes an existing converter work for optional inputs.
- Loading branch information
1 parent
a48124b
commit 82fe20c
Showing
4 changed files
with
64 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
""" | ||
Commonly useful converters. | ||
""" | ||
|
||
from __future__ import absolute_import, division, print_function | ||
|
||
|
||
def optional(converter): | ||
""" | ||
A converter that allows an attribute to be optional. An optional attribute | ||
is one which can be set to ``None``. | ||
:param converter: the converter that is used for non-``None`` values. | ||
.. versionadded:: 17.1.0 *convert* can be optional | ||
""" | ||
|
||
def optional_converter(val): | ||
if val is None: | ||
return None | ||
return converter(val) | ||
|
||
return optional_converter |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
""" | ||
Tests for `attr.converters`. | ||
""" | ||
|
||
from __future__ import absolute_import | ||
|
||
import pytest | ||
|
||
from attr.converters import optional | ||
|
||
|
||
class TestOptional(object): | ||
""" | ||
Tests for `optional`. | ||
""" | ||
|
||
def test_success_with_type(self): | ||
""" | ||
Nothing happens if types match. | ||
""" | ||
c = optional(int) | ||
assert c('42') == 42 | ||
|
||
def test_success_with_none(self): | ||
""" | ||
Nothing happens if None. | ||
""" | ||
c = optional(int) | ||
assert c(None) is None | ||
|
||
def test_fail(self): | ||
""" | ||
Propagates the underlying conversion error when conversion fails. | ||
""" | ||
c = optional(int) | ||
with pytest.raises(ValueError): | ||
c("not_an_int") |