Skip to content

Instantly share code, notes, and snippets.

@JakeTheCorn
Last active February 7, 2021 15:02
Show Gist options
  • Save JakeTheCorn/cebe16688eb972cc3d75a6ec65790576 to your computer and use it in GitHub Desktop.
Save JakeTheCorn/cebe16688eb972cc3d75a6ec65790576 to your computer and use it in GitHub Desktop.
lil' python omit util
# todo: write non-recursive form
import unittest
import copy
from typing import Union, List
def omit(v: dict, paths: List[str]) -> (Union[dict, None], Union[str, None]):
if not isinstance(v, dict):
msg = 'omit expected dict type, received %s' % v.__class__.__name__
return None, msg
collector = copy.deepcopy(v)
for path in paths:
if '.' not in path:
if path not in collector:
err_msg = 'omit path not found path=%s' % path
return None, err_msg
del collector[path]
continue
sub_paths = path.split('.')
if len(sub_paths) < 2:
continue
first, rest = sub_paths[0], sub_paths[1:]
if first not in collector:
err_msg = first + ' not found'
return None, err_msg
val, err = omit(collector[first], rest)
if err:
return None, err
collector[first] = val
return collector, None
class TestOmit(unittest.TestCase):
def test_simple(self):
result, _err = omit({'a': 1, 'b': 2}, ['a'])
self.assertEqual(result, {'b': 2})
def test_nested(self):
result, _err = omit({'a': {'1a1': 1, '1a2': 2}, 'b': 2}, ['a.1a2'])
self.assertEqual(result, {'a': {'1a1': 1}, 'b': 2})
def test_non_dict_error(self):
_res, err = omit(1, ['b'])
self.assertRegex(err, r'dict type')
def test_top_level_not_found_error(self):
_res, err = omit({'a': True}, ['b'])
self.assertRegex(err, r'path not found')
def test_nested_path_not_found_error(self):
_res, err = omit({'a': {'a1': False}}, ['a.a2'])
self.assertRegex(err, r'path not found')
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment