Skip to content

Instantly share code, notes, and snippets.

@shazow
Created May 23, 2010 21:56
Show Gist options
  • Save shazow/411284 to your computer and use it in GitHub Desktop.
Save shazow/411284 to your computer and use it in GitHub Desktop.
More concise handling of request parameters.
def get_many(d, required=[], optional=[], one_of=[]):
"""
Returns a predictable number of elements out of `d` in a list for auto-expanding.
Keys in `required` will raise KeyError if not found in `d`.
Keys in `optional` will return None if not found in `d`.
Keys in `one_of` will raise KeyError if none exist, otherwise return the first in `d`.
Example usage:
uid, action, limit, offset = get_many(request.params, required=['uid', 'action'], optional=['limit', 'offset'])
"""
d = d or {}
r = [d[k] for k in required]
r += [d.get(k)for k in optional]
if one_of:
for k in (k for k in one_of if k in d):
return r + [d[k]]
raise KeyError("Missing a one_of value.")
return r
# Unit tests for get_many
def test_get_many(self):
params = dict((n,n) for n in range(5)) # Dict with keys and values of 0, 1, 2, 3, 4
self.assertEqual(get_many(params), [])
self.assertEqual(get_many(params, required=[1, 2]), [1, 2])
self.assertEqual(get_many(params, optional=[1, 2]), [1, 2])
self.assertEqual(get_many(params, optional=[6, 7, 8]), [None, None, None])
self.assertEqual(get_many(params, one_of=[1, 2]), [1])
self.assertEqual(get_many(params, one_of=[6, 1]), [1])
self.assertEqual(get_many(params, optional=[6, 1]), [None, 1])
self.assertEqual(get_many(params, required=[1, 2], optional=[6, 1]), [1, 2, None, 1])
self.assertEqual(get_many(params, required=[1, 2], optional=[6, 1], one_of=[7, 8, 3]), [1, 2, None, 1, 3])
self.assertRaises(KeyError, get_many, params, required=[1, 6])
self.assertRaises(KeyError, get_many, params, one_of=[7, 6])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment