|
50 | 50 | ComponentUID, |
51 | 51 | Any, |
52 | 52 | ) |
| 53 | +from pyomo.common.collections import ComponentSet |
53 | 54 | from pyomo.common.log import LoggingIntercept |
54 | 55 | from pyomo.common.tempfiles import TempfileManager |
55 | 56 | from pyomo.core.base.block import ( |
@@ -1345,6 +1346,37 @@ def test_add_del_component(self): |
1345 | 1346 | self.assertFalse('x' in m.__dict__) |
1346 | 1347 | self.assertIs(m.component('x'), None) |
1347 | 1348 |
|
| 1349 | + def test_del_component_data(self): |
| 1350 | + m = ConcreteModel() |
| 1351 | + self.assertFalse(m.contains_component(Var)) |
| 1352 | + x = m.x = Var([1, 2, 3]) |
| 1353 | + self.assertTrue(m.contains_component(Var)) |
| 1354 | + self.assertIs(m.component('x'), x) |
| 1355 | + del m.x[1] |
| 1356 | + self.assertTrue(m.contains_component(Var)) |
| 1357 | + self.assertTrue('x' in m.__dict__) |
| 1358 | + self.assertEqual(len(m.x), 2) |
| 1359 | + self.assertIn(m.x[2], ComponentSet(m.x.values())) |
| 1360 | + self.assertIn(m.x[3], ComponentSet(m.x.values())) |
| 1361 | + |
| 1362 | + # This fails: |
| 1363 | + with self.assertRaisesRegex( |
| 1364 | + ValueError, |
| 1365 | + r"Argument 'x\[2\]' to del_component is a ComponentData object. " |
| 1366 | + r"Please use the Python 'del' function to delete members of " |
| 1367 | + r"indexed Pyomo components. The del_component function can " |
| 1368 | + r"only be used to delete IndexedComponents and " |
| 1369 | + r"ScalarComponents.", |
| 1370 | + ): |
| 1371 | + m.del_component(m.x[2]) |
| 1372 | + |
| 1373 | + # But we can use del |
| 1374 | + del m.x[2] |
| 1375 | + self.assertTrue(m.contains_component(Var)) |
| 1376 | + self.assertTrue('x' in m.__dict__) |
| 1377 | + self.assertEqual(len(m.x), 1) |
| 1378 | + self.assertIn(m.x[3], ComponentSet(m.x.values())) |
| 1379 | + |
1348 | 1380 | def test_reclassify_component(self): |
1349 | 1381 | m = Block() |
1350 | 1382 | m.a = Var() |
|
0 commit comments