Skip to content

Commit

Permalink
Returning parameter name is likely useless without the value
Browse files Browse the repository at this point in the history
  • Loading branch information
jace committed Aug 29, 2017
1 parent 556ce89 commit b754f84
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 7 deletions.
13 changes: 8 additions & 5 deletions coaster/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -578,7 +578,7 @@ def nullstr(value):
nullunicode = nullstr # XXX: Deprecated name. Remove soon.


def require_one_of(_which=False, **kwargs):
def require_one_of(_return=False, **kwargs):
"""
Validator that raises :exc:`TypeError` unless one and only one parameter is
not ``None``. Use this inside functions that take multiple parameters, but
Expand All @@ -595,9 +595,11 @@ def my_func(this=None, that=None, other=None):
# Carry on with function logic
pass
:param _which: Return the name of the parameter which was passed in
:param _return: Return the matching parameter
:param kwargs: Parameters, of which one and only one is mandatory
:raises TypeError: If the count of parameters that aren't ``None`` is not one
:return: If `_return`, matching parameter name and value
:rtype: tuple
:raises TypeError: If the count of parameters that aren't ``None`` is not 1
"""

# Two ways to count number of non-None parameters:
Expand All @@ -624,9 +626,10 @@ def my_func(this=None, that=None, other=None):
elif count != 1:
raise TypeError("Only one of these parameters is allowed: " + ', '.join(kwargs.keys()))

if _which:
if _return:
keys, values = zip(*[(k, 1 if v is not None else 0) for k, v in kwargs.items()])
return keys[values.index(1)]
k = keys[values.index(1)]
return k, kwargs[k]


def unicode_http_header(value):
Expand Down
4 changes: 2 additions & 2 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,5 +142,5 @@ def test_require_one_of(self):
with self.assertRaises(TypeError):
require_one_of(first='first', second='second', third='third')
# Ask for which was passed in
self.assertEqual(require_one_of(True, first='a', second=None), 'first')
self.assertEqual(require_one_of(True, first=None, second='b'), 'second')
self.assertEqual(require_one_of(True, first='a', second=None), ('first', 'a'))
self.assertEqual(require_one_of(True, first=None, second='b'), ('second', 'b'))

0 comments on commit b754f84

Please sign in to comment.