Skip to content

Commit

Permalink
allow removing items or sources from config
Browse files Browse the repository at this point in the history
  • Loading branch information
cloud-rocket committed May 14, 2021
1 parent f0485fa commit 681920b
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
26 changes: 26 additions & 0 deletions confuse/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,11 @@ def add(self, value):
"""
raise NotImplementedError

def remove(self, value):
"""Remove source or value from config
"""
raise NotImplementedError

def set(self, value):
"""*Override* the value for this configuration view. The
specified value is added as the highest-priority configuration
Expand Down Expand Up @@ -136,6 +141,11 @@ def __setitem__(self, key, value):
"""
self.set({key: value})

def __delitem__(self, key):
"""Remove value from config by key.
"""
self.remove(key)

def __contains__(self, key):
return self[key].exists()

Expand Down Expand Up @@ -439,6 +449,22 @@ def __init__(self, sources):
def add(self, obj):
self.sources.append(ConfigSource.of(obj))

def remove(self, obj):
"""Remove source or item from configuration
"""
if isinstance(obj, ConfigSource):
if obj.default:
raise ConfigError(u'Cannot remove default source')
self.sources.remove(obj)
elif isinstance(obj, util.STRING):
for source in self.sources:
if isinstance(source, ConfigSource) and obj in source:
del source[obj]
else:
raise ConfigError(u'Unrecognized obj {0}'.format(
obj
))

def set(self, value):
self.sources.insert(0, ConfigSource.of(value))

Expand Down
17 changes: 17 additions & 0 deletions test/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,23 @@ def test_override_list_index(self):
self.assertEqual(config['foo'][1].get(), 'bar')


class DeleteTest(unittest.TestCase):

def test_remove(self):
config = _root({'foo': 'bar', 'qux': 'baz'})
config.remove('foo')
with self.assertRaises(confuse.NotFoundError):
config['foo'].get()
self.assertEqual(set(config.keys()), set(['qux']))

def test_del(self):
config = _root({'foo': 'bar', 'qux': 'baz'})
del config['foo']
with self.assertRaises(confuse.NotFoundError):
config['foo'].get()
self.assertEqual(set(config.keys()), set(['qux']))


class BuildNamespaceDictTests(unittest.TestCase):
def test_pure_dicts(self):
config = {'foo': {'bar': 1}}
Expand Down

0 comments on commit 681920b

Please sign in to comment.