Created
June 27, 2020 23:55
-
-
Save JakeTheCorn/0641fc3460b3de75a7836f2f153c6913 to your computer and use it in GitHub Desktop.
util for seeing if dictionary has path
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
def dict_has_path(d, path): | |
if not isinstance(d, dict): | |
return None, 'dict_has_path expected type dict for d parameter. called with %s' % d.__class__.__name__ | |
if not isinstance(path, str): | |
return None, 'dict_has_path expected type str for path parameter. called with %s' % path.__class__.__name__ | |
if path in d: | |
return True, None | |
if '.' not in path: | |
return False, None | |
sub_paths = path.split('.') | |
first, rest = sub_paths[0], sub_paths[1:] | |
if first not in path: | |
return False, None | |
next_val = d.get(first) | |
if not isinstance(next_val, dict): | |
return False, None | |
return dict_has_path(next_val, '.'.join(rest)) | |
class DictHasPathTestsTest(unittest.TestCase): | |
def test_called_with_non_dict_error(self): | |
has_path, err = dict_has_path(None, 'adsf') | |
self.assertEqual(None, has_path) | |
self.assertRegexpMatches(err, r'expected type dict') | |
def test_called_with_non_string_path(self): | |
has_path, err = dict_has_path({}, None) | |
self.assertEqual(None, has_path) | |
self.assertRegexpMatches(err, r'expected type str') | |
def test_shallow_true(self): | |
has_path, err = dict_has_path({'age': 1}, 'age') | |
self.assertEqual(has_path, True) | |
self.assertEqual(err, None) | |
def test_shallow_false(self): | |
has_path, err = dict_has_path({'age': 1}, 'name') | |
self.assertEqual(has_path, False) | |
self.assertEqual(err, None) | |
def test_nested_true(self): | |
has_path, err = dict_has_path({'name': {'first': 'bo'}}, 'name.first') | |
self.assertEqual(has_path, True) | |
self.assertEqual(err, None) | |
def test_nested_false(self): | |
has_path, err = dict_has_path({'name': {'first': 'bo'}}, 'name.last') | |
self.assertEqual(has_path, False) | |
self.assertEqual(err, None) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment