Skip to content

Commit b1c3167

Browse files
mblahaymarkshannon
authored andcommitted
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.
1 parent ca87eeb commit b1c3167

File tree

3 files changed

+13
-1
lines changed

3 files changed

+13
-1
lines changed

Lib/collections/__init__.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1085,7 +1085,11 @@ def __cast(self, other):
10851085
return other.data if isinstance(other, UserList) else other
10861086
def __contains__(self, item): return item in self.data
10871087
def __len__(self): return len(self.data)
1088-
def __getitem__(self, i): return self.data[i]
1088+
def __getitem__(self, i):
1089+
if isinstance(i, slice):
1090+
return self.__class__(self.data[i])
1091+
else:
1092+
return self.data[i]
10891093
def __setitem__(self, i, item): self.data[i] = item
10901094
def __delitem__(self, i): del self.data[i]
10911095
def __add__(self, other):

Lib/test/test_userlist.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,12 @@ def test_getslice(self):
1717
for j in range(-3, 6):
1818
self.assertEqual(u[i:j], l[i:j])
1919

20+
def test_slice_type(self):
21+
l = [0, 1, 2, 3, 4]
22+
u = UserList(l)
23+
self.assertIsInstance(u[:], u.__class__)
24+
self.assertEqual(u[:],u)
25+
2026
def test_add_specials(self):
2127
u = UserList("spam")
2228
u2 = u + "eggs"
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Correct return type for UserList slicing operations. Patch by Michael Blahay,
2+
Erick Cervantes, and vaultah

0 commit comments

Comments
 (0)