[Python-checkins] bpo-27639: Correct return type for UserList slicing operation (#13169)
Mark Shannon
webhook-mailer at python.org
Tue May 7 17:41:09 EDT 2019
https://github.com/python/cpython/commit/b1c3167c232c36ed3543ca351ff10c613639b5f5
commit: b1c3167c232c36ed3543ca351ff10c613639b5f5
branch: master
author: Michael Blahay <mblahay at users.noreply.github.com>
committer: Mark Shannon <mark at hotpy.org>
date: 2019-05-07T17:41:06-04:00
summary:
bpo-27639: Correct return type for UserList slicing operation (#13169)
* BPO-27639: Correct return type for UserList slicing operation
Added logic to __getitem__ magic method for UserList to ensure that the return
type matches that of self.
files:
A Misc/NEWS.d/next/Core and Builtins/2019-05-07-15-49-17.bpo-27639.b1Ah87.rst
M Lib/collections/__init__.py
M Lib/test/test_userlist.py
diff --git a/Lib/collections/__init__.py b/Lib/collections/__init__.py
index e6cafb320fab..706907ad4a28 100644
--- a/Lib/collections/__init__.py
+++ b/Lib/collections/__init__.py
@@ -1085,7 +1085,11 @@ def __cast(self, other):
return other.data if isinstance(other, UserList) else other
def __contains__(self, item): return item in self.data
def __len__(self): return len(self.data)
- def __getitem__(self, i): return self.data[i]
+ def __getitem__(self, i):
+ if isinstance(i, slice):
+ return self.__class__(self.data[i])
+ else:
+ return self.data[i]
def __setitem__(self, i, item): self.data[i] = item
def __delitem__(self, i): del self.data[i]
def __add__(self, other):
diff --git a/Lib/test/test_userlist.py b/Lib/test/test_userlist.py
index 8de6c14e392f..1ed67dac8059 100644
--- a/Lib/test/test_userlist.py
+++ b/Lib/test/test_userlist.py
@@ -17,6 +17,12 @@ def test_getslice(self):
for j in range(-3, 6):
self.assertEqual(u[i:j], l[i:j])
+ def test_slice_type(self):
+ l = [0, 1, 2, 3, 4]
+ u = UserList(l)
+ self.assertIsInstance(u[:], u.__class__)
+ self.assertEqual(u[:],u)
+
def test_add_specials(self):
u = UserList("spam")
u2 = u + "eggs"
diff --git a/Misc/NEWS.d/next/Core and Builtins/2019-05-07-15-49-17.bpo-27639.b1Ah87.rst b/Misc/NEWS.d/next/Core and Builtins/2019-05-07-15-49-17.bpo-27639.b1Ah87.rst
new file mode 100644
index 000000000000..ae5b915969d3
--- /dev/null
+++ b/Misc/NEWS.d/next/Core and Builtins/2019-05-07-15-49-17.bpo-27639.b1Ah87.rst
@@ -0,0 +1,2 @@
+Correct return type for UserList slicing operations. Patch by Michael Blahay,
+Erick Cervantes, and vaultah
More information about the Python-checkins
mailing list