Made Page class inherit collections.Sequence

This commit is contained in:
Claude Paroz 2012-11-08 16:13:23 +01:00
parent 45802e1248
commit 9942adac17
1 changed files with 2 additions and 31 deletions

View File

@ -1,3 +1,4 @@
import collections
from math import ceil from math import ceil
class InvalidPage(Exception): class InvalidPage(Exception):
@ -75,7 +76,7 @@ class Paginator(object):
QuerySetPaginator = Paginator # For backwards-compatibility. QuerySetPaginator = Paginator # For backwards-compatibility.
class Page(object): class Page(collections.Sequence):
def __init__(self, object_list, number, paginator): def __init__(self, object_list, number, paginator):
self.object_list = object_list self.object_list = object_list
self.number = number self.number = number
@ -92,36 +93,6 @@ class Page(object):
# it won't be a database hit per __getitem__. # it won't be a database hit per __getitem__.
return list(self.object_list)[index] return list(self.object_list)[index]
# The following four methods are only necessary for Python <2.6
# compatibility (this class could just extend 2.6's collections.Sequence).
def __iter__(self):
i = 0
try:
while True:
v = self[i]
yield v
i += 1
except IndexError:
return
def __contains__(self, value):
for v in self:
if v == value:
return True
return False
def index(self, value):
for i, v in enumerate(self):
if v == value:
return i
raise ValueError
def count(self, value):
return sum([1 for v in self if v == value])
# End of compatibility methods.
def has_next(self): def has_next(self):
return self.number < self.paginator.num_pages return self.number < self.paginator.num_pages