Bug 1052526 - Treat appending None to List as empty list; r=glandium

As a special exception, we change List's + and += operators to treat
"+ None" and "+= None" as "+ []" and "+= []" respectively.

This is a hack to make moz.build files simpler so they don't have to
perform "is x" checks before appending x.

While I was here, I fixed the implementation of List.__add__ to return a
List instead of list.

--HG--
extra : rebase_source : e61db4be4cf8144b092609d3baf84c372b9cf9a0
extra : amend_source : dfabc00765582764426f7cf74e79354a0bfb0824
This commit is contained in:
Gregory Szorc 2014-08-12 09:23:33 -07:00
parent 07510ca060
commit 95bd91b3cd
2 changed files with 27 additions and 2 deletions

View File

@ -57,15 +57,36 @@ class TestList(unittest.TestCase):
test = List([1, 2, 3])
test += [4, 5, 6]
self.assertIsInstance(test, List)
self.assertEqual(test, [1, 2, 3, 4, 5, 6])
test = test + [7, 8]
self.assertIsInstance(test, List)
self.assertEqual(test, [1, 2, 3, 4, 5, 6, 7, 8])
def test_add_string(self):
test = List([1, 2, 3])
with self.assertRaises(ValueError):
test += 'string'
def test_none(self):
"""As a special exception, we allow None to be treated as an empty
list."""
test = List([1, 2, 3])
test += None
self.assertEqual(test, [1, 2, 3])
test = test + None
self.assertIsInstance(test, List)
self.assertEqual(test, [1, 2, 3])
with self.assertRaises(ValueError):
test += False
with self.assertRaises(ValueError):
test = test + False
if __name__ == '__main__':
main()

View File

@ -249,12 +249,16 @@ class List(list):
return list.__setslice__(self, i, j, sequence)
def __add__(self, other):
# Allow None is a special case because it makes undefined variable
# references in moz.build behave better.
other = [] if other is None else other
if not isinstance(other, list):
raise ValueError('Only lists can be appended to lists.')
return list.__add__(self, other)
return List(list.__add__(self, other))
def __iadd__(self, other):
other = [] if other is None else other
if not isinstance(other, list):
raise ValueError('Only lists can be appended to lists.')