Skip to content

Commit

Permalink
ConfigDict: defining __delattr__()
Browse files Browse the repository at this point in the history
This partially fixed #352
  • Loading branch information
jsiirola committed Apr 8, 2021
1 parent e99ecde commit f3a7fe2
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
11 changes: 11 additions & 0 deletions pyomo/common/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -1829,6 +1829,17 @@ def __setattr__(self, name, value):
else:
ConfigDict.__setitem__(self, name, value)

def __delattr__(self, name):
_key = str(name).replace(' ','_')
if _key in self._data:
del self[_key]
elif _key in dir(self):
raise AttributeError("'%s' object attribute '%s' is read-only" %
(type(self).__name__, name))
else:
raise AttributeError("'%s' object has no attribute '%s'" %
(type(self).__name__, name))

def keys(self):
return iter(self)

Expand Down
30 changes: 30 additions & 0 deletions pyomo/common/tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -1334,11 +1334,41 @@ def test_delitem(self):
self.assertEqual(sorted(config.keys()), ['bar'])
config.foo = 5
self.assertEqual(sorted(config.keys()), ['bar', 'foo'])
self.assertEqual(sorted(config._declared), ['bar'])
del config['foo']
self.assertEqual(sorted(config.keys()), ['bar'])
self.assertEqual(sorted(config._declared), ['bar'])
del config['bar']
self.assertEqual(sorted(config.keys()), [])
self.assertEqual(sorted(config._declared), [])

with self.assertRaisesRegex(KeyError, "'get'"):
del config['get']
with self.assertRaisesRegex(KeyError, "'foo'"):
del config['foo']

def test_delattr(self):
config = ConfigDict(implicit=True)
config.declare('bar', ConfigValue())
self.assertEqual(sorted(config.keys()), ['bar'])
config.foo = 5
self.assertEqual(sorted(config.keys()), ['bar', 'foo'])
self.assertEqual(sorted(config._declared), ['bar'])
del config.foo
self.assertEqual(sorted(config._declared), ['bar'])
self.assertEqual(sorted(config.keys()), ['bar'])
del config.bar
self.assertEqual(sorted(config.keys()), [])
self.assertEqual(sorted(config._declared), [])

with self.assertRaisesRegex(
AttributeError,
"'ConfigDict' object attribute 'get' is read-only"):
del config.get
with self.assertRaisesRegex(
AttributeError,
"'ConfigDict' object has no attribute 'foo'"):
del config.foo

def test_generate_custom_documentation(self):
reference = \
Expand Down

0 comments on commit f3a7fe2

Please sign in to comment.