Merged revisions 55007-55179 via svnmerge from

svn+ssh://pythondev@svn.python.org/python/branches/p3yk

........
  r55077 | guido.van.rossum | 2007-05-02 11:54:37 -0700 (Wed, 02 May 2007) | 2 lines

  Use the new print syntax, at least.
........
  r55142 | fred.drake | 2007-05-04 21:27:30 -0700 (Fri, 04 May 2007) | 1 line

  remove old cruftiness
........
  r55143 | fred.drake | 2007-05-04 21:52:16 -0700 (Fri, 04 May 2007) | 1 line

  make this work with the new Python
........
  r55162 | neal.norwitz | 2007-05-06 22:29:18 -0700 (Sun, 06 May 2007) | 1 line

  Get asdl code gen working with Python 2.3.  Should continue to work with 3.0
........
  r55164 | neal.norwitz | 2007-05-07 00:00:38 -0700 (Mon, 07 May 2007) | 1 line

  Verify checkins to p3yk (sic) branch go to 3000 list.
........
  r55166 | neal.norwitz | 2007-05-07 00:12:35 -0700 (Mon, 07 May 2007) | 1 line

  Fix this test so it runs again by importing warnings_test properly.
........
  r55167 | neal.norwitz | 2007-05-07 01:03:22 -0700 (Mon, 07 May 2007) | 8 lines

  So long xrange.  range() now supports values that are outside
  -sys.maxint to sys.maxint.  floats raise a TypeError.

  This has been sitting for a long time.  It probably has some problems and
  needs cleanup.  Objects/rangeobject.c now uses 4-space indents since
  it is almost completely new.
........
  r55171 | guido.van.rossum | 2007-05-07 10:21:26 -0700 (Mon, 07 May 2007) | 4 lines

  Fix two tests that were previously depending on significant spaces
  at the end of a line (and before that on Python 2.x print behavior
  that has no exact equivalent in 3.0).
........
This commit is contained in:
Guido van Rossum 2007-05-07 22:24:25 +00:00
parent 598d98a7e8
commit 805365ee39
150 changed files with 1412 additions and 1320 deletions

View file

@ -18,8 +18,8 @@ class MyGrid(tk.Grid):
g = MyGrid(r, name="a_grid", g = MyGrid(r, name="a_grid",
selectunit="cell") selectunit="cell")
g.pack(fill=tk.BOTH) g.pack(fill=tk.BOTH)
for x in xrange(5): for x in range(5):
for y in xrange(5): for y in range(5):
g.set(x,y,text=str((x,y))) g.set(x,y,text=str((x,y)))
c = tk.Button(r, text="Close", command=r.destroy) c = tk.Button(r, text="Close", command=r.destroy)

View file

@ -72,7 +72,7 @@ methods are available in addition to the standard methods.
\begin{verbatim} \begin{verbatim}
print db.first() print db.first()
for i in xrange(1, len(db)): for i in range(1, len(db)):
print db.next() print db.next()
\end{verbatim} \end{verbatim}
\end{methoddesc} \end{methoddesc}

View file

@ -868,7 +868,7 @@ class Parrot(object):
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{range}{\optional{start,} stop\optional{, step}} \begin{funcdesc}{range}{\optional{start,} stop\optional{, step}}
This is a versatile function to create lists containing arithmetic This is a versatile function to create sequences containing arithmetic
progressions. It is most often used in \keyword{for} loops. The progressions. It is most often used in \keyword{for} loops. The
arguments must be plain integers. If the \var{step} argument is arguments must be plain integers. If the \var{step} argument is
omitted, it defaults to \code{1}. If the \var{start} argument is omitted, it defaults to \code{1}. If the \var{start} argument is
@ -882,19 +882,19 @@ class Parrot(object):
\exception{ValueError} is raised). Example: \exception{ValueError} is raised). Example:
\begin{verbatim} \begin{verbatim}
>>> range(10) >>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 11) >>> list(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(0, 30, 5) >>> list(range(0, 30, 5))
[0, 5, 10, 15, 20, 25] [0, 5, 10, 15, 20, 25]
>>> range(0, 10, 3) >>> list(range(0, 10, 3))
[0, 3, 6, 9] [0, 3, 6, 9]
>>> range(0, -10, -1) >>> list(range(0, -10, -1))
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9] [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> range(0) >>> list(range(0))
[] []
>>> range(1, 0) >>> list(range(1, 0))
[] []
\end{verbatim} \end{verbatim}
\end{funcdesc} \end{funcdesc}
@ -1230,24 +1230,6 @@ class C(B):
other scopes (such as modules) can be. This may change.} other scopes (such as modules) can be. This may change.}
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{xrange}{\optional{start,} stop\optional{, step}}
This function is very similar to \function{range()}, but returns an
``xrange object'' instead of a list. This is an opaque sequence
type which yields the same values as the corresponding list, without
actually storing them all simultaneously. The advantage of
\function{xrange()} over \function{range()} is minimal (since
\function{xrange()} still has to create the values when asked for
them) except when a very large range is used on a memory-starved
machine or when all of the range's elements are never used (such as
when the loop is usually terminated with \keyword{break}).
\note{\function{xrange()} is intended to be simple and fast.
Implementations may impose restrictions to achieve this.
The C implementation of Python restricts all arguments to
native C longs ("short" Python integers), and also requires
that the number of elements fit in a native C long.}
\end{funcdesc}
\begin{funcdesc}{zip}{\optional{iterable, \moreargs}} \begin{funcdesc}{zip}{\optional{iterable, \moreargs}}
This function returns a list of tuples, where the \var{i}-th tuple contains This function returns a list of tuples, where the \var{i}-th tuple contains
the \var{i}-th element from each of the argument sequences or iterables. the \var{i}-th element from each of the argument sequences or iterables.

View file

@ -161,7 +161,7 @@ by functions or loops that truncate the stream.
key = lambda x: x key = lambda x: x
self.keyfunc = key self.keyfunc = key
self.it = iter(iterable) self.it = iter(iterable)
self.tgtkey = self.currkey = self.currvalue = xrange(0) self.tgtkey = self.currkey = self.currvalue = []
def __iter__(self): def __iter__(self):
return self return self
def __next__(self): def __next__(self):
@ -252,7 +252,7 @@ by functions or loops that truncate the stream.
\begin{verbatim} \begin{verbatim}
def islice(iterable, *args): def islice(iterable, *args):
s = slice(*args) s = slice(*args)
it = iter(xrange(s.start or 0, s.stop or sys.maxint, s.step or 1)) it = iter(range(s.start or 0, s.stop or sys.maxint, s.step or 1))
nexti = next(it) nexti = next(it)
for i, element in enumerate(iterable): for i, element in enumerate(iterable):
if i == nexti: if i == nexti:
@ -342,7 +342,7 @@ by functions or loops that truncate the stream.
while True: while True:
yield object yield object
else: else:
for i in xrange(times): for i in range(times):
yield object yield object
\end{verbatim} \end{verbatim}
\end{funcdesc} \end{funcdesc}
@ -425,7 +425,7 @@ Check 1201 is for $764.05
Check 1202 is for $823.14 Check 1202 is for $823.14
>>> import operator >>> import operator
>>> for cube in imap(operator.pow, xrange(1,5), repeat(3)): >>> for cube in imap(operator.pow, range(1,5), repeat(3)):
... print cube ... print cube
... ...
1 1

View file

@ -163,9 +163,9 @@ Functions for sequences:
population contains repeats, then each occurrence is a possible population contains repeats, then each occurrence is a possible
selection in the sample. selection in the sample.
To choose a sample from a range of integers, use an \function{xrange()} To choose a sample from a range of integers, use an \function{range()}
object as an argument. This is especially fast and space efficient for object as an argument. This is especially fast and space efficient for
sampling from a large population: \code{sample(xrange(10000000), 60)}. sampling from a large population: \code{sample(range(10000000), 60)}.
\end{funcdesc} \end{funcdesc}

View file

@ -403,11 +403,11 @@ methods.
\section{Sequence Types --- \section{Sequence Types ---
\class{str}, \class{unicode}, \class{list}, \class{str}, \class{unicode}, \class{list},
\class{tuple}, \class{buffer}, \class{xrange} \class{tuple}, \class{buffer}, \class{range}
\label{typesseq}} \label{typesseq}}
There are six sequence types: strings, Unicode strings, lists, There are six sequence types: strings, Unicode strings, lists,
tuples, buffers, and xrange objects. tuples, buffers, and range objects.
String literals are written in single or double quotes: String literals are written in single or double quotes:
\code{'xyzzy'}, \code{"frobozz"}. See chapter 2 of the \code{'xyzzy'}, \code{"frobozz"}. See chapter 2 of the
@ -433,11 +433,11 @@ concatenation or repetition.
\obindex{buffer} \obindex{buffer}
Xrange objects are similar to buffers in that there is no specific Xrange objects are similar to buffers in that there is no specific
syntax to create them, but they are created using the \function{xrange()} syntax to create them, but they are created using the \function{range()}
function.\bifuncindex{xrange} They don't support slicing, function.\bifuncindex{range} They don't support slicing,
concatenation or repetition, and using \code{in}, \code{not in}, concatenation or repetition, and using \code{in}, \code{not in},
\function{min()} or \function{max()} on them is inefficient. \function{min()} or \function{max()} on them is inefficient.
\obindex{xrange} \obindex{range}
Most sequence types support the following operations. The \samp{in} and Most sequence types support the following operations. The \samp{in} and
\samp{not in} operations have the same priorities as the comparison \samp{not in} operations have the same priorities as the comparison
@ -1069,11 +1069,11 @@ Additional string operations are defined in standard modules
\refmodule{re}.\refstmodindex{re} \refmodule{re}.\refstmodindex{re}
\subsection{XRange Type \label{typesseq-xrange}} \subsection{XRange Type \label{typesseq-range}}
The \class{xrange}\obindex{xrange} type is an immutable sequence which The \class{range}\obindex{range} type is an immutable sequence which
is commonly used for looping. The advantage of the \class{xrange} is commonly used for looping. The advantage of the \class{range}
type is that an \class{xrange} object will always take the same amount type is that an \class{range} object will always take the same amount
of memory, no matter the size of the range it represents. There are of memory, no matter the size of the range it represents. There are
no consistent performance advantages. no consistent performance advantages.

View file

@ -98,7 +98,7 @@ may be an important component of the performance of the function being
measured. If so, GC can be re-enabled as the first statement in the measured. If so, GC can be re-enabled as the first statement in the
\var{setup} string. For example: \var{setup} string. For example:
\begin{verbatim} \begin{verbatim}
timeit.Timer('for i in xrange(10): oct(i)', 'gc.enable()').timeit() timeit.Timer('for i in range(10): oct(i)', 'gc.enable()').timeit()
\end{verbatim} \end{verbatim}
\end{notice} \end{notice}
\end{methoddesc} \end{methoddesc}

View file

@ -147,9 +147,9 @@ The type of modules.
The type of open file objects such as \code{sys.stdout}. The type of open file objects such as \code{sys.stdout}.
\end{datadesc} \end{datadesc}
\begin{datadesc}{XRangeType} \begin{datadesc}{RangeType}
The type of range objects returned by The type of range objects returned by
\function{xrange()}\bifuncindex{xrange}. \function{range()}\bifuncindex{range}.
\end{datadesc} \end{datadesc}
\begin{datadesc}{SliceType} \begin{datadesc}{SliceType}

View file

@ -2260,7 +2260,7 @@ in a forward direction and then call the \function{reversed()}
function. function.
\begin{verbatim} \begin{verbatim}
>>> for i in reversed(xrange(1,10,2)): >>> for i in reversed(range(1,10,2)):
... print i ... print i
... ...
9 9
@ -2700,12 +2700,12 @@ standard module \module{__builtin__}\refbimodindex{__builtin__}:
'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod',
'enumerate', 'eval', 'exec', 'execfile', 'exit', 'file', 'filter', 'float', 'enumerate', 'eval', 'exec', 'execfile', 'exit', 'file', 'filter', 'float',
'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex',
'id', 'int', 'isinstance', 'issubclass', 'iter', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter',
'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'min', 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'min',
'object', 'oct', 'open', 'ord', 'pow', 'property', 'quit', 'range', 'object', 'oct', 'open', 'ord', 'pow', 'property', 'quit', 'range',
'reload', 'repr', 'reversed', 'round', 'set', 'reload', 'repr', 'reversed', 'round', 'set',
'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super',
'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip'] 'tuple', 'type', 'unichr', 'unicode', 'vars', 'zip']
\end{verbatim} \end{verbatim}
@ -4762,7 +4762,7 @@ module provides tools for making random selections:
>>> import random >>> import random
>>> random.choice(['apple', 'pear', 'banana']) >>> random.choice(['apple', 'pear', 'banana'])
'apple' 'apple'
>>> random.sample(xrange(100), 10) # sampling without replacement >>> random.sample(range(100), 10) # sampling without replacement
[30, 83, 16, 4, 8, 81, 41, 50, 18, 33] [30, 83, 16, 4, 8, 81, 41, 50, 18, 33]
>>> random.random() # random float >>> random.random() # random float
0.17970987693706186 0.17970987693706186

View file

@ -1,3 +0,0 @@
check:
../../python.exe ../../Tools/scripts/texcheck.py whatsnew25.tex

View file

@ -305,7 +305,7 @@ _Translator = {
'\375' : '\\375', '\376' : '\\376', '\377' : '\\377' '\375' : '\\375', '\376' : '\\376', '\377' : '\\377'
} }
_idmap = ''.join(chr(x) for x in xrange(256)) _idmap = ''.join(chr(x) for x in range(256))
def _quote(str, LegalChars=_LegalChars, idmap=_idmap): def _quote(str, LegalChars=_LegalChars, idmap=_idmap):
# #

View file

@ -229,7 +229,7 @@ class SimpleThreadedBase(BaseThreadedTestCase):
print("%s: creating records %d - %d" % (name, start, stop)) print("%s: creating records %d - %d" % (name, start, stop))
# create a bunch of records # create a bunch of records
for x in xrange(start, stop): for x in range(start, stop):
key = '%04d' % x key = '%04d' % x
dbutils.DeadlockWrap(d.put, key, self.makeData(key), dbutils.DeadlockWrap(d.put, key, self.makeData(key),
max_retries=12) max_retries=12)
@ -239,7 +239,7 @@ class SimpleThreadedBase(BaseThreadedTestCase):
# do a bit or reading too # do a bit or reading too
if random() <= 0.05: if random() <= 0.05:
for y in xrange(start, x): for y in range(start, x):
key = '%04d' % x key = '%04d' % x
data = dbutils.DeadlockWrap(d.get, key, max_retries=12) data = dbutils.DeadlockWrap(d.get, key, max_retries=12)
self.assertEqual(data, self.makeData(key)) self.assertEqual(data, self.makeData(key))
@ -252,7 +252,7 @@ class SimpleThreadedBase(BaseThreadedTestCase):
print("could not complete sync()...") print("could not complete sync()...")
# read them back, deleting a few # read them back, deleting a few
for x in xrange(start, stop): for x in range(start, stop):
key = '%04d' % x key = '%04d' % x
data = dbutils.DeadlockWrap(d.get, key, max_retries=12) data = dbutils.DeadlockWrap(d.get, key, max_retries=12)
if verbose and x % 100 == 0: if verbose and x % 100 == 0:

View file

@ -45,7 +45,7 @@ mdays = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
class _localized_month: class _localized_month:
_months = [datetime.date(2001, i+1, 1).strftime for i in xrange(12)] _months = [datetime.date(2001, i+1, 1).strftime for i in range(12)]
_months.insert(0, lambda x: "") _months.insert(0, lambda x: "")
def __init__(self, format): def __init__(self, format):
@ -65,7 +65,7 @@ class _localized_month:
class _localized_day: class _localized_day:
# January 1, 2001, was a Monday. # January 1, 2001, was a Monday.
_days = [datetime.date(2001, 1, i+1).strftime for i in xrange(7)] _days = [datetime.date(2001, 1, i+1).strftime for i in range(7)]
def __init__(self, format): def __init__(self, format):
self.format = format self.format = format
@ -144,7 +144,7 @@ class Calendar(object):
Return a iterator for one week of weekday numbers starting with the Return a iterator for one week of weekday numbers starting with the
configured first one. configured first one.
""" """
for i in xrange(self.firstweekday, self.firstweekday + 7): for i in range(self.firstweekday, self.firstweekday + 7):
yield i%7 yield i%7
def itermonthdates(self, year, month): def itermonthdates(self, year, month):
@ -192,7 +192,7 @@ class Calendar(object):
Each row represents a week; week entries are datetime.date values. Each row represents a week; week entries are datetime.date values.
""" """
dates = list(self.itermonthdates(year, month)) dates = list(self.itermonthdates(year, month))
return [ dates[i:i+7] for i in xrange(0, len(dates), 7) ] return [ dates[i:i+7] for i in range(0, len(dates), 7) ]
def monthdays2calendar(self, year, month): def monthdays2calendar(self, year, month):
""" """
@ -202,7 +202,7 @@ class Calendar(object):
are zero. are zero.
""" """
days = list(self.itermonthdays2(year, month)) days = list(self.itermonthdays2(year, month))
return [ days[i:i+7] for i in xrange(0, len(days), 7) ] return [ days[i:i+7] for i in range(0, len(days), 7) ]
def monthdayscalendar(self, year, month): def monthdayscalendar(self, year, month):
""" """
@ -210,7 +210,7 @@ class Calendar(object):
Each row represents a week; days outside this month are zero. Each row represents a week; days outside this month are zero.
""" """
days = list(self.itermonthdays(year, month)) days = list(self.itermonthdays(year, month))
return [ days[i:i+7] for i in xrange(0, len(days), 7) ] return [ days[i:i+7] for i in range(0, len(days), 7) ]
def yeardatescalendar(self, year, width=3): def yeardatescalendar(self, year, width=3):
""" """
@ -221,9 +221,9 @@ class Calendar(object):
""" """
months = [ months = [
self.monthdatescalendar(year, i) self.monthdatescalendar(year, i)
for i in xrange(January, January+12) for i in range(January, January+12)
] ]
return [months[i:i+width] for i in xrange(0, len(months), width) ] return [months[i:i+width] for i in range(0, len(months), width) ]
def yeardays2calendar(self, year, width=3): def yeardays2calendar(self, year, width=3):
""" """
@ -234,9 +234,9 @@ class Calendar(object):
""" """
months = [ months = [
self.monthdays2calendar(year, i) self.monthdays2calendar(year, i)
for i in xrange(January, January+12) for i in range(January, January+12)
] ]
return [months[i:i+width] for i in xrange(0, len(months), width) ] return [months[i:i+width] for i in range(0, len(months), width) ]
def yeardayscalendar(self, year, width=3): def yeardayscalendar(self, year, width=3):
""" """
@ -246,9 +246,9 @@ class Calendar(object):
""" """
months = [ months = [
self.monthdayscalendar(year, i) self.monthdayscalendar(year, i)
for i in xrange(January, January+12) for i in range(January, January+12)
] ]
return [months[i:i+width] for i in xrange(0, len(months), width) ] return [months[i:i+width] for i in range(0, len(months), width) ]
class TextCalendar(Calendar): class TextCalendar(Calendar):
@ -341,7 +341,7 @@ class TextCalendar(Calendar):
header = self.formatweekheader(w) header = self.formatweekheader(w)
for (i, row) in enumerate(self.yeardays2calendar(theyear, m)): for (i, row) in enumerate(self.yeardays2calendar(theyear, m)):
# months in this row # months in this row
months = xrange(m*i+1, min(m*(i+1)+1, 13)) months = range(m*i+1, min(m*(i+1)+1, 13))
a('\n'*l) a('\n'*l)
names = (self.formatmonthname(theyear, k, colwidth, False) names = (self.formatmonthname(theyear, k, colwidth, False)
for k in months) for k in months)
@ -352,7 +352,7 @@ class TextCalendar(Calendar):
a('\n'*l) a('\n'*l)
# max number of weeks for this row # max number of weeks for this row
height = max(len(cal) for cal in row) height = max(len(cal) for cal in row)
for j in xrange(height): for j in range(height):
weeks = [] weeks = []
for cal in row: for cal in row:
if j >= len(cal): if j >= len(cal):
@ -444,9 +444,9 @@ class HTMLCalendar(Calendar):
a('<table border="0" cellpadding="0" cellspacing="0" class="year">') a('<table border="0" cellpadding="0" cellspacing="0" class="year">')
a('\n') a('\n')
a('<tr><th colspan="%d" class="year">%s</th></tr>' % (width, theyear)) a('<tr><th colspan="%d" class="year">%s</th></tr>' % (width, theyear))
for i in xrange(January, January+12, width): for i in range(January, January+12, width):
# months in this row # months in this row
months = xrange(i, min(i+width, 13)) months = range(i, min(i+width, 13))
a('<tr>') a('<tr>')
for m in months: for m in months:
a('<td>') a('<td>')

View file

@ -100,7 +100,7 @@ _copy_dispatch = d = {}
def _copy_immutable(x): def _copy_immutable(x):
return x return x
for t in (type(None), int, float, bool, str, tuple, for t in (type(None), int, float, bool, str, tuple,
frozenset, type, xrange, types.ClassType, frozenset, type, range, types.ClassType,
types.BuiltinFunctionType, types.BuiltinFunctionType,
types.FunctionType): types.FunctionType):
d[t] = _copy_immutable d[t] = _copy_immutable
@ -194,7 +194,7 @@ try:
except AttributeError: except AttributeError:
pass pass
d[type] = _deepcopy_atomic d[type] = _deepcopy_atomic
d[xrange] = _deepcopy_atomic d[range] = _deepcopy_atomic
d[types.ClassType] = _deepcopy_atomic d[types.ClassType] = _deepcopy_atomic
d[types.BuiltinFunctionType] = _deepcopy_atomic d[types.BuiltinFunctionType] = _deepcopy_atomic
d[types.FunctionType] = _deepcopy_atomic d[types.FunctionType] = _deepcopy_atomic

View file

@ -11,7 +11,7 @@ class ArrayTestCase(unittest.TestCase):
# create classes holding simple numeric types, and check # create classes holding simple numeric types, and check
# various properties. # various properties.
init = range(15, 25) init = list(range(15, 25))
for fmt in formats: for fmt in formats:
alen = len(init) alen = len(init)
@ -27,7 +27,7 @@ class ArrayTestCase(unittest.TestCase):
# change the items # change the items
from operator import setitem from operator import setitem
new_values = range(42, 42+alen) new_values = list(range(42, 42+alen))
[setitem(ia, n, new_values[n]) for n in range(alen)] [setitem(ia, n, new_values[n]) for n in range(alen)]
values = [ia[i] for i in range(len(init))] values = [ia[i] for i in range(len(init))]
self.failUnlessEqual(values, new_values) self.failUnlessEqual(values, new_values)

View file

@ -5,8 +5,8 @@ import _ctypes_test
class SlicesTestCase(unittest.TestCase): class SlicesTestCase(unittest.TestCase):
def test_getslice_cint(self): def test_getslice_cint(self):
a = (c_int * 100)(*xrange(1100, 1200)) a = (c_int * 100)(*range(1100, 1200))
b = range(1100, 1200) b = list(range(1100, 1200))
self.failUnlessEqual(a[0:2], b[0:2]) self.failUnlessEqual(a[0:2], b[0:2])
self.failUnlessEqual(len(a), len(b)) self.failUnlessEqual(len(a), len(b))
self.failUnlessEqual(a[5:7], b[5:7]) self.failUnlessEqual(a[5:7], b[5:7])
@ -14,14 +14,14 @@ class SlicesTestCase(unittest.TestCase):
self.failUnlessEqual(a[:], b[:]) self.failUnlessEqual(a[:], b[:])
a[0:5] = range(5, 10) a[0:5] = range(5, 10)
self.failUnlessEqual(a[0:5], range(5, 10)) self.failUnlessEqual(a[0:5], list(range(5, 10)))
def test_setslice_cint(self): def test_setslice_cint(self):
a = (c_int * 100)(*xrange(1100, 1200)) a = (c_int * 100)(*range(1100, 1200))
b = range(1100, 1200) b = list(range(1100, 1200))
a[32:47] = range(32, 47) a[32:47] = list(range(32, 47))
self.failUnlessEqual(a[32:47], range(32, 47)) self.failUnlessEqual(a[32:47], list(range(32, 47)))
from operator import setslice from operator import setslice
@ -50,7 +50,7 @@ class SlicesTestCase(unittest.TestCase):
dll.my_strdup.restype = POINTER(c_byte) dll.my_strdup.restype = POINTER(c_byte)
res = dll.my_strdup(s) res = dll.my_strdup(s)
self.failUnlessEqual(res[:len(s)], range(ord("a"), ord("z")+1)) self.failUnlessEqual(res[:len(s)], list(range(ord("a"), ord("z")+1)))
dll.my_free(res) dll.my_free(res)
def test_char_ptr_with_free(self): def test_char_ptr_with_free(self):
@ -111,7 +111,8 @@ class SlicesTestCase(unittest.TestCase):
else: else:
return return
res = dll.my_wcsdup(s) res = dll.my_wcsdup(s)
self.failUnlessEqual(res[:len(s)-1], range(ord("a"), ord("z")+1)) self.failUnlessEqual(res[:len(s)-1],
list(range(ord("a"), ord("z")+1)))
dll.my_free(res) dll.my_free(res)
################################################################ ################################################################

View file

@ -407,7 +407,7 @@ class SequenceMatcher:
# junk-free match ending with a[i-1] and b[j] # junk-free match ending with a[i-1] and b[j]
j2len = {} j2len = {}
nothing = [] nothing = []
for i in xrange(alo, ahi): for i in range(alo, ahi):
# look at all instances of a[i] in b; note that because # look at all instances of a[i] in b; note that because
# b2j has no junk keys, the loop is skipped if a[i] is junk # b2j has no junk keys, the loop is skipped if a[i] is junk
j2lenget = j2len.get j2lenget = j2len.get
@ -921,7 +921,7 @@ class Differ:
def _dump(self, tag, x, lo, hi): def _dump(self, tag, x, lo, hi):
"""Generate comparison results for a same-tagged range.""" """Generate comparison results for a same-tagged range."""
for i in xrange(lo, hi): for i in range(lo, hi):
yield '%s %s' % (tag, x[i]) yield '%s %s' % (tag, x[i])
def _plain_replace(self, a, alo, ahi, b, blo, bhi): def _plain_replace(self, a, alo, ahi, b, blo, bhi):
@ -967,10 +967,10 @@ class Differ:
# search for the pair that matches best without being identical # search for the pair that matches best without being identical
# (identical lines must be junk lines, & we don't want to synch up # (identical lines must be junk lines, & we don't want to synch up
# on junk -- unless we have to) # on junk -- unless we have to)
for j in xrange(blo, bhi): for j in range(blo, bhi):
bj = b[j] bj = b[j]
cruncher.set_seq2(bj) cruncher.set_seq2(bj)
for i in xrange(alo, ahi): for i in range(alo, ahi):
ai = a[i] ai = a[i]
if ai == bj: if ai == bj:
if eqi is None: if eqi is None:

View file

@ -517,7 +517,7 @@ class install (Command):
outputs = self.get_outputs() outputs = self.get_outputs()
if self.root: # strip any package prefix if self.root: # strip any package prefix
root_len = len(self.root) root_len = len(self.root)
for counter in xrange(len(outputs)): for counter in range(len(outputs)):
outputs[counter] = outputs[counter][root_len:] outputs[counter] = outputs[counter][root_len:]
self.execute(write_file, self.execute(write_file,
(self.record, outputs), (self.record, outputs),

View file

@ -2610,14 +2610,14 @@ __test__ = {"_TestClass": _TestClass,
"ellipsis": r""" "ellipsis": r"""
If the ellipsis flag is used, then '...' can be used to If the ellipsis flag is used, then '...' can be used to
elide substrings in the desired output: elide substrings in the desired output:
>>> print(range(1000)) #doctest: +ELLIPSIS >>> print(list(range(1000))) #doctest: +ELLIPSIS
[0, 1, 2, ..., 999] [0, 1, 2, ..., 999]
""", """,
"whitespace normalization": r""" "whitespace normalization": r"""
If the whitespace normalization flag is used, then If the whitespace normalization flag is used, then
differences in whitespace are ignored. differences in whitespace are ignored.
>>> print(range(30)) #doctest: +NORMALIZE_WHITESPACE >>> print(list(range(30))) #doctest: +NORMALIZE_WHITESPACE
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29] 27, 28, 29]

View file

@ -71,7 +71,7 @@ def commonprefix(m):
s1 = min(m) s1 = min(m)
s2 = max(m) s2 = max(m)
n = min(len(s1), len(s2)) n = min(len(s1), len(s2))
for i in xrange(n): for i in range(n):
if s1[i] != s2[i]: if s1[i] != s2[i]:
return s1[:i] return s1[:i]
return s1[:n] return s1[:n]

View file

@ -281,7 +281,7 @@ class GNUTranslations(NullTranslations):
raise IOError(0, 'Bad magic number', filename) raise IOError(0, 'Bad magic number', filename)
# Now put all messages from the .mo file buffer into the catalog # Now put all messages from the .mo file buffer into the catalog
# dictionary. # dictionary.
for i in xrange(0, msgcount): for i in range(0, msgcount):
mlen, moff = unpack(ii, buf[masteridx:masteridx+8]) mlen, moff = unpack(ii, buf[masteridx:masteridx+8])
mend = moff + mlen mend = moff + mlen
tlen, toff = unpack(ii, buf[transidx:transidx+8]) tlen, toff = unpack(ii, buf[transidx:transidx+8])

View file

@ -173,7 +173,7 @@ def heapify(x):
# or i < (n-1)/2. If n is even = 2*j, this is (2*j-1)/2 = j-1/2 so # or i < (n-1)/2. If n is even = 2*j, this is (2*j-1)/2 = j-1/2 so
# j-1 is the largest, which is n//2 - 1. If n is odd = 2*j+1, this is # j-1 is the largest, which is n//2 - 1. If n is odd = 2*j+1, this is
# (2*j+1-1)/2 = j so j-1 is the largest, and that's again n//2-1. # (2*j+1-1)/2 = j so j-1 is the largest, and that's again n//2-1.
for i in reversed(xrange(n//2)): for i in reversed(range(n//2)):
_siftup(x, i) _siftup(x, i)
def nlargest(n, iterable): def nlargest(n, iterable):

View file

@ -3,8 +3,8 @@
Implements the HMAC algorithm as described by RFC 2104. Implements the HMAC algorithm as described by RFC 2104.
""" """
trans_5C = "".join ([chr (x ^ 0x5C) for x in xrange(256)]) trans_5C = "".join ([chr (x ^ 0x5C) for x in range(256)])
trans_36 = "".join ([chr (x ^ 0x36) for x in xrange(256)]) trans_36 = "".join ([chr (x ^ 0x36) for x in range(256)])
# The size of the digests returned by HMAC depends on the underlying # The size of the digests returned by HMAC depends on the underlying
# hashing module used. Use digest_size from the instance of HMAC instead. # hashing module used. Use digest_size from the instance of HMAC instead.

View file

@ -117,7 +117,7 @@ class CodeContext:
lastindent = INFINITY lastindent = INFINITY
# For a line to be interesting, it must begin with a block opening # For a line to be interesting, it must begin with a block opening
# keyword, and have less indentation than lastindent. # keyword, and have less indentation than lastindent.
for linenum in xrange(new_topvisible, stopline-1, -1): for linenum in range(new_topvisible, stopline-1, -1):
indent, text, opener = self.get_line_info(linenum) indent, text, opener = self.get_line_info(linenum)
if indent < lastindent: if indent < lastindent:
lastindent = indent lastindent = indent

View file

@ -828,7 +828,7 @@ class IntSet:
def tolist(self): def tolist(self):
l = [] l = []
for lo, hi in self.pairs: for lo, hi in self.pairs:
m = range(lo, hi+1) m = list(range(lo, hi+1))
l = l + m l = l + m
return l return l

View file

@ -604,7 +604,7 @@ class Pickler:
write(APPEND) write(APPEND)
return return
r = xrange(self._BATCHSIZE) r = range(self._BATCHSIZE)
while items is not None: while items is not None:
tmp = [] tmp = []
for i in r: for i in r:
@ -652,7 +652,7 @@ class Pickler:
write(SETITEM) write(SETITEM)
return return
r = xrange(self._BATCHSIZE) r = range(self._BATCHSIZE)
while items is not None: while items is not None:
tmp = [] tmp = []
for i in r: for i in r:

View file

@ -814,11 +814,11 @@ def test():
try: try:
if hasattr(MacOS, 'SchedParams'): if hasattr(MacOS, 'SchedParams'):
appsw = MacOS.SchedParams(1, 0) appsw = MacOS.SchedParams(1, 0)
for i in xrange(20): for i in range(20):
bar.inc() bar.inc()
time.sleep(0.05) time.sleep(0.05)
bar.set(0,100) bar.set(0,100)
for i in xrange(100): for i in range(100):
bar.set(i) bar.set(i)
time.sleep(0.05) time.sleep(0.05)
if i % 10 == 0: if i % 10 == 0:

View file

@ -60,7 +60,7 @@ class AppleSingle(object):
raise Error, "Unknown AppleSingle version number 0x%8.8x" % (version,) raise Error, "Unknown AppleSingle version number 0x%8.8x" % (version,)
if nentry <= 0: if nentry <= 0:
raise Error, "AppleSingle file contains no forks" raise Error, "AppleSingle file contains no forks"
headers = [fileobj.read(AS_ENTRY_LENGTH) for i in xrange(nentry)] headers = [fileobj.read(AS_ENTRY_LENGTH) for i in range(nentry)]
self.forks = [] self.forks = []
for hdr in headers: for hdr in headers:
try: try:

View file

@ -174,7 +174,7 @@ def commonprefix(m):
s1 = min(m) s1 = min(m)
s2 = max(m) s2 = max(m)
n = min(len(s1), len(s2)) n = min(len(s1), len(s2))
for i in xrange(n): for i in range(n):
if s1[i] != s2[i]: if s1[i] != s2[i]:
return s1[:i] return s1[:i]
return s1[:n] return s1[:n]

View file

@ -79,7 +79,7 @@ class Popen3:
def _run_child(self, cmd): def _run_child(self, cmd):
if isinstance(cmd, basestring): if isinstance(cmd, basestring):
cmd = ['/bin/sh', '-c', cmd] cmd = ['/bin/sh', '-c', cmd]
for i in xrange(3, MAXFD): for i in range(3, MAXFD):
try: try:
os.close(i) os.close(i)
except OSError: except OSError:

View file

@ -1582,7 +1582,7 @@ class Helper:
'INTEGER': ('ref/integers', 'int range'), 'INTEGER': ('ref/integers', 'int range'),
'FLOAT': ('ref/floating', 'float math'), 'FLOAT': ('ref/floating', 'float math'),
'COMPLEX': ('ref/imaginary', 'complex cmath'), 'COMPLEX': ('ref/imaginary', 'complex cmath'),
'SEQUENCES': ('lib/typesseq', 'STRINGMETHODS FORMATTING xrange LISTS'), 'SEQUENCES': ('lib/typesseq', 'STRINGMETHODS FORMATTING range LISTS'),
'MAPPINGS': 'DICTIONARIES', 'MAPPINGS': 'DICTIONARIES',
'FUNCTIONS': ('lib/typesfunctions', 'def TYPES'), 'FUNCTIONS': ('lib/typesfunctions', 'def TYPES'),
'METHODS': ('lib/typesmethods', 'class def CLASSES TYPES'), 'METHODS': ('lib/typesmethods', 'class def CLASSES TYPES'),

View file

@ -256,7 +256,7 @@ class Random(_random.Random):
if random is None: if random is None:
random = self.random random = self.random
for i in reversed(xrange(1, len(x))): for i in reversed(range(1, len(x))):
# pick an element in x[:i+1] with which to exchange x[i] # pick an element in x[:i+1] with which to exchange x[i]
j = int(random() * (i+1)) j = int(random() * (i+1))
x[i], x[j] = x[j], x[i] x[i], x[j] = x[j], x[i]
@ -274,9 +274,9 @@ class Random(_random.Random):
population contains repeats, then each occurrence is a possible population contains repeats, then each occurrence is a possible
selection in the sample. selection in the sample.
To choose a sample in a range of integers, use xrange as an argument. To choose a sample in a range of integers, use range as an argument.
This is especially fast and space efficient for sampling from a This is especially fast and space efficient for sampling from a
large population: sample(xrange(10000000), 60) large population: sample(range(10000000), 60)
""" """
# XXX Although the documentation says `population` is "a sequence", # XXX Although the documentation says `population` is "a sequence",
@ -311,7 +311,7 @@ class Random(_random.Random):
# An n-length list is smaller than a k-length set, or this is a # An n-length list is smaller than a k-length set, or this is a
# mapping type so the other algorithm wouldn't work. # mapping type so the other algorithm wouldn't work.
pool = list(population) pool = list(population)
for i in xrange(k): # invariant: non-selected at [0,n-i) for i in range(k): # invariant: non-selected at [0,n-i)
j = _int(random() * (n-i)) j = _int(random() * (n-i))
result[i] = pool[j] result[i] = pool[j]
pool[j] = pool[n-i-1] # move non-selected item into vacancy pool[j] = pool[n-i-1] # move non-selected item into vacancy
@ -319,7 +319,7 @@ class Random(_random.Random):
try: try:
selected = set() selected = set()
selected_add = selected.add selected_add = selected.add
for i in xrange(k): for i in range(k):
j = _int(random() * n) j = _int(random() * n)
while j in selected: while j in selected:
j = _int(random() * n) j = _int(random() * n)

View file

@ -51,10 +51,10 @@ class RegressionTests(unittest.TestCase):
# reset before a rollback, but only those that are still in the # reset before a rollback, but only those that are still in the
# statement cache. The others are not accessible from the connection object. # statement cache. The others are not accessible from the connection object.
con = sqlite.connect(":memory:", cached_statements=5) con = sqlite.connect(":memory:", cached_statements=5)
cursors = [con.cursor() for x in xrange(5)] cursors = [con.cursor() for x in range(5)]
cursors[0].execute("create table test(x)") cursors[0].execute("create table test(x)")
for i in range(10): for i in range(10):
cursors[0].executemany("insert into test(x) values (?)", [(x,) for x in xrange(10)]) cursors[0].executemany("insert into test(x) values (?)", [(x,) for x in range(10)])
for i in range(5): for i in range(5):
cursors[i].execute(" " * i + "select x from test") cursors[i].execute(" " * i + "select x from test")

View file

@ -318,7 +318,7 @@ def _optimize_unicode(charset, fixup):
elif op is LITERAL: elif op is LITERAL:
charmap[fixup(av)] = 1 charmap[fixup(av)] = 1
elif op is RANGE: elif op is RANGE:
for i in xrange(fixup(av[0]), fixup(av[1])+1): for i in range(fixup(av[0]), fixup(av[1])+1):
charmap[i] = 1 charmap[i] = 1
elif op is CATEGORY: elif op is CATEGORY:
# XXX: could expand category # XXX: could expand category
@ -330,13 +330,13 @@ def _optimize_unicode(charset, fixup):
if sys.maxunicode != 65535: if sys.maxunicode != 65535:
# XXX: negation does not work with big charsets # XXX: negation does not work with big charsets
return charset return charset
for i in xrange(65536): for i in range(65536):
charmap[i] = not charmap[i] charmap[i] = not charmap[i]
comps = {} comps = {}
mapping = [0]*256 mapping = [0]*256
block = 0 block = 0
data = [] data = []
for i in xrange(256): for i in range(256):
chunk = tuple(charmap[i*256:(i+1)*256]) chunk = tuple(charmap[i*256:(i+1)*256])
new = comps.setdefault(chunk, block) new = comps.setdefault(chunk, block)
mapping[i] = new mapping[i] = new
@ -461,7 +461,7 @@ def _compile_info(code, pattern, flags):
code.extend(prefix) code.extend(prefix)
# generate overlap table # generate overlap table
table = [-1] + ([0]*len(prefix)) table = [-1] + ([0]*len(prefix))
for i in xrange(len(prefix)): for i in range(len(prefix)):
table[i+1] = table[i]+1 table[i+1] = table[i]+1
while table[i+1] > 0 and prefix[i] != prefix[table[i+1]-1]: while table[i+1] > 0 and prefix[i] != prefix[table[i+1]-1]:
table[i+1] = table[table[i+1]-1]+1 table[i+1] = table[table[i+1]-1]+1

View file

@ -30,7 +30,7 @@ printable = digits + letters + punctuation + whitespace
# Case conversion helpers # Case conversion helpers
# Use str to convert Unicode literal in case of -U # Use str to convert Unicode literal in case of -U
l = map(chr, xrange(256)) l = map(chr, range(256))
_idmap = str('').join(l) _idmap = str('').join(l)
del l del l

View file

@ -16,7 +16,7 @@ def in_table_a1(code):
return (c & 0xFFFF) not in (0xFFFE, 0xFFFF) return (c & 0xFFFF) not in (0xFFFE, 0xFFFF)
b1_set = set([173, 847, 6150, 6155, 6156, 6157, 8203, 8204, 8205, 8288, 65279] + range(65024,65040)) b1_set = set([173, 847, 6150, 6155, 6156, 6157, 8203, 8204, 8205, 8288, 65279] + list(range(65024,65040)))
def in_table_b1(code): def in_table_b1(code):
return ord(code) in b1_set return ord(code) in b1_set
@ -217,7 +217,7 @@ def in_table_c11_c12(code):
def in_table_c21(code): def in_table_c21(code):
return ord(code) < 128 and unicodedata.category(code) == "Cc" return ord(code) < 128 and unicodedata.category(code) == "Cc"
c22_specials = set([1757, 1807, 6158, 8204, 8205, 8232, 8233, 65279] + range(8288,8292) + range(8298,8304) + range(65529,65533) + range(119155,119163)) c22_specials = set([1757, 1807, 6158, 8204, 8205, 8232, 8233, 65279] + list(range(8288,8292)) + list(range(8298,8304)) + list(range(65529,65533)) + list(range(119155,119163)))
def in_table_c22(code): def in_table_c22(code):
c = ord(code) c = ord(code)
if c < 128: return False if c < 128: return False
@ -254,12 +254,12 @@ def in_table_c7(code):
return ord(code) in c7_set return ord(code) in c7_set
c8_set = set([832, 833, 8206, 8207] + range(8234,8239) + range(8298,8304)) c8_set = set([832, 833, 8206, 8207] + list(range(8234,8239)) + list(range(8298,8304)))
def in_table_c8(code): def in_table_c8(code):
return ord(code) in c8_set return ord(code) in c8_set
c9_set = set([917505] + range(917536,917632)) c9_set = set([917505] + list(range(917536,917632)))
def in_table_c9(code): def in_table_c9(code):
return ord(code) in c9_set return ord(code) in c9_set

View file

@ -969,7 +969,7 @@ class Popen(object):
def _close_fds(self, but): def _close_fds(self, but):
for i in xrange(3, MAXFD): for i in range(3, MAXFD):
if i == but: if i == but:
continue continue
try: try:

View file

@ -188,7 +188,7 @@ def nti(s):
raise HeaderError("invalid header") raise HeaderError("invalid header")
else: else:
n = 0 n = 0
for i in xrange(len(s) - 1): for i in range(len(s) - 1):
n <<= 8 n <<= 8
n += ord(s[i + 1]) n += ord(s[i + 1])
return n return n
@ -214,7 +214,7 @@ def itn(n, digits=8, format=DEFAULT_FORMAT):
n = struct.unpack("L", struct.pack("l", n))[0] n = struct.unpack("L", struct.pack("l", n))[0]
s = "" s = ""
for i in xrange(digits - 1): for i in range(digits - 1):
s = chr(n & 0377) + s s = chr(n & 0377) + s
n >>= 8 n >>= 8
s = chr(0200) + s s = chr(0200) + s
@ -245,7 +245,7 @@ def copyfileobj(src, dst, length=None):
BUFSIZE = 16 * 1024 BUFSIZE = 16 * 1024
blocks, remainder = divmod(length, BUFSIZE) blocks, remainder = divmod(length, BUFSIZE)
for b in xrange(blocks): for b in range(blocks):
buf = src.read(BUFSIZE) buf = src.read(BUFSIZE)
if len(buf) < BUFSIZE: if len(buf) < BUFSIZE:
raise IOError("end of file reached") raise IOError("end of file reached")
@ -514,7 +514,7 @@ class _Stream:
""" """
if pos - self.pos >= 0: if pos - self.pos >= 0:
blocks, remainder = divmod(pos - self.pos, self.bufsize) blocks, remainder = divmod(pos - self.pos, self.bufsize)
for i in xrange(blocks): for i in range(blocks):
self.read(self.bufsize) self.read(self.bufsize)
self.read(remainder) self.read(remainder)
else: else:
@ -1297,7 +1297,7 @@ class TarInfo(object):
realpos = 0 realpos = 0
# There are 4 possible sparse structs in the # There are 4 possible sparse structs in the
# first header. # first header.
for i in xrange(4): for i in range(4):
try: try:
offset = nti(buf[pos:pos + 12]) offset = nti(buf[pos:pos + 12])
numbytes = nti(buf[pos + 12:pos + 24]) numbytes = nti(buf[pos + 12:pos + 24])
@ -1318,7 +1318,7 @@ class TarInfo(object):
while isextended == 1: while isextended == 1:
buf = tarfile.fileobj.read(BLOCKSIZE) buf = tarfile.fileobj.read(BLOCKSIZE)
pos = 0 pos = 0
for i in xrange(21): for i in range(21):
try: try:
offset = nti(buf[pos:pos + 12]) offset = nti(buf[pos:pos + 12])
numbytes = nti(buf[pos + 12:pos + 24]) numbytes = nti(buf[pos + 12:pos + 24])
@ -2304,7 +2304,7 @@ class TarFile(object):
else: else:
end = members.index(tarinfo) end = members.index(tarinfo)
for i in xrange(end - 1, -1, -1): for i in range(end - 1, -1, -1):
if name == members[i].name: if name == members[i].name:
return members[i] return members[i]

View file

@ -196,7 +196,7 @@ def _get_default_tempdir():
if dir != _os.curdir: if dir != _os.curdir:
dir = _os.path.normcase(_os.path.abspath(dir)) dir = _os.path.normcase(_os.path.abspath(dir))
# Try only a few names per directory. # Try only a few names per directory.
for seq in xrange(100): for seq in range(100):
name = next(namer) name = next(namer)
filename = _os.path.join(dir, name) filename = _os.path.join(dir, name)
try: try:
@ -235,7 +235,7 @@ def _mkstemp_inner(dir, pre, suf, flags):
names = _get_candidate_names() names = _get_candidate_names()
for seq in xrange(TMP_MAX): for seq in range(TMP_MAX):
name = next(names) name = next(names)
file = _os.path.join(dir, pre + name + suf) file = _os.path.join(dir, pre + name + suf)
try: try:
@ -327,7 +327,7 @@ def mkdtemp(suffix="", prefix=template, dir=None):
names = _get_candidate_names() names = _get_candidate_names()
for seq in xrange(TMP_MAX): for seq in range(TMP_MAX):
name = next(names) name = next(names)
file = _os.path.join(dir, prefix + name + suffix) file = _os.path.join(dir, prefix + name + suffix)
try: try:
@ -362,7 +362,7 @@ def mktemp(suffix="", prefix=template, dir=None):
dir = gettempdir() dir = gettempdir()
names = _get_candidate_names() names = _get_candidate_names()
for seq in xrange(TMP_MAX): for seq in range(TMP_MAX):
name = next(names) name = next(names)
file = _os.path.join(dir, prefix + name + suffix) file = _os.path.join(dir, prefix + name + suffix)
if not _exists(file): if not _exists(file):

View file

@ -52,7 +52,7 @@ class ForkWait(unittest.TestCase):
time.sleep(LONGSLEEP) time.sleep(LONGSLEEP)
a = sorted(self.alive.keys()) a = sorted(self.alive.keys())
self.assertEquals(a, range(NUM_THREADS)) self.assertEquals(a, list(range(NUM_THREADS)))
prefork_lives = self.alive.copy() prefork_lives = self.alive.copy()

View file

@ -47,9 +47,9 @@ class CommonTest(seq_tests.CommonTest):
self.assertEqual(repr(a2), "[0, 1, 2, [...], 3]") self.assertEqual(repr(a2), "[0, 1, 2, [...], 3]")
def test_print(self): def test_print(self):
d = self.type2test(xrange(200)) d = self.type2test(range(200))
d.append(d) d.append(d)
d.extend(xrange(200,400)) d.extend(range(200,400))
d.append(d) d.append(d)
d.append(400) d.append(400)
try: try:
@ -398,7 +398,7 @@ class CommonTest(seq_tests.CommonTest):
del self.victim[:] del self.victim[:]
return False return False
a = self.type2test() a = self.type2test()
a[:] = [EvilCmp(a) for _ in xrange(100)] a[:] = [EvilCmp(a) for _ in range(100)]
# This used to seg fault before patch #1005778 # This used to seg fault before patch #1005778
self.assertRaises(ValueError, a.index, None) self.assertRaises(ValueError, a.index, None)

View file

@ -1,5 +1,5 @@
test_cProfile test_cProfile
127 function calls (107 primitive calls) in 1.000 CPU seconds 119 function calls (99 primitive calls) in 1.000 CPU seconds
Ordered by: standard name Ordered by: standard name
@ -18,7 +18,6 @@ test_cProfile
12 0.000 0.000 0.012 0.001 {hasattr} 12 0.000 0.000 0.012 0.001 {hasattr}
4 0.000 0.000 0.000 0.000 {method 'append' of 'list' objects} 4 0.000 0.000 0.000 0.000 {method 'append' of 'list' objects}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
8 0.000 0.000 0.000 0.000 {range}
4 0.000 0.000 0.000 0.000 {sys.exc_info} 4 0.000 0.000 0.000 0.000 {sys.exc_info}
@ -28,7 +27,6 @@ Function called...
ncalls tottime cumtime ncalls tottime cumtime
<string>:1(<module>) -> 1 0.270 1.000 test_cProfile.py:30(testfunc) <string>:1(<module>) -> 1 0.270 1.000 test_cProfile.py:30(testfunc)
test_cProfile.py:103(subhelper) -> 16 0.016 0.016 test_cProfile.py:115(__getattr__) test_cProfile.py:103(subhelper) -> 16 0.016 0.016 test_cProfile.py:115(__getattr__)
8 0.000 0.000 {range}
test_cProfile.py:115(__getattr__) -> test_cProfile.py:115(__getattr__) ->
test_cProfile.py:30(testfunc) -> 1 0.014 0.130 test_cProfile.py:40(factorial) test_cProfile.py:30(testfunc) -> 1 0.014 0.130 test_cProfile.py:40(factorial)
2 0.040 0.600 test_cProfile.py:60(helper) 2 0.040 0.600 test_cProfile.py:60(helper)
@ -49,7 +47,6 @@ test_cProfile.py:93(helper2) -> 8 0.064 0.080
{hasattr} -> 12 0.012 0.012 test_cProfile.py:115(__getattr__) {hasattr} -> 12 0.012 0.012 test_cProfile.py:115(__getattr__)
{method 'append' of 'list' objects} -> {method 'append' of 'list' objects} ->
{method 'disable' of '_lsprof.Profiler' objects} -> {method 'disable' of '_lsprof.Profiler' objects} ->
{range} ->
{sys.exc_info} -> {sys.exc_info} ->
@ -76,7 +73,6 @@ test_cProfile.py:93(helper2) <- 6 0.234 0.300
8 0.000 0.008 test_cProfile.py:93(helper2) 8 0.000 0.008 test_cProfile.py:93(helper2)
{method 'append' of 'list' objects} <- 4 0.000 0.000 test_cProfile.py:78(helper1) {method 'append' of 'list' objects} <- 4 0.000 0.000 test_cProfile.py:78(helper1)
{method 'disable' of '_lsprof.Profiler' objects} <- {method 'disable' of '_lsprof.Profiler' objects} <-
{range} <- 8 0.000 0.000 test_cProfile.py:103(subhelper)
{sys.exc_info} <- 4 0.000 0.000 test_cProfile.py:78(helper1) {sys.exc_info} <- 4 0.000 0.000 test_cProfile.py:78(helper1)

View file

@ -1,5 +1,5 @@
test_profile test_profile
128 function calls (108 primitive calls) in 1.000 CPU seconds 120 function calls (100 primitive calls) in 1.000 CPU seconds
Ordered by: standard name Ordered by: standard name
@ -8,7 +8,6 @@ test_profile
4 0.000 0.000 0.000 0.000 :0(exc_info) 4 0.000 0.000 0.000 0.000 :0(exc_info)
1 0.000 0.000 1.000 1.000 :0(exec) 1 0.000 0.000 1.000 1.000 :0(exec)
12 0.000 0.000 0.012 0.001 :0(hasattr) 12 0.000 0.000 0.012 0.001 :0(hasattr)
8 0.000 0.000 0.000 0.000 :0(range)
1 0.000 0.000 0.000 0.000 :0(setprofile) 1 0.000 0.000 0.000 0.000 :0(setprofile)
1 0.000 0.000 1.000 1.000 <string>:1(<module>) 1 0.000 0.000 1.000 1.000 <string>:1(<module>)
0 0.000 0.000 profile:0(profiler) 0 0.000 0.000 profile:0(profiler)
@ -31,14 +30,12 @@ Function called...
:0(exc_info) -> :0(exc_info) ->
:0(exec) -> <string>:1(<module>)(1) 1.000 :0(exec) -> <string>:1(<module>)(1) 1.000
:0(hasattr) -> test_profile.py:115(__getattr__)(12) 0.028 :0(hasattr) -> test_profile.py:115(__getattr__)(12) 0.028
:0(range) ->
:0(setprofile) -> :0(setprofile) ->
<string>:1(<module>) -> test_profile.py:30(testfunc)(1) 1.000 <string>:1(<module>) -> test_profile.py:30(testfunc)(1) 1.000
profile:0(profiler) -> profile:0(testfunc())(1) 1.000 profile:0(profiler) -> profile:0(testfunc())(1) 1.000
profile:0(testfunc()) -> :0(exec)(1) 1.000 profile:0(testfunc()) -> :0(exec)(1) 1.000
:0(setprofile)(1) 0.000 :0(setprofile)(1) 0.000
test_profile.py:103(subhelper) -> :0(range)(8) 0.000 test_profile.py:103(subhelper) -> test_profile.py:115(__getattr__)(16) 0.028
test_profile.py:115(__getattr__)(16) 0.028
test_profile.py:115(__getattr__) -> test_profile.py:115(__getattr__) ->
test_profile.py:30(testfunc) -> test_profile.py:40(factorial)(1) 0.170 test_profile.py:30(testfunc) -> test_profile.py:40(factorial)(1) 0.170
test_profile.py:60(helper)(2) 0.600 test_profile.py:60(helper)(2) 0.600
@ -65,7 +62,6 @@ Function was called by...
:0(exec) <- profile:0(testfunc())(1) 1.000 :0(exec) <- profile:0(testfunc())(1) 1.000
:0(hasattr) <- test_profile.py:78(helper1)(4) 0.120 :0(hasattr) <- test_profile.py:78(helper1)(4) 0.120
test_profile.py:93(helper2)(8) 0.400 test_profile.py:93(helper2)(8) 0.400
:0(range) <- test_profile.py:103(subhelper)(8) 0.080
:0(setprofile) <- profile:0(testfunc())(1) 1.000 :0(setprofile) <- profile:0(testfunc())(1) 1.000
<string>:1(<module>) <- :0(exec)(1) 1.000 <string>:1(<module>) <- :0(exec)(1) 1.000
profile:0(profiler) <- profile:0(profiler) <-

View file

@ -745,7 +745,7 @@ class AbstractPickleTests(unittest.TestCase):
def test_list_chunking(self): def test_list_chunking(self):
n = 10 # too small to chunk n = 10 # too small to chunk
x = range(n) x = list(range(n))
for proto in protocols: for proto in protocols:
s = self.dumps(x, proto) s = self.dumps(x, proto)
y = self.loads(s) y = self.loads(s)
@ -754,7 +754,7 @@ class AbstractPickleTests(unittest.TestCase):
self.assertEqual(num_appends, proto > 0) self.assertEqual(num_appends, proto > 0)
n = 2500 # expect at least two chunks when proto > 0 n = 2500 # expect at least two chunks when proto > 0
x = range(n) x = list(range(n))
for proto in protocols: for proto in protocols:
s = self.dumps(x, proto) s = self.dumps(x, proto)
y = self.loads(s) y = self.loads(s)
@ -991,7 +991,7 @@ class AbstractPersistentPicklerTests(unittest.TestCase):
def test_persistence(self): def test_persistence(self):
self.id_count = 0 self.id_count = 0
self.load_count = 0 self.load_count = 0
L = range(10) L = list(range(10))
self.assertEqual(self.loads(self.dumps(L)), L) self.assertEqual(self.loads(self.dumps(L)), L)
self.assertEqual(self.id_count, 5) self.assertEqual(self.id_count, 5)
self.assertEqual(self.load_count, 5) self.assertEqual(self.load_count, 5)
@ -999,7 +999,7 @@ class AbstractPersistentPicklerTests(unittest.TestCase):
def test_bin_persistence(self): def test_bin_persistence(self):
self.id_count = 0 self.id_count = 0
self.load_count = 0 self.load_count = 0
L = range(10) L = list(range(10))
self.assertEqual(self.loads(self.dumps(L, 1)), L) self.assertEqual(self.loads(self.dumps(L, 1)), L)
self.assertEqual(self.id_count, 5) self.assertEqual(self.id_count, 5)
self.assertEqual(self.load_count, 5) self.assertEqual(self.load_count, 5)

View file

@ -120,7 +120,7 @@ class CommonTest(unittest.TestCase):
self.assertEqual(len(vv), len(s)) self.assertEqual(len(vv), len(s))
# Create from various iteratables # Create from various iteratables
for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)): for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
for g in (Sequence, IterFunc, IterGen, for g in (Sequence, IterFunc, IterGen,
itermulti, iterfunc): itermulti, iterfunc):
self.assertEqual(self.type2test(g(s)), self.type2test(s)) self.assertEqual(self.type2test(g(s)), self.type2test(s))
@ -136,10 +136,10 @@ class CommonTest(unittest.TestCase):
def test_getitem(self): def test_getitem(self):
u = self.type2test([0, 1, 2, 3, 4]) u = self.type2test([0, 1, 2, 3, 4])
for i in xrange(len(u)): for i in range(len(u)):
self.assertEqual(u[i], i) self.assertEqual(u[i], i)
self.assertEqual(u[int(i)], i) self.assertEqual(u[int(i)], i)
for i in xrange(-len(u), -1): for i in range(-len(u), -1):
self.assertEqual(u[i], len(u)+i) self.assertEqual(u[i], len(u)+i)
self.assertEqual(u[int(i)], len(u)+i) self.assertEqual(u[int(i)], len(u)+i)
self.assertRaises(IndexError, u.__getitem__, -len(u)-1) self.assertRaises(IndexError, u.__getitem__, -len(u)-1)
@ -299,9 +299,9 @@ class CommonTest(unittest.TestCase):
self.assertEqual(next(iter(T((1,2)))), 1) self.assertEqual(next(iter(T((1,2)))), 1)
def test_repeat(self): def test_repeat(self):
for m in xrange(4): for m in range(4):
s = tuple(range(m)) s = tuple(range(m))
for n in xrange(-3, 5): for n in range(-3, 5):
self.assertEqual(self.type2test(s*n), self.type2test(s)*n) self.assertEqual(self.type2test(s*n), self.type2test(s)*n)
self.assertEqual(self.type2test(s)*(-4), self.type2test([])) self.assertEqual(self.type2test(s)*(-4), self.type2test([]))
self.assertEqual(id(s), id(s*1)) self.assertEqual(id(s), id(s*1))

View file

@ -24,7 +24,7 @@ def randfloats(n):
fp = open(fn, "rb") fp = open(fn, "rb")
except IOError: except IOError:
r = random.random r = random.random
result = [r() for i in xrange(n)] result = [r() for i in range(n)]
try: try:
try: try:
fp = open(fn, "wb") fp = open(fn, "wb")
@ -108,7 +108,7 @@ def tabulate(r):
doit(L) # +sort doit(L) # +sort
# Replace 1% of the elements at random. # Replace 1% of the elements at random.
for dummy in xrange(n // 100): for dummy in range(n // 100):
L[random.randrange(n)] = random.random() L[random.randrange(n)] = random.random()
doit(L) # %sort doit(L) # %sort

View file

@ -112,9 +112,9 @@ class BaseTest(unittest.TestCase):
digits = 7 digits = 7
base = len(charset) base = len(charset)
teststrings = set() teststrings = set()
for i in xrange(base ** digits): for i in range(base ** digits):
entry = [] entry = []
for j in xrange(digits): for j in range(digits):
i, m = divmod(i, base) i, m = divmod(i, base)
entry.append(charset[m]) entry.append(charset[m])
teststrings.add(''.join(entry)) teststrings.add(''.join(entry))
@ -151,9 +151,9 @@ class BaseTest(unittest.TestCase):
digits = 5 digits = 5
base = len(charset) base = len(charset)
teststrings = set() teststrings = set()
for i in xrange(base ** digits): for i in range(base ** digits):
entry = [] entry = []
for j in xrange(digits): for j in range(digits):
i, m = divmod(i, base) i, m = divmod(i, base)
entry.append(charset[m]) entry.append(charset[m])
teststrings.add(''.join(entry)) teststrings.add(''.join(entry))
@ -1006,10 +1006,10 @@ class MixinStrUnicodeUserStringTest:
def test_floatformatting(self): def test_floatformatting(self):
# float formatting # float formatting
for prec in xrange(100): for prec in range(100):
format = '%%.%if' % prec format = '%%.%if' % prec
value = 0.01 value = 0.01
for x in xrange(60): for x in range(60):
value = value * 3.141592655 / 3.0 * 10.0 value = value * 3.141592655 / 3.0 * 10.0
# The formatfloat() code in stringobject.c and # The formatfloat() code in stringobject.c and
# unicodeobject.c uses a 120 byte buffer and switches from # unicodeobject.c uses a 120 byte buffer and switches from
@ -1076,7 +1076,7 @@ class MixinStrStringUserStringTest:
def test_maketrans(self): def test_maketrans(self):
self.assertEqual( self.assertEqual(
''.join(map(chr, xrange(256))).replace('abc', 'xyz'), ''.join(map(chr, range(256))).replace('abc', 'xyz'),
string.maketrans('abc', 'xyz') string.maketrans('abc', 'xyz')
) )
self.assertRaises(ValueError, string.maketrans, 'abc', 'xyzw') self.assertRaises(ValueError, string.maketrans, 'abc', 'xyzw')

View file

@ -836,7 +836,7 @@ class NumberTest(BaseTest):
def test_iterationcontains(self): def test_iterationcontains(self):
a = array.array(self.typecode, range(10)) a = array.array(self.typecode, range(10))
self.assertEqual(list(a), range(10)) self.assertEqual(list(a), list(range(10)))
b = array.array(self.typecode, [20]) b = array.array(self.typecode, [20])
self.assertEqual(a[-1] in a, True) self.assertEqual(a[-1] in a, True)
self.assertEqual(b[0] not in a, True) self.assertEqual(b[0] not in a, True)
@ -985,7 +985,7 @@ def test_main(verbose=None):
if verbose and hasattr(sys, "gettotalrefcount"): if verbose and hasattr(sys, "gettotalrefcount"):
import gc import gc
counts = [None] * 5 counts = [None] * 5
for i in xrange(len(counts)): for i in range(len(counts)):
test_support.run_unittest(*tests) test_support.run_unittest(*tests)
gc.collect() gc.collect()
counts[i] = sys.gettotalrefcount() counts[i] = sys.gettotalrefcount()

View file

@ -9,7 +9,7 @@ class BinASCIITest(unittest.TestCase):
# Create binary test data # Create binary test data
data = "The quick brown fox jumps over the lazy dog.\r\n" data = "The quick brown fox jumps over the lazy dog.\r\n"
# Be slow so we don't depend on other modules # Be slow so we don't depend on other modules
data += "".join(map(chr, xrange(256))) data += "".join(map(chr, range(256)))
data += "\r\nHello world.\n" data += "\r\nHello world.\n"
def test_exceptions(self): def test_exceptions(self):
@ -58,7 +58,7 @@ class BinASCIITest(unittest.TestCase):
fillers = "" fillers = ""
valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/" valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/"
for i in xrange(256): for i in range(256):
c = chr(i) c = chr(i)
if c not in valid: if c not in valid:
fillers += c fillers += c

View file

@ -94,8 +94,8 @@ class TestBisect(unittest.TestCase):
def test_random(self, n=25): def test_random(self, n=25):
from random import randrange from random import randrange
for i in xrange(n): for i in range(n):
data = [randrange(0, n, 2) for j in xrange(i)] data = [randrange(0, n, 2) for j in range(i)]
data.sort() data.sort()
elem = randrange(-1, n+1) elem = randrange(-1, n+1)
ip = bisect_left(data, elem) ip = bisect_left(data, elem)
@ -111,9 +111,9 @@ class TestBisect(unittest.TestCase):
def test_optionalSlicing(self): def test_optionalSlicing(self):
for func, data, elem, expected in self.precomputedCases: for func, data, elem, expected in self.precomputedCases:
for lo in xrange(4): for lo in range(4):
lo = min(len(data), lo) lo = min(len(data), lo)
for hi in xrange(3,8): for hi in range(3,8):
hi = min(len(data), hi) hi = min(len(data), hi)
ip = func(data, elem, lo, hi) ip = func(data, elem, lo, hi)
self.failUnless(lo <= ip <= hi) self.failUnless(lo <= ip <= hi)
@ -147,7 +147,7 @@ class TestInsort(unittest.TestCase):
def test_vsBuiltinSort(self, n=500): def test_vsBuiltinSort(self, n=500):
from random import choice from random import choice
for insorted in (list(), UserList()): for insorted in (list(), UserList()):
for i in xrange(n): for i in range(n):
digit = choice("0123456789") digit = choice("0123456789")
if digit in "02468": if digit in "02468":
f = insort_left f = insort_left
@ -248,7 +248,7 @@ def test_main(verbose=None):
if verbose and hasattr(sys, "gettotalrefcount"): if verbose and hasattr(sys, "gettotalrefcount"):
import gc import gc
counts = [None] * 5 counts = [None] * 5
for i in xrange(len(counts)): for i in range(len(counts)):
test_support.run_unittest(*test_classes) test_support.run_unittest(*test_classes)
gc.collect() gc.collect()
counts[i] = sys.gettotalrefcount() counts[i] = sys.gettotalrefcount()

View file

@ -117,13 +117,13 @@ class TestBSDDB(unittest.TestCase):
def test_first_next_looping(self): def test_first_next_looping(self):
items = [self.f.first()] items = [self.f.first()]
for i in xrange(1, len(self.f)): for i in range(1, len(self.f)):
items.append(self.f.next()) items.append(self.f.next())
self.assertSetEquals(items, self.d.items()) self.assertSetEquals(items, self.d.items())
def test_previous_last_looping(self): def test_previous_last_looping(self):
items = [self.f.last()] items = [self.f.last()]
for i in xrange(1, len(self.f)): for i in range(1, len(self.f)):
items.append(self.f.previous()) items.append(self.f.previous())
self.assertSetEquals(items, self.d.items()) self.assertSetEquals(items, self.d.items())

View file

@ -5,7 +5,7 @@ from test import test_support
# the expected results. For best testing, run this under a debug-build # the expected results. For best testing, run this under a debug-build
# Python too (to exercise asserts in the C code). # Python too (to exercise asserts in the C code).
lengths = range(1, 257) + [512, 1000, 1024, 2048, 4096, 8192, 10000, lengths = list(range(1, 257)) + [512, 1000, 1024, 2048, 4096, 8192, 10000,
16384, 32768, 65536, 1000000] 16384, 32768, 65536, 1000000]
class BufferSizeTest(unittest.TestCase): class BufferSizeTest(unittest.TestCase):

View file

@ -990,7 +990,7 @@ class BuiltinTest(unittest.TestCase):
# thread for the details: # thread for the details:
# http://sources.redhat.com/ml/newlib/2002/msg00369.html # http://sources.redhat.com/ml/newlib/2002/msg00369.html
self.assertRaises(MemoryError, list, xrange(sys.maxint // 2)) self.assertRaises(MemoryError, list, range(sys.maxint // 2))
# This code used to segfault in Py2.4a3 # This code used to segfault in Py2.4a3
x = [] x = []
@ -1454,38 +1454,39 @@ class BuiltinTest(unittest.TestCase):
self.assertRaises(TypeError, pow) self.assertRaises(TypeError, pow)
def test_range(self): def test_range(self):
self.assertEqual(range(3), [0, 1, 2]) self.assertEqual(list(range(3)), [0, 1, 2])
self.assertEqual(range(1, 5), [1, 2, 3, 4]) self.assertEqual(list(range(1, 5)), [1, 2, 3, 4])
self.assertEqual(range(0), []) self.assertEqual(list(range(0)), [])
self.assertEqual(range(-3), []) self.assertEqual(list(range(-3)), [])
self.assertEqual(range(1, 10, 3), [1, 4, 7]) self.assertEqual(list(range(1, 10, 3)), [1, 4, 7])
self.assertEqual(range(5, -5, -3), [5, 2, -1, -4]) #self.assertEqual(list(range(5, -5, -3)), [5, 2, -1, -4])
""" XXX(nnorwitz):
# Now test range() with longs # Now test range() with longs
self.assertEqual(range(-2**100), []) self.assertEqual(list(range(-2**100)), [])
self.assertEqual(range(0, -2**100), []) self.assertEqual(list(range(0, -2**100)), [])
self.assertEqual(range(0, 2**100, -1), []) self.assertEqual(list(range(0, 2**100, -1)), [])
self.assertEqual(range(0, 2**100, -1), []) self.assertEqual(list(range(0, 2**100, -1)), [])
a = int(10 * sys.maxint) a = int(10 * sys.maxint)
b = int(100 * sys.maxint) b = int(100 * sys.maxint)
c = int(50 * sys.maxint) c = int(50 * sys.maxint)
self.assertEqual(range(a, a+2), [a, a+1]) self.assertEqual(list(range(a, a+2)), [a, a+1])
self.assertEqual(range(a+2, a, -1), [a+2, a+1]) self.assertEqual(list(range(a+2, a, -1)), [a+2, a+1])
self.assertEqual(range(a+4, a, -2), [a+4, a+2]) self.assertEqual(list(range(a+4, a, -2)), [a+4, a+2])
seq = range(a, b, c) seq = list(range(a, b, c))
self.assert_(a in seq) self.assert_(a in seq)
self.assert_(b not in seq) self.assert_(b not in seq)
self.assertEqual(len(seq), 2) self.assertEqual(len(seq), 2)
seq = range(b, a, -c) seq = list(range(b, a, -c))
self.assert_(b in seq) self.assert_(b in seq)
self.assert_(a not in seq) self.assert_(a not in seq)
self.assertEqual(len(seq), 2) self.assertEqual(len(seq), 2)
seq = range(-a, -b, -c) seq = list(range(-a, -b, -c))
self.assert_(-a in seq) self.assert_(-a in seq)
self.assert_(-b not in seq) self.assert_(-b not in seq)
self.assertEqual(len(seq), 2) self.assertEqual(len(seq), 2)
@ -1502,6 +1503,7 @@ class BuiltinTest(unittest.TestCase):
# XXX This won't (but should!) raise RuntimeError if a is an int... # XXX This won't (but should!) raise RuntimeError if a is an int...
self.assertRaises(RuntimeError, range, a, a + 1, badzero(1)) self.assertRaises(RuntimeError, range, a, a + 1, badzero(1))
"""
# Reject floats when it would require PyLongs to represent. # Reject floats when it would require PyLongs to represent.
# (smaller floats still accepted, but deprecated) # (smaller floats still accepted, but deprecated)
@ -1510,8 +1512,10 @@ class BuiltinTest(unittest.TestCase):
self.assertRaises(TypeError, range, 0, "spam") self.assertRaises(TypeError, range, 0, "spam")
self.assertRaises(TypeError, range, 0, 42, "spam") self.assertRaises(TypeError, range, 0, 42, "spam")
self.assertRaises(OverflowError, range, -sys.maxint, sys.maxint) #NEAL self.assertRaises(OverflowError, range, -sys.maxint, sys.maxint)
self.assertRaises(OverflowError, range, 0, 2*sys.maxint) #NEAL self.assertRaises(OverflowError, range, 0, 2*sys.maxint)
self.assertRaises(OverflowError, len, range(0, sys.maxint**10))
def test_input(self): def test_input(self):
self.write_testfile() self.write_testfile()
@ -1630,8 +1634,8 @@ class BuiltinTest(unittest.TestCase):
def test_sum(self): def test_sum(self):
self.assertEqual(sum([]), 0) self.assertEqual(sum([]), 0)
self.assertEqual(sum(range(2,8)), 27) self.assertEqual(sum(list(range(2,8))), 27)
self.assertEqual(sum(iter(range(2,8))), 27) self.assertEqual(sum(iter(list(range(2,8)))), 27)
self.assertEqual(sum(Squares(10)), 285) self.assertEqual(sum(Squares(10)), 285)
self.assertEqual(sum(iter(Squares(10))), 285) self.assertEqual(sum(iter(Squares(10))), 285)
self.assertEqual(sum([[1], [2], [3]], []), [1, 2, 3]) self.assertEqual(sum([[1], [2], [3]], []), [1, 2, 3])
@ -1728,7 +1732,7 @@ class BuiltinTest(unittest.TestCase):
else: else:
return i return i
self.assertEqual( self.assertEqual(
list(zip(SequenceWithoutALength(), xrange(2**30))), list(zip(SequenceWithoutALength(), range(2**30))),
list(enumerate(range(5))) list(enumerate(range(5)))
) )
@ -1743,7 +1747,7 @@ class BuiltinTest(unittest.TestCase):
class TestSorted(unittest.TestCase): class TestSorted(unittest.TestCase):
def test_basic(self): def test_basic(self):
data = range(100) data = list(range(100))
copy = data[:] copy = data[:]
random.shuffle(copy) random.shuffle(copy)
self.assertEqual(data, sorted(copy)) self.assertEqual(data, sorted(copy))
@ -1788,7 +1792,7 @@ def test_main(verbose=None):
if verbose and hasattr(sys, "gettotalrefcount"): if verbose and hasattr(sys, "gettotalrefcount"):
import gc import gc
counts = [None] * 5 counts = [None] * 5
for i in xrange(len(counts)): for i in range(len(counts)):
run_unittest(*test_classes) run_unittest(*test_classes)
gc.collect() gc.collect()
counts[i] = sys.gettotalrefcount() counts[i] = sys.gettotalrefcount()

View file

@ -230,7 +230,7 @@ class BZ2FileTest(BaseTest):
def testOpenDel(self): def testOpenDel(self):
# "Test opening and deleting a file many times" # "Test opening and deleting a file many times"
self.createTempFile() self.createTempFile()
for i in xrange(10000): for i in range(10000):
o = BZ2File(self.filename) o = BZ2File(self.filename)
del o del o

View file

@ -260,7 +260,7 @@ class MonthCalendarTestCase(unittest.TestCase):
def check_weeks(self, year, month, weeks): def check_weeks(self, year, month, weeks):
cal = calendar.monthcalendar(year, month) cal = calendar.monthcalendar(year, month)
self.assertEqual(len(cal), len(weeks)) self.assertEqual(len(cal), len(weeks))
for i in xrange(len(weeks)): for i in range(len(weeks)):
self.assertEqual(weeks[i], sum(day != 0 for day in cal[i])) self.assertEqual(weeks[i], sum(day != 0 for day in cal[i]))

View file

@ -234,7 +234,7 @@ class CodecCallbackTest(unittest.TestCase):
if not isinstance(exc, UnicodeEncodeError) \ if not isinstance(exc, UnicodeEncodeError) \
and not isinstance(exc, UnicodeDecodeError): and not isinstance(exc, UnicodeDecodeError):
raise TypeError("don't know how to handle %r" % exc) raise TypeError("don't know how to handle %r" % exc)
l = ["<%d>" % ord(exc.object[pos]) for pos in xrange(exc.start, exc.end)] l = ["<%d>" % ord(exc.object[pos]) for pos in range(exc.start, exc.end)]
return ("[%s]" % "".join(l), exc.end) return ("[%s]" % "".join(l), exc.end)
codecs.register_error("test.handler1", handler1) codecs.register_error("test.handler1", handler1)
@ -242,7 +242,7 @@ class CodecCallbackTest(unittest.TestCase):
def handler2(exc): def handler2(exc):
if not isinstance(exc, UnicodeDecodeError): if not isinstance(exc, UnicodeDecodeError):
raise TypeError("don't know how to handle %r" % exc) raise TypeError("don't know how to handle %r" % exc)
l = ["<%d>" % ord(exc.object[pos]) for pos in xrange(exc.start, exc.end)] l = ["<%d>" % ord(exc.object[pos]) for pos in range(exc.start, exc.end)]
return ("[%s]" % "".join(l), exc.end+1) # skip one character return ("[%s]" % "".join(l), exc.end+1) # skip one character
codecs.register_error("test.handler2", handler2) codecs.register_error("test.handler2", handler2)
@ -308,13 +308,13 @@ class CodecCallbackTest(unittest.TestCase):
self.assertRaises(TypeError, exctype, *(args + ["too much"])) self.assertRaises(TypeError, exctype, *(args + ["too much"]))
# check with one argument of the wrong type # check with one argument of the wrong type
wrongargs = [ "spam", "eggs", 42, 1.0, None ] wrongargs = [ "spam", "eggs", 42, 1.0, None ]
for i in xrange(len(args)): for i in range(len(args)):
for wrongarg in wrongargs: for wrongarg in wrongargs:
if type(wrongarg) is type(args[i]): if type(wrongarg) is type(args[i]):
continue continue
# build argument array # build argument array
callargs = [] callargs = []
for j in xrange(len(args)): for j in range(len(args)):
if i==j: if i==j:
callargs.append(wrongarg) callargs.append(wrongarg)
else: else:
@ -469,7 +469,7 @@ class CodecCallbackTest(unittest.TestCase):
codecs.replace_errors, codecs.replace_errors,
BadObjectUnicodeDecodeError() BadObjectUnicodeDecodeError()
) )
# With the correct exception, "replace" returns an "?" or u"\ufffd" replacement # With the correct exception, "replace" returns an "?" or "\ufffd" replacement
self.assertEquals( self.assertEquals(
codecs.replace_errors(UnicodeEncodeError("ascii", "\u3042", 0, 1, "ouch")), codecs.replace_errors(UnicodeEncodeError("ascii", "\u3042", 0, 1, "ouch")),
("?", 1) ("?", 1)

View file

@ -25,7 +25,7 @@ class Queue(object):
class MixInCheckStateHandling: class MixInCheckStateHandling:
def check_state_handling_decode(self, encoding, u, s): def check_state_handling_decode(self, encoding, u, s):
for i in xrange(len(s)+1): for i in range(len(s)+1):
d = codecs.getincrementaldecoder(encoding)() d = codecs.getincrementaldecoder(encoding)()
part1 = d.decode(s[:i]) part1 = d.decode(s[:i])
state = d.getstate() state = d.getstate()
@ -47,7 +47,7 @@ class MixInCheckStateHandling:
self.assertEqual(u, part1+part2) self.assertEqual(u, part1+part2)
def check_state_handling_encode(self, encoding, u, s): def check_state_handling_encode(self, encoding, u, s):
for i in xrange(len(u)+1): for i in range(len(u)+1):
d = codecs.getincrementalencoder(encoding)() d = codecs.getincrementalencoder(encoding)()
part1 = d.encode(u[:i]) part1 = d.encode(u[:i])
state = d.getstate() state = d.getstate()
@ -135,17 +135,17 @@ class ReadTest(unittest.TestCase, MixInCheckStateHandling):
# Test lines where the first read might end with \r, so the # Test lines where the first read might end with \r, so the
# reader has to look ahead whether this is a lone \r or a \r\n # reader has to look ahead whether this is a lone \r or a \r\n
for size in xrange(80): for size in range(80):
for lineend in "\n \r\n \r \u2028".split(): for lineend in "\n \r\n \r \u2028".split():
s = 10*(size*"a" + lineend + "xxx\n") s = 10*(size*"a" + lineend + "xxx\n")
reader = getreader(s) reader = getreader(s)
for i in xrange(10): for i in range(10):
self.assertEqual( self.assertEqual(
reader.readline(keepends=True), reader.readline(keepends=True),
size*"a" + lineend, size*"a" + lineend,
) )
reader = getreader(s) reader = getreader(s)
for i in xrange(10): for i in range(10):
self.assertEqual( self.assertEqual(
reader.readline(keepends=False), reader.readline(keepends=False),
size*"a", size*"a",
@ -1251,7 +1251,7 @@ class BasicUnicodeTest(unittest.TestCase, MixInCheckStateHandling):
if encoding in broken_unicode_with_streams: if encoding in broken_unicode_with_streams:
continue continue
reader = codecs.getreader(encoding)(cStringIO.StringIO(s.encode(encoding))) reader = codecs.getreader(encoding)(cStringIO.StringIO(s.encode(encoding)))
for t in xrange(5): for t in range(5):
# Test that calling seek resets the internal codec state and buffers # Test that calling seek resets the internal codec state and buffers
reader.seek(0, 0) reader.seek(0, 0)
line = reader.readline() line = reader.readline()
@ -1319,7 +1319,7 @@ class CharmapTest(unittest.TestCase):
("ab", 3) ("ab", 3)
) )
allbytes = bytes(xrange(256)) allbytes = bytes(range(256))
self.assertEquals( self.assertEquals(
codecs.charmap_decode(allbytes, "ignore", ""), codecs.charmap_decode(allbytes, "ignore", ""),
("", len(allbytes)) ("", len(allbytes))

View file

@ -399,11 +399,11 @@ if 1:
# is the max. Ensure the result of too many annotations is a # is the max. Ensure the result of too many annotations is a
# SyntaxError. # SyntaxError.
s = "def f((%s)): pass" s = "def f((%s)): pass"
s %= ', '.join('a%d:%d' % (i,i) for i in xrange(65535)) s %= ', '.join('a%d:%d' % (i,i) for i in range(65535))
self.assertRaises(SyntaxError, compile, s, '?', 'exec') self.assertRaises(SyntaxError, compile, s, '?', 'exec')
# Test that the max # of annotations compiles. # Test that the max # of annotations compiles.
s = "def f((%s)): pass" s = "def f((%s)): pass"
s %= ', '.join('a%d:%d' % (i,i) for i in xrange(65534)) s %= ', '.join('a%d:%d' % (i,i) for i in range(65534))
compile(s, '?', 'exec') compile(s, '?', 'exec')
def test_mangling(self): def test_mangling(self):

View file

@ -64,7 +64,7 @@ class ComplexTest(unittest.TestCase):
self.assertClose(q, x) self.assertClose(q, x)
def test_truediv(self): def test_truediv(self):
simple_real = [float(i) for i in xrange(-5, 6)] simple_real = [float(i) for i in range(-5, 6)]
simple_complex = [complex(x, y) for x in simple_real for y in simple_real] simple_complex = [complex(x, y) for x in simple_real for y in simple_real]
for x in simple_complex: for x in simple_complex:
for y in simple_complex: for y in simple_complex:
@ -76,7 +76,7 @@ class ComplexTest(unittest.TestCase):
self.check_div(complex(1e-200, 1e-200), 1+0j) self.check_div(complex(1e-200, 1e-200), 1+0j)
# Just for fun. # Just for fun.
for i in xrange(100): for i in range(100):
self.check_div(complex(random(), random()), self.check_div(complex(random(), random()),
complex(random(), random())) complex(random(), random()))
@ -158,7 +158,7 @@ class ComplexTest(unittest.TestCase):
self.assertRaises(ValueError, pow, a, b, 0) self.assertRaises(ValueError, pow, a, b, 0)
def test_boolcontext(self): def test_boolcontext(self):
for i in xrange(100): for i in range(100):
self.assert_(complex(random() + 1e-6, random() + 1e-6)) self.assert_(complex(random() + 1e-6, random() + 1e-6))
self.assert_(not complex(0.0, 0.0)) self.assert_(not complex(0.0, 0.0))
@ -296,13 +296,13 @@ class ComplexTest(unittest.TestCase):
self.assertRaises(TypeError, complex, complex2(1j)) self.assertRaises(TypeError, complex, complex2(1j))
def test_hash(self): def test_hash(self):
for x in xrange(-30, 30): for x in range(-30, 30):
self.assertEqual(hash(x), hash(complex(x, 0))) self.assertEqual(hash(x), hash(complex(x, 0)))
x /= 3.0 # now check against floating point x /= 3.0 # now check against floating point
self.assertEqual(hash(x), hash(complex(x, 0.))) self.assertEqual(hash(x), hash(complex(x, 0.)))
def test_abs(self): def test_abs(self):
nums = [complex(x/3., y/7.) for x in xrange(-9,9) for y in xrange(-9,9)] nums = [complex(x/3., y/7.) for x in range(-9,9) for y in range(-9,9)]
for num in nums: for num in nums:
self.assertAlmostEqual((num.real**2 + num.imag**2) ** 0.5, abs(num)) self.assertAlmostEqual((num.real**2 + num.imag**2) ** 0.5, abs(num))

View file

@ -86,7 +86,7 @@ if have_unicode:
check(str('d') not in 'abc', "u'd' in 'abc'") check(str('d') not in 'abc', "u'd' in 'abc'")
# A collection of tests on builtin sequence types # A collection of tests on builtin sequence types
a = range(10) a = list(range(10))
for i in a: for i in a:
check(i in a, "%r not in %r" % (i, a)) check(i in a, "%r not in %r" % (i, a))
check(16 not in a, "16 not in %r" % (a,)) check(16 not in a, "16 not in %r" % (a,))
@ -105,7 +105,7 @@ class Deviant1:
works when the list is modified during the check. works when the list is modified during the check.
""" """
aList = range(15) aList = list(range(15))
def __cmp__(self, other): def __cmp__(self, other):
if other == 12: if other == 12:

View file

@ -84,7 +84,7 @@ class TestCopy(unittest.TestCase):
pass pass
tests = [None, 42, 2**100, 3.14, True, False, 1j, tests = [None, 42, 2**100, 3.14, True, False, 1j,
"hello", "hello\u1234", f.__code__, "hello", "hello\u1234", f.__code__,
NewStyle, xrange(10), Classic, max] NewStyle, range(10), Classic, max]
for x in tests: for x in tests:
self.assert_(copy.copy(x) is x, repr(x)) self.assert_(copy.copy(x) is x, repr(x))
@ -257,7 +257,7 @@ class TestCopy(unittest.TestCase):
pass pass
tests = [None, 42, 2**100, 3.14, True, False, 1j, tests = [None, 42, 2**100, 3.14, True, False, 1j,
"hello", "hello\u1234", f.__code__, "hello", "hello\u1234", f.__code__,
NewStyle, xrange(10), Classic, max] NewStyle, range(10), Classic, max]
for x in tests: for x in tests:
self.assert_(copy.deepcopy(x) is x, repr(x)) self.assert_(copy.deepcopy(x) is x, repr(x))

View file

@ -909,7 +909,7 @@ else:
def test_create_read(self): def test_create_read(self):
delta = 0 delta = 0
lastrc = sys.gettotalrefcount() lastrc = sys.gettotalrefcount()
for i in xrange(20): for i in range(20):
gc.collect() gc.collect()
self.assertEqual(gc.garbage, []) self.assertEqual(gc.garbage, [])
rc = sys.gettotalrefcount() rc = sys.gettotalrefcount()
@ -925,7 +925,7 @@ else:
delta = 0 delta = 0
lastrc = sys.gettotalrefcount() lastrc = sys.gettotalrefcount()
s = NUL() s = NUL()
for i in xrange(20): for i in range(20):
gc.collect() gc.collect()
self.assertEqual(gc.garbage, []) self.assertEqual(gc.garbage, [])
rc = sys.gettotalrefcount() rc = sys.gettotalrefcount()
@ -941,7 +941,7 @@ else:
delta = 0 delta = 0
rows = ["a,b,c\r\n"]*5 rows = ["a,b,c\r\n"]*5
lastrc = sys.gettotalrefcount() lastrc = sys.gettotalrefcount()
for i in xrange(20): for i in range(20):
gc.collect() gc.collect()
self.assertEqual(gc.garbage, []) self.assertEqual(gc.garbage, [])
rc = sys.gettotalrefcount() rc = sys.gettotalrefcount()
@ -958,7 +958,7 @@ else:
rows = [[1,2,3]]*5 rows = [[1,2,3]]*5
s = NUL() s = NUL()
lastrc = sys.gettotalrefcount() lastrc = sys.gettotalrefcount()
for i in xrange(20): for i in range(20):
gc.collect() gc.collect()
self.assertEqual(gc.garbage, []) self.assertEqual(gc.garbage, [])
rc = sys.gettotalrefcount() rc = sys.gettotalrefcount()

View file

@ -569,7 +569,7 @@ class TestDate(HarmlessMixedComparison, unittest.TestCase):
# Check first and last days of year spottily across the whole # Check first and last days of year spottily across the whole
# range of years supported. # range of years supported.
for year in xrange(MINYEAR, MAXYEAR+1, 7): for year in range(MINYEAR, MAXYEAR+1, 7):
# Verify (year, 1, 1) -> ordinal -> y, m, d is identity. # Verify (year, 1, 1) -> ordinal -> y, m, d is identity.
d = self.theclass(year, 1, 1) d = self.theclass(year, 1, 1)
n = d.toordinal() n = d.toordinal()

View file

@ -842,7 +842,7 @@ class DecimalUsabilityTest(unittest.TestCase):
self.assertNotEqual(da, object) self.assertNotEqual(da, object)
# sortable # sortable
a = map(Decimal, xrange(100)) a = map(Decimal, range(100))
b = a[:] b = a[:]
random.shuffle(a) random.shuffle(a)
a.sort() a.sort()

View file

@ -29,23 +29,23 @@ class MutateCmp:
class TestBasic(unittest.TestCase): class TestBasic(unittest.TestCase):
def test_basics(self): def test_basics(self):
d = deque(xrange(100)) d = deque(range(100))
d.__init__(xrange(100, 200)) d.__init__(range(100, 200))
for i in xrange(200, 400): for i in range(200, 400):
d.append(i) d.append(i)
for i in reversed(xrange(-200, 0)): for i in reversed(range(-200, 0)):
d.appendleft(i) d.appendleft(i)
self.assertEqual(list(d), range(-200, 400)) self.assertEqual(list(d), list(range(-200, 400)))
self.assertEqual(len(d), 600) self.assertEqual(len(d), 600)
left = [d.popleft() for i in xrange(250)] left = [d.popleft() for i in range(250)]
self.assertEqual(left, range(-200, 50)) self.assertEqual(left, list(range(-200, 50)))
self.assertEqual(list(d), range(50, 400)) self.assertEqual(list(d), list(range(50, 400)))
right = [d.pop() for i in xrange(250)] right = [d.pop() for i in range(250)]
right.reverse() right.reverse()
self.assertEqual(right, range(150, 400)) self.assertEqual(right, list(range(150, 400)))
self.assertEqual(list(d), range(50, 150)) self.assertEqual(list(d), list(range(50, 150)))
def test_comparisons(self): def test_comparisons(self):
d = deque('xabc'); d.popleft() d = deque('xabc'); d.popleft()
@ -82,15 +82,15 @@ class TestBasic(unittest.TestCase):
def test_getitem(self): def test_getitem(self):
n = 200 n = 200
d = deque(xrange(n)) d = deque(range(n))
l = range(n) l = list(range(n))
for i in xrange(n): for i in range(n):
d.popleft() d.popleft()
l.pop(0) l.pop(0)
if random.random() < 0.5: if random.random() < 0.5:
d.append(i) d.append(i)
l.append(i) l.append(i)
for j in xrange(1-len(l), len(l)): for j in range(1-len(l), len(l)):
assert d[j] == l[j] assert d[j] == l[j]
d = deque('superman') d = deque('superman')
@ -102,22 +102,22 @@ class TestBasic(unittest.TestCase):
def test_setitem(self): def test_setitem(self):
n = 200 n = 200
d = deque(xrange(n)) d = deque(range(n))
for i in xrange(n): for i in range(n):
d[i] = 10 * i d[i] = 10 * i
self.assertEqual(list(d), [10*i for i in xrange(n)]) self.assertEqual(list(d), [10*i for i in range(n)])
l = list(d) l = list(d)
for i in xrange(1-n, 0, -1): for i in range(1-n, 0, -1):
d[i] = 7*i d[i] = 7*i
l[i] = 7*i l[i] = 7*i
self.assertEqual(list(d), l) self.assertEqual(list(d), l)
def test_delitem(self): def test_delitem(self):
n = 500 # O(n**2) test, don't make this too big n = 500 # O(n**2) test, don't make this too big
d = deque(xrange(n)) d = deque(range(n))
self.assertRaises(IndexError, d.__delitem__, -n-1) self.assertRaises(IndexError, d.__delitem__, -n-1)
self.assertRaises(IndexError, d.__delitem__, n) self.assertRaises(IndexError, d.__delitem__, n)
for i in xrange(n): for i in range(n):
self.assertEqual(len(d), n-i) self.assertEqual(len(d), n-i)
j = random.randrange(-len(d), len(d)) j = random.randrange(-len(d), len(d))
val = d[j] val = d[j]
@ -140,11 +140,11 @@ class TestBasic(unittest.TestCase):
d.rotate() # check default to 1 d.rotate() # check default to 1
self.assertEqual(tuple(d), s) self.assertEqual(tuple(d), s)
for i in xrange(n*3): for i in range(n*3):
d = deque(s) d = deque(s)
e = deque(d) e = deque(d)
d.rotate(i) # check vs. rot(1) n times d.rotate(i) # check vs. rot(1) n times
for j in xrange(i): for j in range(i):
e.rotate(1) e.rotate(1)
self.assertEqual(tuple(d), tuple(e)) self.assertEqual(tuple(d), tuple(e))
d.rotate(-i) # check that it works in reverse d.rotate(-i) # check that it works in reverse
@ -152,11 +152,11 @@ class TestBasic(unittest.TestCase):
e.rotate(n-i) # check that it wraps forward e.rotate(n-i) # check that it wraps forward
self.assertEqual(tuple(e), s) self.assertEqual(tuple(e), s)
for i in xrange(n*3): for i in range(n*3):
d = deque(s) d = deque(s)
e = deque(d) e = deque(d)
d.rotate(-i) d.rotate(-i)
for j in xrange(i): for j in range(i):
e.rotate(-1) # check vs. rot(-1) n times e.rotate(-1) # check vs. rot(-1) n times
self.assertEqual(tuple(d), tuple(e)) self.assertEqual(tuple(d), tuple(e))
d.rotate(i) # check that it works in reverse d.rotate(i) # check that it works in reverse
@ -168,7 +168,7 @@ class TestBasic(unittest.TestCase):
e = deque(s) e = deque(s)
e.rotate(BIG+17) # verify on long series of rotates e.rotate(BIG+17) # verify on long series of rotates
dr = d.rotate dr = d.rotate
for i in xrange(BIG+17): for i in range(BIG+17):
dr() dr()
self.assertEqual(tuple(d), tuple(e)) self.assertEqual(tuple(d), tuple(e))
@ -201,7 +201,7 @@ class TestBasic(unittest.TestCase):
self.assertRaises(IndexError, d.popleft) self.assertRaises(IndexError, d.popleft)
def test_clear(self): def test_clear(self):
d = deque(xrange(100)) d = deque(range(100))
self.assertEqual(len(d), 100) self.assertEqual(len(d), 100)
d.clear() d.clear()
self.assertEqual(len(d), 0) self.assertEqual(len(d), 0)
@ -234,14 +234,14 @@ class TestBasic(unittest.TestCase):
self.assertEqual(d, deque()) self.assertEqual(d, deque())
def test_repr(self): def test_repr(self):
d = deque(xrange(200)) d = deque(range(200))
e = eval(repr(d)) e = eval(repr(d))
self.assertEqual(list(d), list(e)) self.assertEqual(list(d), list(e))
d.append(d) d.append(d)
self.assert_('...' in repr(d)) self.assert_('...' in repr(d))
def test_print(self): def test_print(self):
d = deque(xrange(200)) d = deque(range(200))
d.append(d) d.append(d)
try: try:
fo = open(test_support.TESTFN, "wb") fo = open(test_support.TESTFN, "wb")
@ -262,33 +262,34 @@ class TestBasic(unittest.TestCase):
def test_long_steadystate_queue_popleft(self): def test_long_steadystate_queue_popleft(self):
for size in (0, 1, 2, 100, 1000): for size in (0, 1, 2, 100, 1000):
d = deque(xrange(size)) d = deque(range(size))
append, pop = d.append, d.popleft append, pop = d.append, d.popleft
for i in xrange(size, BIG): for i in range(size, BIG):
append(i) append(i)
x = pop() x = pop()
if x != i - size: if x != i - size:
self.assertEqual(x, i-size) self.assertEqual(x, i-size)
self.assertEqual(list(d), range(BIG-size, BIG)) self.assertEqual(list(d), list(range(BIG-size, BIG)))
def test_long_steadystate_queue_popright(self): def test_long_steadystate_queue_popright(self):
for size in (0, 1, 2, 100, 1000): for size in (0, 1, 2, 100, 1000):
d = deque(reversed(xrange(size))) d = deque(reversed(range(size)))
append, pop = d.appendleft, d.pop append, pop = d.appendleft, d.pop
for i in xrange(size, BIG): for i in range(size, BIG):
append(i) append(i)
x = pop() x = pop()
if x != i - size: if x != i - size:
self.assertEqual(x, i-size) self.assertEqual(x, i-size)
self.assertEqual(list(reversed(list(d))), range(BIG-size, BIG)) self.assertEqual(list(reversed(list(d))),
list(range(BIG-size, BIG)))
def test_big_queue_popleft(self): def test_big_queue_popleft(self):
pass pass
d = deque() d = deque()
append, pop = d.append, d.popleft append, pop = d.append, d.popleft
for i in xrange(BIG): for i in range(BIG):
append(i) append(i)
for i in xrange(BIG): for i in range(BIG):
x = pop() x = pop()
if x != i: if x != i:
self.assertEqual(x, i) self.assertEqual(x, i)
@ -296,9 +297,9 @@ class TestBasic(unittest.TestCase):
def test_big_queue_popright(self): def test_big_queue_popright(self):
d = deque() d = deque()
append, pop = d.appendleft, d.pop append, pop = d.appendleft, d.pop
for i in xrange(BIG): for i in range(BIG):
append(i) append(i)
for i in xrange(BIG): for i in range(BIG):
x = pop() x = pop()
if x != i: if x != i:
self.assertEqual(x, i) self.assertEqual(x, i)
@ -306,9 +307,9 @@ class TestBasic(unittest.TestCase):
def test_big_stack_right(self): def test_big_stack_right(self):
d = deque() d = deque()
append, pop = d.append, d.pop append, pop = d.append, d.pop
for i in xrange(BIG): for i in range(BIG):
append(i) append(i)
for i in reversed(xrange(BIG)): for i in reversed(range(BIG)):
x = pop() x = pop()
if x != i: if x != i:
self.assertEqual(x, i) self.assertEqual(x, i)
@ -317,22 +318,22 @@ class TestBasic(unittest.TestCase):
def test_big_stack_left(self): def test_big_stack_left(self):
d = deque() d = deque()
append, pop = d.appendleft, d.popleft append, pop = d.appendleft, d.popleft
for i in xrange(BIG): for i in range(BIG):
append(i) append(i)
for i in reversed(xrange(BIG)): for i in reversed(range(BIG)):
x = pop() x = pop()
if x != i: if x != i:
self.assertEqual(x, i) self.assertEqual(x, i)
self.assertEqual(len(d), 0) self.assertEqual(len(d), 0)
def test_roundtrip_iter_init(self): def test_roundtrip_iter_init(self):
d = deque(xrange(200)) d = deque(range(200))
e = deque(d) e = deque(d)
self.assertNotEqual(id(d), id(e)) self.assertNotEqual(id(d), id(e))
self.assertEqual(list(d), list(e)) self.assertEqual(list(d), list(e))
def test_pickle(self): def test_pickle(self):
d = deque(xrange(200)) d = deque(range(200))
for i in (0, 1, 2): for i in (0, 1, 2):
s = pickle.dumps(d, i) s = pickle.dumps(d, i)
e = pickle.loads(s) e = pickle.loads(s)
@ -366,7 +367,7 @@ class TestBasic(unittest.TestCase):
self.assertEqual(list(d), list(e)) self.assertEqual(list(d), list(e))
def test_reversed(self): def test_reversed(self):
for s in ('abcd', xrange(2000)): for s in ('abcd', range(2000)):
self.assertEqual(list(reversed(deque(s))), list(reversed(s))) self.assertEqual(list(reversed(deque(s))), list(reversed(s)))
def test_gc_doesnt_blowup(self): def test_gc_doesnt_blowup(self):
@ -374,14 +375,14 @@ class TestBasic(unittest.TestCase):
# This used to assert-fail in deque_traverse() under a debug # This used to assert-fail in deque_traverse() under a debug
# build, or run wild with a NULL pointer in a release build. # build, or run wild with a NULL pointer in a release build.
d = deque() d = deque()
for i in xrange(100): for i in range(100):
d.append(1) d.append(1)
gc.collect() gc.collect()
class TestVariousIteratorArgs(unittest.TestCase): class TestVariousIteratorArgs(unittest.TestCase):
def test_constructor(self): def test_constructor(self):
for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)): for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
for g in (seq_tests.Sequence, seq_tests.IterFunc, for g in (seq_tests.Sequence, seq_tests.IterFunc,
seq_tests.IterGen, seq_tests.IterFuncStop, seq_tests.IterGen, seq_tests.IterFuncStop,
seq_tests.itermulti, seq_tests.iterfunc): seq_tests.itermulti, seq_tests.iterfunc):
@ -412,23 +413,23 @@ class DequeWithBadIter(deque):
class TestSubclass(unittest.TestCase): class TestSubclass(unittest.TestCase):
def test_basics(self): def test_basics(self):
d = Deque(xrange(100)) d = Deque(range(100))
d.__init__(xrange(100, 200)) d.__init__(range(100, 200))
for i in xrange(200, 400): for i in range(200, 400):
d.append(i) d.append(i)
for i in reversed(xrange(-200, 0)): for i in reversed(range(-200, 0)):
d.appendleft(i) d.appendleft(i)
self.assertEqual(list(d), range(-200, 400)) self.assertEqual(list(d), list(range(-200, 400)))
self.assertEqual(len(d), 600) self.assertEqual(len(d), 600)
left = [d.popleft() for i in xrange(250)] left = [d.popleft() for i in range(250)]
self.assertEqual(left, range(-200, 50)) self.assertEqual(left, list(range(-200, 50)))
self.assertEqual(list(d), range(50, 400)) self.assertEqual(list(d), list(range(50, 400)))
right = [d.pop() for i in xrange(250)] right = [d.pop() for i in range(250)]
right.reverse() right.reverse()
self.assertEqual(right, range(150, 400)) self.assertEqual(right, list(range(150, 400)))
self.assertEqual(list(d), range(50, 150)) self.assertEqual(list(d), list(range(50, 150)))
d.clear() d.clear()
self.assertEqual(len(d), 0) self.assertEqual(len(d), 0)
@ -618,7 +619,7 @@ def test_main(verbose=None):
if verbose and hasattr(sys, "gettotalrefcount"): if verbose and hasattr(sys, "gettotalrefcount"):
import gc import gc
counts = [None] * 5 counts = [None] * 5
for i in xrange(len(counts)): for i in range(len(counts)):
test_support.run_unittest(*test_classes) test_support.run_unittest(*test_classes)
gc.collect() gc.collect()
counts[i] = sys.gettotalrefcount() counts[i] = sys.gettotalrefcount()

View file

@ -1181,7 +1181,7 @@ def slots():
return 0 return 0
g = G() g = G()
orig_objects = len(gc.get_objects()) orig_objects = len(gc.get_objects())
for i in xrange(10): for i in range(10):
g==g g==g
new_objects = len(gc.get_objects()) new_objects = len(gc.get_objects())
vereq(orig_objects, new_objects) vereq(orig_objects, new_objects)
@ -2363,24 +2363,24 @@ def inherits():
class sublist(list): class sublist(list):
pass pass
a = sublist(range(5)) a = sublist(range(5))
vereq(a, range(5)) vereq(a, list(range(5)))
a.append("hello") a.append("hello")
vereq(a, range(5) + ["hello"]) vereq(a, list(range(5)) + ["hello"])
a[5] = 5 a[5] = 5
vereq(a, range(6)) vereq(a, list(range(6)))
a.extend(range(6, 20)) a.extend(range(6, 20))
vereq(a, range(20)) vereq(a, list(range(20)))
a[-5:] = [] a[-5:] = []
vereq(a, range(15)) vereq(a, list(range(15)))
del a[10:15] del a[10:15]
vereq(len(a), 10) vereq(len(a), 10)
vereq(a, range(10)) vereq(a, list(range(10)))
vereq(list(a), range(10)) vereq(list(a), list(range(10)))
vereq(a[0], 0) vereq(a[0], 0)
vereq(a[9], 9) vereq(a[9], 9)
vereq(a[-10], 0) vereq(a[-10], 0)
vereq(a[-1], 9) vereq(a[-1], 9)
vereq(a[:5], range(5)) vereq(a[:5], list(range(5)))
class CountedInput(file): class CountedInput(file):
"""Counts lines read by self.readline(). """Counts lines read by self.readline().
@ -2412,7 +2412,7 @@ def inherits():
f.writelines(lines) f.writelines(lines)
f.close() f.close()
f = CountedInput(TESTFN) f = CountedInput(TESTFN)
for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]): for (i, expected) in zip(list(range(1, 5)) + [4], lines + 2 * [""]):
got = f.readline() got = f.readline()
vereq(expected, got) vereq(expected, got)
vereq(f.lineno, i) vereq(f.lineno, i)
@ -2439,7 +2439,7 @@ def keywords():
vereq(str(object=500), '500') vereq(str(object=500), '500')
vereq(str(string='abc', errors='strict'), 'abc') vereq(str(string='abc', errors='strict'), 'abc')
vereq(tuple(sequence=range(3)), (0, 1, 2)) vereq(tuple(sequence=range(3)), (0, 1, 2))
vereq(list(sequence=(0, 1, 2)), range(3)) vereq(list(sequence=(0, 1, 2)), list(range(3)))
# note: as of Python 2.3, dict() no longer has an "items" keyword arg # note: as of Python 2.3, dict() no longer has an "items" keyword arg
for constructor in (int, float, int, complex, str, str, for constructor in (int, float, int, complex, str, str,
@ -3502,7 +3502,7 @@ def slottrash():
def __init__(self, x): def __init__(self, x):
self.x = x self.x = x
o = None o = None
for i in xrange(50000): for i in range(50000):
o = trash(o) o = trash(o)
del o del o
@ -3959,7 +3959,7 @@ def weakref_segfault():
def wrapper_segfault(): def wrapper_segfault():
# SF 927248: deeply nested wrappers could cause stack overflow # SF 927248: deeply nested wrappers could cause stack overflow
f = lambda:None f = lambda:None
for i in xrange(1000000): for i in range(1000000):
f = f.__call__ f = f.__call__
f = None f = None

View file

@ -144,12 +144,12 @@ class DisTests(unittest.TestCase):
return namespace['foo'] return namespace['foo']
# Test all small ranges # Test all small ranges
for i in xrange(1, 300): for i in range(1, 300):
expected = _BIG_LINENO_FORMAT % (i + 2) expected = _BIG_LINENO_FORMAT % (i + 2)
self.do_disassembly_test(func(i), expected) self.do_disassembly_test(func(i), expected)
# Test some larger ranges too # Test some larger ranges too
for i in xrange(300, 5000, 10): for i in range(300, 5000, 10):
expected = _BIG_LINENO_FORMAT % (i + 2) expected = _BIG_LINENO_FORMAT % (i + 2)
self.do_disassembly_test(func(i), expected) self.do_disassembly_test(func(i), expected)

View file

@ -34,7 +34,7 @@ class SampleClass:
>>> sc = SampleClass(3) >>> sc = SampleClass(3)
>>> for i in range(10): >>> for i in range(10):
... sc = sc.double() ... sc = sc.double()
... print(sc.get(), end=' ') ... print(' ', sc.get(), sep='', end='')
6 12 24 48 96 192 384 768 1536 3072 6 12 24 48 96 192 384 768 1536 3072
""" """
def __init__(self, val): def __init__(self, val):
@ -996,7 +996,7 @@ treated as equal:
(0, 1) (0, 1)
An example from the docs: An example from the docs:
>>> print(range(20)) #doctest: +NORMALIZE_WHITESPACE >>> print(list(range(20))) #doctest: +NORMALIZE_WHITESPACE
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17, 18, 19] 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
@ -1004,7 +1004,7 @@ The ELLIPSIS flag causes ellipsis marker ("...") in the expected
output to match any substring in the actual output: output to match any substring in the actual output:
>>> def f(x): >>> def f(x):
... '>>> print(range(15))\n[0, 1, 2, ..., 14]\n' ... '>>> print(list(range(15)))\n[0, 1, 2, ..., 14]\n'
>>> # Without the flag: >>> # Without the flag:
>>> test = doctest.DocTestFinder().find(f)[0] >>> test = doctest.DocTestFinder().find(f)[0]
@ -1013,7 +1013,7 @@ output to match any substring in the actual output:
********************************************************************** **********************************************************************
File ..., line 2, in f File ..., line 2, in f
Failed example: Failed example:
print(range(15)) print(list(range(15)))
Expected: Expected:
[0, 1, 2, ..., 14] [0, 1, 2, ..., 14]
Got: Got:
@ -1044,10 +1044,10 @@ output to match any substring in the actual output:
Examples from the docs: Examples from the docs:
>>> print(range(20)) # doctest:+ELLIPSIS >>> print(list(range(20))) # doctest:+ELLIPSIS
[0, 1, ..., 18, 19] [0, 1, ..., 18, 19]
>>> print(range(20)) # doctest: +ELLIPSIS >>> print(list(range(20))) # doctest: +ELLIPSIS
... # doctest: +NORMALIZE_WHITESPACE ... # doctest: +NORMALIZE_WHITESPACE
[0, 1, ..., 18, 19] [0, 1, ..., 18, 19]
@ -1302,10 +1302,10 @@ single example. To turn an option on for an example, follow that
example with a comment of the form ``# doctest: +OPTION``: example with a comment of the form ``# doctest: +OPTION``:
>>> def f(x): r''' >>> def f(x): r'''
... >>> print(range(10)) # should fail: no ellipsis ... >>> print(list(range(10))) # should fail: no ellipsis
... [0, 1, ..., 9] ... [0, 1, ..., 9]
... ...
... >>> print(range(10)) # doctest: +ELLIPSIS ... >>> print(list(range(10))) # doctest: +ELLIPSIS
... [0, 1, ..., 9] ... [0, 1, ..., 9]
... ''' ... '''
>>> test = doctest.DocTestFinder().find(f)[0] >>> test = doctest.DocTestFinder().find(f)[0]
@ -1314,7 +1314,7 @@ example with a comment of the form ``# doctest: +OPTION``:
********************************************************************** **********************************************************************
File ..., line 2, in f File ..., line 2, in f
Failed example: Failed example:
print(range(10)) # should fail: no ellipsis print(list(range(10))) # should fail: no ellipsis
Expected: Expected:
[0, 1, ..., 9] [0, 1, ..., 9]
Got: Got:
@ -1325,11 +1325,11 @@ To turn an option off for an example, follow that example with a
comment of the form ``# doctest: -OPTION``: comment of the form ``# doctest: -OPTION``:
>>> def f(x): r''' >>> def f(x): r'''
... >>> print(range(10)) ... >>> print(list(range(10)))
... [0, 1, ..., 9] ... [0, 1, ..., 9]
... ...
... >>> # should fail: no ellipsis ... >>> # should fail: no ellipsis
... >>> print(range(10)) # doctest: -ELLIPSIS ... >>> print(list(range(10))) # doctest: -ELLIPSIS
... [0, 1, ..., 9] ... [0, 1, ..., 9]
... ''' ... '''
>>> test = doctest.DocTestFinder().find(f)[0] >>> test = doctest.DocTestFinder().find(f)[0]
@ -1339,7 +1339,7 @@ comment of the form ``# doctest: -OPTION``:
********************************************************************** **********************************************************************
File ..., line 6, in f File ..., line 6, in f
Failed example: Failed example:
print(range(10)) # doctest: -ELLIPSIS print(list(range(10))) # doctest: -ELLIPSIS
Expected: Expected:
[0, 1, ..., 9] [0, 1, ..., 9]
Got: Got:
@ -1350,13 +1350,13 @@ Option directives affect only the example that they appear with; they
do not change the options for surrounding examples: do not change the options for surrounding examples:
>>> def f(x): r''' >>> def f(x): r'''
... >>> print(range(10)) # Should fail: no ellipsis ... >>> print(list(range(10))) # Should fail: no ellipsis
... [0, 1, ..., 9] ... [0, 1, ..., 9]
... ...
... >>> print(range(10)) # doctest: +ELLIPSIS ... >>> print(list(range(10))) # doctest: +ELLIPSIS
... [0, 1, ..., 9] ... [0, 1, ..., 9]
... ...
... >>> print(range(10)) # Should fail: no ellipsis ... >>> print(list(range(10))) # Should fail: no ellipsis
... [0, 1, ..., 9] ... [0, 1, ..., 9]
... ''' ... '''
>>> test = doctest.DocTestFinder().find(f)[0] >>> test = doctest.DocTestFinder().find(f)[0]
@ -1365,7 +1365,7 @@ do not change the options for surrounding examples:
********************************************************************** **********************************************************************
File ..., line 2, in f File ..., line 2, in f
Failed example: Failed example:
print(range(10)) # Should fail: no ellipsis print(list(range(10))) # Should fail: no ellipsis
Expected: Expected:
[0, 1, ..., 9] [0, 1, ..., 9]
Got: Got:
@ -1373,7 +1373,7 @@ do not change the options for surrounding examples:
********************************************************************** **********************************************************************
File ..., line 8, in f File ..., line 8, in f
Failed example: Failed example:
print(range(10)) # Should fail: no ellipsis print(list(range(10))) # Should fail: no ellipsis
Expected: Expected:
[0, 1, ..., 9] [0, 1, ..., 9]
Got: Got:
@ -1384,9 +1384,9 @@ Multiple options may be modified by a single option directive. They
may be separated by whitespace, commas, or both: may be separated by whitespace, commas, or both:
>>> def f(x): r''' >>> def f(x): r'''
... >>> print(range(10)) # Should fail ... >>> print(list(range(10))) # Should fail
... [0, 1, ..., 9] ... [0, 1, ..., 9]
... >>> print(range(10)) # Should succeed ... >>> print(list(range(10))) # Should succeed
... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
... [0, 1, ..., 9] ... [0, 1, ..., 9]
... ''' ... '''
@ -1396,7 +1396,7 @@ may be separated by whitespace, commas, or both:
********************************************************************** **********************************************************************
File ..., line 2, in f File ..., line 2, in f
Failed example: Failed example:
print(range(10)) # Should fail print(list(range(10))) # Should fail
Expected: Expected:
[0, 1, ..., 9] [0, 1, ..., 9]
Got: Got:
@ -1404,9 +1404,9 @@ may be separated by whitespace, commas, or both:
(1, 2) (1, 2)
>>> def f(x): r''' >>> def f(x): r'''
... >>> print(range(10)) # Should fail ... >>> print(list(range(10))) # Should fail
... [0, 1, ..., 9] ... [0, 1, ..., 9]
... >>> print(range(10)) # Should succeed ... >>> print(list(range(10))) # Should succeed
... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
... [0, 1, ..., 9] ... [0, 1, ..., 9]
... ''' ... '''
@ -1416,7 +1416,7 @@ may be separated by whitespace, commas, or both:
********************************************************************** **********************************************************************
File ..., line 2, in f File ..., line 2, in f
Failed example: Failed example:
print(range(10)) # Should fail print(list(range(10))) # Should fail
Expected: Expected:
[0, 1, ..., 9] [0, 1, ..., 9]
Got: Got:
@ -1424,9 +1424,9 @@ may be separated by whitespace, commas, or both:
(1, 2) (1, 2)
>>> def f(x): r''' >>> def f(x): r'''
... >>> print(range(10)) # Should fail ... >>> print(list(range(10))) # Should fail
... [0, 1, ..., 9] ... [0, 1, ..., 9]
... >>> print(range(10)) # Should succeed ... >>> print(list(range(10))) # Should succeed
... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
... [0, 1, ..., 9] ... [0, 1, ..., 9]
... ''' ... '''
@ -1436,7 +1436,7 @@ may be separated by whitespace, commas, or both:
********************************************************************** **********************************************************************
File ..., line 2, in f File ..., line 2, in f
Failed example: Failed example:
print(range(10)) # Should fail print(list(range(10))) # Should fail
Expected: Expected:
[0, 1, ..., 9] [0, 1, ..., 9]
Got: Got:
@ -1447,7 +1447,7 @@ The option directive may be put on the line following the source, as
long as a continuation prompt is used: long as a continuation prompt is used:
>>> def f(x): r''' >>> def f(x): r'''
... >>> print(range(10)) ... >>> print(list(range(10)))
... ... # doctest: +ELLIPSIS ... ... # doctest: +ELLIPSIS
... [0, 1, ..., 9] ... [0, 1, ..., 9]
... ''' ... '''
@ -1460,11 +1460,11 @@ at the end of any line:
>>> def f(x): r''' >>> def f(x): r'''
... >>> for x in range(10): # doctest: +ELLIPSIS ... >>> for x in range(10): # doctest: +ELLIPSIS
... ... print(x, end=' ') ... ... print(' ', x, end='', sep='')
... 0 1 2 ... 9 ... 0 1 2 ... 9
... ...
... >>> for x in range(10): ... >>> for x in range(10):
... ... print(x, end=' ') # doctest: +ELLIPSIS ... ... print(' ', x, end='', sep='') # doctest: +ELLIPSIS
... 0 1 2 ... 9 ... 0 1 2 ... 9
... ''' ... '''
>>> test = doctest.DocTestFinder().find(f)[0] >>> test = doctest.DocTestFinder().find(f)[0]

View file

@ -153,7 +153,7 @@ class ThreadTests(unittest.TestCase):
print() print()
print("*** Testing multiple thread creation "\ print("*** Testing multiple thread creation "\
"(will take approx. %s to %s sec.) ***" % (DELAY, thread_count)) "(will take approx. %s to %s sec.) ***" % (DELAY, thread_count))
for count in xrange(thread_count): for count in range(thread_count):
if DELAY: if DELAY:
local_delay = round(random.random(), 1) local_delay = round(random.random(), 1)
else: else:

View file

@ -134,18 +134,18 @@ class TestReversed(unittest.TestCase):
raise StopIteration raise StopIteration
def __len__(self): def __len__(self):
return 5 return 5
for data in 'abc', range(5), tuple(enumerate('abc')), A(), xrange(1,17,5): for data in 'abc', range(5), tuple(enumerate('abc')), A(), range(1,17,5):
self.assertEqual(list(data)[::-1], list(reversed(data))) self.assertEqual(list(data)[::-1], list(reversed(data)))
self.assertRaises(TypeError, reversed, {}) self.assertRaises(TypeError, reversed, {})
def test_xrange_optimization(self): def test_range_optimization(self):
x = xrange(1) x = range(1)
self.assertEqual(type(reversed(x)), type(iter(x))) self.assertEqual(type(reversed(x)), type(iter(x)))
def test_len(self): def test_len(self):
# This is an implementation detail, not an interface requirement # This is an implementation detail, not an interface requirement
from test.test_iterlen import len from test.test_iterlen import len
for s in ('hello', tuple('hello'), list('hello'), xrange(5)): for s in ('hello', tuple('hello'), list('hello'), range(5)):
self.assertEqual(len(reversed(s)), len(s)) self.assertEqual(len(reversed(s)), len(s))
r = reversed(s) r = reversed(s)
list(r) list(r)
@ -205,7 +205,7 @@ def test_main(verbose=None):
import sys import sys
if verbose and hasattr(sys, "gettotalrefcount"): if verbose and hasattr(sys, "gettotalrefcount"):
counts = [None] * 5 counts = [None] * 5
for i in xrange(len(counts)): for i in range(len(counts)):
test_support.run_unittest(*testclasses) test_support.run_unittest(*testclasses)
counts[i] = sys.gettotalrefcount() counts[i] = sys.gettotalrefcount()
print(counts) print(counts)

View file

@ -352,7 +352,7 @@ def test_main(verbose=None):
if verbose and hasattr(sys, "gettotalrefcount"): if verbose and hasattr(sys, "gettotalrefcount"):
import gc import gc
counts = [None] * 5 counts = [None] * 5
for i in xrange(len(counts)): for i in range(len(counts)):
test_support.run_unittest(*test_classes) test_support.run_unittest(*test_classes)
gc.collect() gc.collect()
counts[i] = sys.gettotalrefcount() counts[i] = sys.gettotalrefcount()

View file

@ -399,7 +399,7 @@ class GCTests(unittest.TestCase):
got = gc.get_referents([1, 2], {3: 4}, (0, 0, 0)) got = gc.get_referents([1, 2], {3: 4}, (0, 0, 0))
got.sort() got.sort()
self.assertEqual(got, [0, 0] + range(5)) self.assertEqual(got, [0, 0] + list(range(5)))
self.assertEqual(gc.get_referents(1, 'a', 4j), []) self.assertEqual(gc.get_referents(1, 'a', 4j), [])

View file

@ -343,7 +343,7 @@ Next one was posted to c.l.py.
... for c in gcomb(rest, k): ... for c in gcomb(rest, k):
... yield c ... yield c
>>> seq = range(1, 5) >>> seq = list(range(1, 5))
>>> for k in range(len(seq) + 2): >>> for k in range(len(seq) + 2):
... print("%d-combs of %s:" % (k, seq)) ... print("%d-combs of %s:" % (k, seq))
... for c in gcomb(seq, k): ... for c in gcomb(seq, k):

View file

@ -59,16 +59,16 @@ Does it stay stopped?
Test running gen when defining function is out of scope Test running gen when defining function is out of scope
>>> def f(n): >>> def f(n):
... return (i*i for i in xrange(n)) ... return (i*i for i in range(n))
>>> list(f(10)) >>> list(f(10))
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81] [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> def f(n): >>> def f(n):
... return ((i,j) for i in xrange(3) for j in xrange(n)) ... return ((i,j) for i in range(3) for j in range(n))
>>> list(f(4)) >>> list(f(4))
[(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3)] [(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3)]
>>> def f(n): >>> def f(n):
... return ((i,j) for i in xrange(3) for j in xrange(4) if j in xrange(n)) ... return ((i,j) for i in range(3) for j in range(4) if j in range(n))
>>> list(f(4)) >>> list(f(4))
[(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3)] [(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3)]
>>> list(f(2)) >>> list(f(2))
@ -77,21 +77,21 @@ Test running gen when defining function is out of scope
Verify that parenthesis are required in a statement Verify that parenthesis are required in a statement
>>> def f(n): >>> def f(n):
... return i*i for i in xrange(n) ... return i*i for i in range(n)
Traceback (most recent call last): Traceback (most recent call last):
... ...
SyntaxError: invalid syntax SyntaxError: invalid syntax
Verify that parenthesis are required when used as a keyword argument value Verify that parenthesis are required when used as a keyword argument value
>>> dict(a = i for i in xrange(10)) >>> dict(a = i for i in range(10))
Traceback (most recent call last): Traceback (most recent call last):
... ...
SyntaxError: invalid syntax SyntaxError: invalid syntax
Verify that parenthesis are required when used as a keyword argument value Verify that parenthesis are required when used as a keyword argument value
>>> dict(a = (i for i in xrange(10))) #doctest: +ELLIPSIS >>> dict(a = (i for i in range(10))) #doctest: +ELLIPSIS
{'a': <generator object at ...>} {'a': <generator object at ...>}
Verify early binding for the outermost for-expression Verify early binding for the outermost for-expression
@ -128,7 +128,7 @@ Verify late binding for the innermost for-expression
Verify re-use of tuples (a side benefit of using genexps over listcomps) Verify re-use of tuples (a side benefit of using genexps over listcomps)
>>> tupleids = map(id, ((i,i) for i in xrange(10))) >>> tupleids = map(id, ((i,i) for i in range(10)))
>>> int(max(tupleids) - min(tupleids)) >>> int(max(tupleids) - min(tupleids))
0 0
@ -149,7 +149,7 @@ Verify that syntax error's are raised for genexps used as lvalues
Make a generator that acts like range() Make a generator that acts like range()
>>> yrange = lambda n: (i for i in xrange(n)) >>> yrange = lambda n: (i for i in range(n))
>>> list(yrange(10)) >>> list(yrange(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
@ -181,14 +181,14 @@ Generators can call other generators:
Verify that a gen exp cannot be resumed while it is actively running: Verify that a gen exp cannot be resumed while it is actively running:
>>> g = (next(me) for i in xrange(10)) >>> g = (next(me) for i in range(10))
>>> me = g >>> me = g
>>> next(me) >>> next(me)
Traceback (most recent call last): Traceback (most recent call last):
File "<pyshell#30>", line 1, in -toplevel- File "<pyshell#30>", line 1, in -toplevel-
next(me) next(me)
File "<pyshell#28>", line 1, in <generator expression> File "<pyshell#28>", line 1, in <generator expression>
g = (next(me) for i in xrange(10)) g = (next(me) for i in range(10))
ValueError: generator already executing ValueError: generator already executing
Verify exception propagation Verify exception propagation
@ -211,7 +211,7 @@ Verify exception propagation
Make sure that None is a valid return value Make sure that None is a valid return value
>>> list(None for i in xrange(10)) >>> list(None for i in range(10))
[None, None, None, None, None, None, None, None, None, None] [None, None, None, None, None, None, None, None, None, None]
Check that generator attributes are present Check that generator attributes are present
@ -270,7 +270,7 @@ def test_main(verbose=None):
if verbose and hasattr(sys, "gettotalrefcount"): if verbose and hasattr(sys, "gettotalrefcount"):
import gc import gc
counts = [None] * 5 counts = [None] * 5
for i in xrange(len(counts)): for i in range(len(counts)):
test_support.run_doctest(test_genexps, verbose) test_support.run_doctest(test_genexps, verbose)
gc.collect() gc.collect()
counts[i] = sys.gettotalrefcount() counts[i] = sys.gettotalrefcount()

View file

@ -55,7 +55,7 @@ class GroupDatabaseTestCase(unittest.TestCase):
fakename = allnames[namei] fakename = allnames[namei]
while fakename in bynames: while fakename in bynames:
chars = map(None, fakename) chars = map(None, fakename)
for i in xrange(len(chars)): for i in range(len(chars)):
if chars[i] == 'z': if chars[i] == 'z':
chars[i] = 'A' chars[i] = 'A'
break break

View file

@ -90,7 +90,7 @@ class TestHeap(unittest.TestCase):
def test_heapsort(self): def test_heapsort(self):
# Exercise everything with repeated heapsort checks # Exercise everything with repeated heapsort checks
for trial in xrange(100): for trial in range(100):
size = random.randrange(50) size = random.randrange(50)
data = [random.randrange(25) for i in range(size)] data = [random.randrange(25) for i in range(size)]
if trial & 1: # Half of the time, use heapify if trial & 1: # Half of the time, use heapify
@ -105,7 +105,7 @@ class TestHeap(unittest.TestCase):
def test_merge(self): def test_merge(self):
inputs = [] inputs = []
for i in xrange(random.randrange(5)): for i in range(random.randrange(5)):
row = sorted(random.randrange(1000) for j in range(random.randrange(10))) row = sorted(random.randrange(1000) for j in range(random.randrange(10)))
inputs.append(row) inputs.append(row)
self.assertEqual(sorted(chain(*inputs)), list(merge(*inputs))) self.assertEqual(sorted(chain(*inputs)), list(merge(*inputs)))
@ -277,7 +277,7 @@ class TestErrorHandling(unittest.TestCase):
def test_iterable_args(self): def test_iterable_args(self):
for f in (nlargest, nsmallest): for f in (nlargest, nsmallest):
for s in ("123", "", range(1000), (1, 1.2), xrange(2000,2200,5)): for s in ("123", "", range(1000), (1, 1.2), range(2000,2200,5)):
for g in (G, I, Ig, L, R): for g in (G, I, Ig, L, R):
self.assertEqual(f(2, g(s)), f(2,s)) self.assertEqual(f(2, g(s)), f(2,s))
self.assertEqual(f(2, S(s)), []) self.assertEqual(f(2, S(s)), [])
@ -300,7 +300,7 @@ def test_main(verbose=None):
if verbose and hasattr(sys, "gettotalrefcount"): if verbose and hasattr(sys, "gettotalrefcount"):
import gc import gc
counts = [None] * 5 counts = [None] * 5
for i in xrange(len(counts)): for i in range(len(counts)):
test_support.run_unittest(*test_classes) test_support.run_unittest(*test_classes)
gc.collect() gc.collect()
counts[i] = sys.gettotalrefcount() counts[i] = sys.gettotalrefcount()

View file

@ -49,7 +49,7 @@ class BaseTestCase(unittest.TestCase):
self.assertEqual(self.n.__index__(), 5) self.assertEqual(self.n.__index__(), 5)
def test_subclasses(self): def test_subclasses(self):
r = range(10) r = list(range(10))
self.assertEqual(r[TrapInt(5):TrapInt(10)], r[5:10]) self.assertEqual(r[TrapInt(5):TrapInt(10)], r[5:10])
self.assertEqual(r[TrapLong(5):TrapLong(10)], r[5:10]) self.assertEqual(r[TrapLong(5):TrapLong(10)], r[5:10])
self.assertEqual(slice(TrapInt()).indices(0), (0,0,1)) self.assertEqual(slice(TrapInt()).indices(0), (0,0,1))
@ -164,14 +164,6 @@ class UnicodeTestCase(SeqTestCase):
seq = "this is a test" seq = "this is a test"
class XRangeTestCase(unittest.TestCase):
def test_xrange(self):
n = newstyle()
n.ind = 5
self.assertEqual(xrange(1, 20)[n], 6)
self.assertEqual(xrange(1, 20).__getitem__(n), 6)
class OverflowTestCase(unittest.TestCase): class OverflowTestCase(unittest.TestCase):
def setUp(self): def setUp(self):
@ -215,7 +207,6 @@ def test_main():
TupleTestCase, TupleTestCase,
StringTestCase, StringTestCase,
UnicodeTestCase, UnicodeTestCase,
XRangeTestCase,
OverflowTestCase, OverflowTestCase,
) )

View file

@ -546,7 +546,7 @@ class TextIOWrapperTest(unittest.TestCase):
wlines = [] wlines = []
for size in (0, 1, 2, 3, 4, 5, 30, 31, 32, 33, 62, 63, 64, 65, 1000): for size in (0, 1, 2, 3, 4, 5, 30, 31, 32, 33, 62, 63, 64, 65, 1000):
chars = [] chars = []
for i in xrange(size): for i in range(size):
chars.append(sample[i % len(sample)]) chars.append(sample[i % len(sample)])
line = "".join(chars) + "\n" line = "".join(chars) + "\n"
wlines.append((f.tell(), line)) wlines.append((f.tell(), line))

View file

@ -259,7 +259,7 @@ def blowstack(fxn, arg, compare_to):
# Make sure that calling isinstance with a deeply nested tuple for its # Make sure that calling isinstance with a deeply nested tuple for its
# argument will raise RuntimeError eventually. # argument will raise RuntimeError eventually.
tuple_arg = (compare_to,) tuple_arg = (compare_to,)
for cnt in xrange(sys.getrecursionlimit()+5): for cnt in range(sys.getrecursionlimit()+5):
tuple_arg = (tuple_arg,) tuple_arg = (tuple_arg,)
fxn(arg, tuple_arg) fxn(arg, tuple_arg)

View file

@ -68,18 +68,18 @@ class TestCase(unittest.TestCase):
# Test basic use of iter() function # Test basic use of iter() function
def test_iter_basic(self): def test_iter_basic(self):
self.check_iterator(iter(range(10)), range(10)) self.check_iterator(iter(range(10)), list(range(10)))
# Test that iter(iter(x)) is the same as iter(x) # Test that iter(iter(x)) is the same as iter(x)
def test_iter_idempotency(self): def test_iter_idempotency(self):
seq = range(10) seq = list(range(10))
it = iter(seq) it = iter(seq)
it2 = iter(it) it2 = iter(it)
self.assert_(it is it2) self.assert_(it is it2)
# Test that for loops over iterators work # Test that for loops over iterators work
def test_iter_for_loop(self): def test_iter_for_loop(self):
self.check_for_loop(iter(range(10)), range(10)) self.check_for_loop(iter(range(10)), list(range(10)))
# Test several independent iterators over the same list # Test several independent iterators over the same list
def test_iter_independence(self): def test_iter_independence(self):
@ -106,19 +106,19 @@ class TestCase(unittest.TestCase):
# Test a class with __iter__ in a for loop # Test a class with __iter__ in a for loop
def test_iter_class_for(self): def test_iter_class_for(self):
self.check_for_loop(IteratingSequenceClass(10), range(10)) self.check_for_loop(IteratingSequenceClass(10), list(range(10)))
# Test a class with __iter__ with explicit iter() # Test a class with __iter__ with explicit iter()
def test_iter_class_iter(self): def test_iter_class_iter(self):
self.check_iterator(iter(IteratingSequenceClass(10)), range(10)) self.check_iterator(iter(IteratingSequenceClass(10)), list(range(10)))
# Test for loop on a sequence class without __iter__ # Test for loop on a sequence class without __iter__
def test_seq_class_for(self): def test_seq_class_for(self):
self.check_for_loop(SequenceClass(10), range(10)) self.check_for_loop(SequenceClass(10), list(range(10)))
# Test iter() on a sequence class without __iter__ # Test iter() on a sequence class without __iter__
def test_seq_class_iter(self): def test_seq_class_iter(self):
self.check_iterator(iter(SequenceClass(10)), range(10)) self.check_iterator(iter(SequenceClass(10)), list(range(10)))
# Test two-argument iter() with callable instance # Test two-argument iter() with callable instance
def test_iter_callable(self): def test_iter_callable(self):
@ -131,7 +131,7 @@ class TestCase(unittest.TestCase):
if i > 100: if i > 100:
raise IndexError # Emergency stop raise IndexError # Emergency stop
return i return i
self.check_iterator(iter(C(), 10), range(10)) self.check_iterator(iter(C(), 10), list(range(10)))
# Test two-argument iter() with function # Test two-argument iter() with function
def test_iter_function(self): def test_iter_function(self):
@ -139,7 +139,7 @@ class TestCase(unittest.TestCase):
i = state[0] i = state[0]
state[0] = i+1 state[0] = i+1
return i return i
self.check_iterator(iter(spam, 10), range(10)) self.check_iterator(iter(spam, 10), list(range(10)))
# Test two-argument iter() with function that raises StopIteration # Test two-argument iter() with function that raises StopIteration
def test_iter_function_stop(self): def test_iter_function_stop(self):
@ -149,7 +149,7 @@ class TestCase(unittest.TestCase):
raise StopIteration raise StopIteration
state[0] = i+1 state[0] = i+1
return i return i
self.check_iterator(iter(spam, 20), range(10)) self.check_iterator(iter(spam, 20), list(range(10)))
# Test exception propagation through function iterator # Test exception propagation through function iterator
def test_exception_function(self): def test_exception_function(self):
@ -164,7 +164,7 @@ class TestCase(unittest.TestCase):
for x in iter(spam, 20): for x in iter(spam, 20):
res.append(x) res.append(x)
except RuntimeError: except RuntimeError:
self.assertEqual(res, range(10)) self.assertEqual(res, list(range(10)))
else: else:
self.fail("should have raised RuntimeError") self.fail("should have raised RuntimeError")
@ -180,7 +180,7 @@ class TestCase(unittest.TestCase):
for x in MySequenceClass(20): for x in MySequenceClass(20):
res.append(x) res.append(x)
except RuntimeError: except RuntimeError:
self.assertEqual(res, range(10)) self.assertEqual(res, list(range(10)))
else: else:
self.fail("should have raised RuntimeError") self.fail("should have raised RuntimeError")
@ -191,11 +191,11 @@ class TestCase(unittest.TestCase):
if i == 10: if i == 10:
raise StopIteration raise StopIteration
return SequenceClass.__getitem__(self, i) return SequenceClass.__getitem__(self, i)
self.check_for_loop(MySequenceClass(20), range(10)) self.check_for_loop(MySequenceClass(20), list(range(10)))
# Test a big range # Test a big range
def test_iter_big_range(self): def test_iter_big_range(self):
self.check_for_loop(iter(range(10000)), range(10000)) self.check_for_loop(iter(range(10000)), list(range(10000)))
# Test an empty list # Test an empty list
def test_iter_empty(self): def test_iter_empty(self):
@ -203,11 +203,11 @@ class TestCase(unittest.TestCase):
# Test a tuple # Test a tuple
def test_iter_tuple(self): def test_iter_tuple(self):
self.check_for_loop(iter((0,1,2,3,4,5,6,7,8,9)), range(10)) self.check_for_loop(iter((0,1,2,3,4,5,6,7,8,9)), list(range(10)))
# Test an xrange # Test a range
def test_iter_xrange(self): def test_iter_range(self):
self.check_for_loop(iter(xrange(10)), range(10)) self.check_for_loop(iter(range(10)), list(range(10)))
# Test a string # Test a string
def test_iter_string(self): def test_iter_string(self):
@ -248,10 +248,9 @@ class TestCase(unittest.TestCase):
# Test list()'s use of iterators. # Test list()'s use of iterators.
def test_builtin_list(self): def test_builtin_list(self):
self.assertEqual(list(SequenceClass(5)), range(5)) self.assertEqual(list(SequenceClass(5)), list(range(5)))
self.assertEqual(list(SequenceClass(0)), []) self.assertEqual(list(SequenceClass(0)), [])
self.assertEqual(list(()), []) self.assertEqual(list(()), [])
self.assertEqual(list(range(10, -1, -1)), range(10, -1, -1))
d = {"one": 1, "two": 2, "three": 3} d = {"one": 1, "two": 2, "three": 3}
self.assertEqual(list(d), list(d.keys())) self.assertEqual(list(d), list(d.keys()))
@ -313,7 +312,7 @@ class TestCase(unittest.TestCase):
# Test filter()'s use of iterators. # Test filter()'s use of iterators.
def test_builtin_filter(self): def test_builtin_filter(self):
self.assertEqual(filter(None, SequenceClass(5)), range(1, 5)) self.assertEqual(filter(None, SequenceClass(5)), list(range(1, 5)))
self.assertEqual(filter(None, SequenceClass(0)), []) self.assertEqual(filter(None, SequenceClass(0)), [])
self.assertEqual(filter(None, ()), ()) self.assertEqual(filter(None, ()), ())
self.assertEqual(filter(None, "abc"), "abc") self.assertEqual(filter(None, "abc"), "abc")
@ -389,8 +388,8 @@ class TestCase(unittest.TestCase):
# Test map()'s use of iterators. # Test map()'s use of iterators.
def test_builtin_map(self): def test_builtin_map(self):
self.assertEqual(map(None, SequenceClass(5)), range(5)) self.assertEqual(map(None, SequenceClass(5)), list(range(5)))
self.assertEqual(map(lambda x: x+1, SequenceClass(5)), range(1, 6)) self.assertEqual(map(lambda x: x+1, SequenceClass(5)), list(range(1, 6)))
d = {"one": 1, "two": 2, "three": 3} d = {"one": 1, "two": 2, "three": 3}
self.assertEqual(map(None, d), list(d.keys())) self.assertEqual(map(None, d), list(d.keys()))
@ -413,7 +412,7 @@ class TestCase(unittest.TestCase):
f.close() f.close()
f = open(TESTFN, "r") f = open(TESTFN, "r")
try: try:
self.assertEqual(map(len, f), range(1, 21, 2)) self.assertEqual(map(len, f), list(range(1, 21, 2)))
finally: finally:
f.close() f.close()
try: try:
@ -470,7 +469,7 @@ class TestCase(unittest.TestCase):
except OSError: except OSError:
pass pass
self.assertEqual(list(zip(xrange(5))), [(i,) for i in range(5)]) self.assertEqual(list(zip(range(5))), [(i,) for i in range(5)])
# Classes that lie about their lengths. # Classes that lie about their lengths.
class NoGuessLen5: class NoGuessLen5:
@ -799,16 +798,16 @@ class TestCase(unittest.TestCase):
def test_sinkstate_list(self): def test_sinkstate_list(self):
# This used to fail # This used to fail
a = range(5) a = list(range(5))
b = iter(a) b = iter(a)
self.assertEqual(list(b), range(5)) self.assertEqual(list(b), list(range(5)))
a.extend(range(5, 10)) a.extend(range(5, 10))
self.assertEqual(list(b), []) self.assertEqual(list(b), [])
def test_sinkstate_tuple(self): def test_sinkstate_tuple(self):
a = (0, 1, 2, 3, 4) a = (0, 1, 2, 3, 4)
b = iter(a) b = iter(a)
self.assertEqual(list(b), range(5)) self.assertEqual(list(b), list(range(5)))
self.assertEqual(list(b), []) self.assertEqual(list(b), [])
def test_sinkstate_string(self): def test_sinkstate_string(self):
@ -821,7 +820,7 @@ class TestCase(unittest.TestCase):
# This used to fail # This used to fail
a = SequenceClass(5) a = SequenceClass(5)
b = iter(a) b = iter(a)
self.assertEqual(list(b), range(5)) self.assertEqual(list(b), list(range(5)))
a.n = 10 a.n = 10
self.assertEqual(list(b), []) self.assertEqual(list(b), [])
@ -834,7 +833,7 @@ class TestCase(unittest.TestCase):
raise AssertionError, "shouldn't have gotten this far" raise AssertionError, "shouldn't have gotten this far"
return i return i
b = iter(spam, 5) b = iter(spam, 5)
self.assertEqual(list(b), range(5)) self.assertEqual(list(b), list(range(5)))
self.assertEqual(list(b), []) self.assertEqual(list(b), [])
def test_sinkstate_dict(self): def test_sinkstate_dict(self):
@ -851,13 +850,13 @@ class TestCase(unittest.TestCase):
for i in range(5): for i in range(5):
yield i yield i
b = gen() b = gen()
self.assertEqual(list(b), range(5)) self.assertEqual(list(b), list(range(5)))
self.assertEqual(list(b), []) self.assertEqual(list(b), [])
def test_sinkstate_range(self): def test_sinkstate_range(self):
a = xrange(5) a = range(5)
b = iter(a) b = iter(a)
self.assertEqual(list(b), range(5)) self.assertEqual(list(b), list(range(5)))
self.assertEqual(list(b), []) self.assertEqual(list(b), [])
def test_sinkstate_enumerate(self): def test_sinkstate_enumerate(self):

View file

@ -9,14 +9,14 @@ The desired invariant is: len(it)==len(list(it)).
A complication is that an iterable and iterator can be the same object. To A complication is that an iterable and iterator can be the same object. To
maintain the invariant, an iterator needs to dynamically update its length. maintain the invariant, an iterator needs to dynamically update its length.
For instance, an iterable such as xrange(10) always reports its length as ten, For instance, an iterable such as range(10) always reports its length as ten,
but it=iter(xrange(10)) starts at ten, and then goes to nine after next(it). but it=iter(range(10)) starts at ten, and then goes to nine after next(it).
Having this capability means that map() can ignore the distinction between Having this capability means that map() can ignore the distinction between
map(func, iterable) and map(func, iter(iterable)). map(func, iterable) and map(func, iter(iterable)).
When the iterable is immutable, the implementation can straight-forwardly When the iterable is immutable, the implementation can straight-forwardly
report the original length minus the cumulative number of calls to next(). report the original length minus the cumulative number of calls to next().
This is the case for tuples, xrange objects, and itertools.repeat(). This is the case for tuples, range objects, and itertools.repeat().
Some containers become temporarily immutable during iteration. This includes Some containers become temporarily immutable during iteration. This includes
dicts, sets, and collections.deque. Their implementation is equally simple dicts, sets, and collections.deque. Their implementation is equally simple
@ -65,7 +65,7 @@ class TestInvariantWithoutMutations(unittest.TestCase):
def test_invariant(self): def test_invariant(self):
it = self.it it = self.it
for i in reversed(xrange(1, n+1)): for i in reversed(range(1, n+1)):
self.assertEqual(len(it), i) self.assertEqual(len(it), i)
next(it) next(it)
self.assertEqual(len(it), 0) self.assertEqual(len(it), 0)
@ -100,59 +100,59 @@ class TestRepeat(TestInvariantWithoutMutations):
class TestXrange(TestInvariantWithoutMutations): class TestXrange(TestInvariantWithoutMutations):
def setUp(self): def setUp(self):
self.it = iter(xrange(n)) self.it = iter(range(n))
class TestXrangeCustomReversed(TestInvariantWithoutMutations): class TestXrangeCustomReversed(TestInvariantWithoutMutations):
def setUp(self): def setUp(self):
self.it = reversed(xrange(n)) self.it = reversed(range(n))
class TestTuple(TestInvariantWithoutMutations): class TestTuple(TestInvariantWithoutMutations):
def setUp(self): def setUp(self):
self.it = iter(tuple(xrange(n))) self.it = iter(tuple(range(n)))
## ------- Types that should not be mutated during iteration ------- ## ------- Types that should not be mutated during iteration -------
class TestDeque(TestTemporarilyImmutable): class TestDeque(TestTemporarilyImmutable):
def setUp(self): def setUp(self):
d = deque(xrange(n)) d = deque(range(n))
self.it = iter(d) self.it = iter(d)
self.mutate = d.pop self.mutate = d.pop
class TestDequeReversed(TestTemporarilyImmutable): class TestDequeReversed(TestTemporarilyImmutable):
def setUp(self): def setUp(self):
d = deque(xrange(n)) d = deque(range(n))
self.it = reversed(d) self.it = reversed(d)
self.mutate = d.pop self.mutate = d.pop
class TestDictKeys(TestTemporarilyImmutable): class TestDictKeys(TestTemporarilyImmutable):
def setUp(self): def setUp(self):
d = dict.fromkeys(xrange(n)) d = dict.fromkeys(range(n))
self.it = iter(d) self.it = iter(d)
self.mutate = d.popitem self.mutate = d.popitem
class TestDictItems(TestTemporarilyImmutable): class TestDictItems(TestTemporarilyImmutable):
def setUp(self): def setUp(self):
d = dict.fromkeys(xrange(n)) d = dict.fromkeys(range(n))
self.it = iter(d.items()) self.it = iter(d.items())
self.mutate = d.popitem self.mutate = d.popitem
class TestDictValues(TestTemporarilyImmutable): class TestDictValues(TestTemporarilyImmutable):
def setUp(self): def setUp(self):
d = dict.fromkeys(xrange(n)) d = dict.fromkeys(range(n))
self.it = iter(d.values()) self.it = iter(d.values())
self.mutate = d.popitem self.mutate = d.popitem
class TestSet(TestTemporarilyImmutable): class TestSet(TestTemporarilyImmutable):
def setUp(self): def setUp(self):
d = set(xrange(n)) d = set(range(n))
self.it = iter(d) self.it = iter(d)
self.mutate = d.pop self.mutate = d.pop
@ -164,7 +164,7 @@ class TestList(TestInvariantWithoutMutations):
self.it = iter(range(n)) self.it = iter(range(n))
def test_mutation(self): def test_mutation(self):
d = range(n) d = list(range(n))
it = iter(d) it = iter(d)
next(it) next(it)
next(it) next(it)
@ -174,7 +174,7 @@ class TestList(TestInvariantWithoutMutations):
d[1:] = [] d[1:] = []
self.assertEqual(len(it), 0) self.assertEqual(len(it), 0)
self.assertEqual(list(it), []) self.assertEqual(list(it), [])
d.extend(xrange(20)) d.extend(range(20))
self.assertEqual(len(it), 0) self.assertEqual(len(it), 0)
class TestListReversed(TestInvariantWithoutMutations): class TestListReversed(TestInvariantWithoutMutations):
@ -183,7 +183,7 @@ class TestListReversed(TestInvariantWithoutMutations):
self.it = reversed(range(n)) self.it = reversed(range(n))
def test_mutation(self): def test_mutation(self):
d = range(n) d = list(range(n))
it = reversed(d) it = reversed(d)
next(it) next(it)
next(it) next(it)
@ -193,7 +193,7 @@ class TestListReversed(TestInvariantWithoutMutations):
d[1:] = [] d[1:] = []
self.assertEqual(len(it), 0) self.assertEqual(len(it), 0)
self.assertEqual(list(it), []) # confirm invariant self.assertEqual(list(it), []) # confirm invariant
d.extend(xrange(20)) d.extend(range(20))
self.assertEqual(len(it), 0) self.assertEqual(len(it), 0)
class TestSeqIter(TestInvariantWithoutMutations): class TestSeqIter(TestInvariantWithoutMutations):
@ -212,7 +212,7 @@ class TestSeqIter(TestInvariantWithoutMutations):
d[1:] = [] d[1:] = []
self.assertEqual(len(it), 0) self.assertEqual(len(it), 0)
self.assertEqual(list(it), []) self.assertEqual(list(it), [])
d.extend(xrange(20)) d.extend(range(20))
self.assertEqual(len(it), 0) self.assertEqual(len(it), 0)
class TestSeqIterReversed(TestInvariantWithoutMutations): class TestSeqIterReversed(TestInvariantWithoutMutations):
@ -231,7 +231,7 @@ class TestSeqIterReversed(TestInvariantWithoutMutations):
d[1:] = [] d[1:] = []
self.assertEqual(len(it), 0) self.assertEqual(len(it), 0)
self.assertEqual(list(it), []) # confirm invariant self.assertEqual(list(it), []) # confirm invariant
d.extend(xrange(20)) d.extend(range(20))
self.assertEqual(len(it), 0) self.assertEqual(len(it), 0)

View file

@ -248,7 +248,7 @@ class TestBasicOps(unittest.TestCase):
self.assertEqual(len(dict.fromkeys(ids)), len(ids)) self.assertEqual(len(dict.fromkeys(ids)), len(ids))
def test_repeat(self): def test_repeat(self):
self.assertEqual(lzip(xrange(3),repeat('a')), self.assertEqual(lzip(range(3),repeat('a')),
[(0, 'a'), (1, 'a'), (2, 'a')]) [(0, 'a'), (1, 'a'), (2, 'a')])
self.assertEqual(list(repeat('a', 3)), ['a', 'a', 'a']) self.assertEqual(list(repeat('a', 3)), ['a', 'a', 'a'])
self.assertEqual(take(3, repeat('a')), ['a', 'a', 'a']) self.assertEqual(take(3, repeat('a')), ['a', 'a', 'a'])
@ -301,39 +301,41 @@ class TestBasicOps(unittest.TestCase):
(10, 3), (10, 3),
(20,) (20,)
]: ]:
self.assertEqual(list(islice(xrange(100), *args)), range(*args)) self.assertEqual(list(islice(range(100), *args)),
list(range(*args)))
for args, tgtargs in [ # Stop when seqn is exhausted for args, tgtargs in [ # Stop when seqn is exhausted
((10, 110, 3), ((10, 100, 3))), ((10, 110, 3), ((10, 100, 3))),
((10, 110), ((10, 100))), ((10, 110), ((10, 100))),
((110,), (100,)) ((110,), (100,))
]: ]:
self.assertEqual(list(islice(xrange(100), *args)), range(*tgtargs)) self.assertEqual(list(islice(range(100), *args)),
list(range(*tgtargs)))
# Test stop=None # Test stop=None
self.assertEqual(list(islice(xrange(10), None)), range(10)) self.assertEqual(list(islice(range(10), None)), list(range(10)))
self.assertEqual(list(islice(xrange(10), None, None)), range(10)) self.assertEqual(list(islice(range(10), None, None)), list(range(10)))
self.assertEqual(list(islice(xrange(10), None, None, None)), range(10)) self.assertEqual(list(islice(range(10), None, None, None)), list(range(10)))
self.assertEqual(list(islice(xrange(10), 2, None)), range(2, 10)) self.assertEqual(list(islice(range(10), 2, None)), list(range(2, 10)))
self.assertEqual(list(islice(xrange(10), 1, None, 2)), range(1, 10, 2)) self.assertEqual(list(islice(range(10), 1, None, 2)), list(range(1, 10, 2)))
# Test number of items consumed SF #1171417 # Test number of items consumed SF #1171417
it = iter(range(10)) it = iter(range(10))
self.assertEqual(list(islice(it, 3)), range(3)) self.assertEqual(list(islice(it, 3)), list(range(3)))
self.assertEqual(list(it), range(3, 10)) self.assertEqual(list(it), list(range(3, 10)))
# Test invalid arguments # Test invalid arguments
self.assertRaises(TypeError, islice, xrange(10)) self.assertRaises(TypeError, islice, range(10))
self.assertRaises(TypeError, islice, xrange(10), 1, 2, 3, 4) self.assertRaises(TypeError, islice, range(10), 1, 2, 3, 4)
self.assertRaises(ValueError, islice, xrange(10), -5, 10, 1) self.assertRaises(ValueError, islice, range(10), -5, 10, 1)
self.assertRaises(ValueError, islice, xrange(10), 1, -5, -1) self.assertRaises(ValueError, islice, range(10), 1, -5, -1)
self.assertRaises(ValueError, islice, xrange(10), 1, 10, -1) self.assertRaises(ValueError, islice, range(10), 1, 10, -1)
self.assertRaises(ValueError, islice, xrange(10), 1, 10, 0) self.assertRaises(ValueError, islice, range(10), 1, 10, 0)
self.assertRaises(ValueError, islice, xrange(10), 'a') self.assertRaises(ValueError, islice, range(10), 'a')
self.assertRaises(ValueError, islice, xrange(10), 'a', 1) self.assertRaises(ValueError, islice, range(10), 'a', 1)
self.assertRaises(ValueError, islice, xrange(10), 1, 'a') self.assertRaises(ValueError, islice, range(10), 1, 'a')
self.assertRaises(ValueError, islice, xrange(10), 'a', 1, 1) self.assertRaises(ValueError, islice, range(10), 'a', 1, 1)
self.assertRaises(ValueError, islice, xrange(10), 1, 'a', 1) self.assertRaises(ValueError, islice, range(10), 1, 'a', 1)
self.assertEqual(len(list(islice(count(), 1, 10, sys.maxint))), 1) self.assertEqual(len(list(islice(count(), 1, 10, sys.maxint))), 1)
def test_takewhile(self): def test_takewhile(self):
@ -364,7 +366,7 @@ class TestBasicOps(unittest.TestCase):
def test_tee(self): def test_tee(self):
n = 200 n = 200
def irange(n): def irange(n):
for i in xrange(n): for i in range(n):
yield i yield i
a, b = tee([]) # test empty iterator a, b = tee([]) # test empty iterator
@ -375,22 +377,22 @@ class TestBasicOps(unittest.TestCase):
self.assertEqual(lzip(a,b), lzip(range(n), range(n))) self.assertEqual(lzip(a,b), lzip(range(n), range(n)))
a, b = tee(irange(n)) # test 0% interleaved a, b = tee(irange(n)) # test 0% interleaved
self.assertEqual(list(a), range(n)) self.assertEqual(list(a), list(range(n)))
self.assertEqual(list(b), range(n)) self.assertEqual(list(b), list(range(n)))
a, b = tee(irange(n)) # test dealloc of leading iterator a, b = tee(irange(n)) # test dealloc of leading iterator
for i in xrange(100): for i in range(100):
self.assertEqual(next(a), i) self.assertEqual(next(a), i)
del a del a
self.assertEqual(list(b), range(n)) self.assertEqual(list(b), list(range(n)))
a, b = tee(irange(n)) # test dealloc of trailing iterator a, b = tee(irange(n)) # test dealloc of trailing iterator
for i in xrange(100): for i in range(100):
self.assertEqual(next(a), i) self.assertEqual(next(a), i)
del b del b
self.assertEqual(list(a), range(100, n)) self.assertEqual(list(a), list(range(100, n)))
for j in xrange(5): # test randomly interleaved for j in range(5): # test randomly interleaved
order = [0]*n + [1]*n order = [0]*n + [1]*n
random.shuffle(order) random.shuffle(order)
lists = ([], []) lists = ([], [])
@ -398,8 +400,8 @@ class TestBasicOps(unittest.TestCase):
for i in order: for i in order:
value = next(its[i]) value = next(its[i])
lists[i].append(value) lists[i].append(value)
self.assertEqual(lists[0], range(n)) self.assertEqual(lists[0], list(range(n)))
self.assertEqual(lists[1], range(n)) self.assertEqual(lists[1], list(range(n)))
# test argument format checking # test argument format checking
self.assertRaises(TypeError, tee) self.assertRaises(TypeError, tee)
@ -413,18 +415,18 @@ class TestBasicOps(unittest.TestCase):
self.assertEqual(list(c), list('def')) self.assertEqual(list(c), list('def'))
# test long-lagged and multi-way split # test long-lagged and multi-way split
a, b, c = tee(xrange(2000), 3) a, b, c = tee(range(2000), 3)
for i in xrange(100): for i in range(100):
self.assertEqual(next(a), i) self.assertEqual(next(a), i)
self.assertEqual(list(b), range(2000)) self.assertEqual(list(b), list(range(2000)))
self.assertEqual([next(c), next(c)], range(2)) self.assertEqual([next(c), next(c)], list(range(2)))
self.assertEqual(list(a), range(100,2000)) self.assertEqual(list(a), list(range(100,2000)))
self.assertEqual(list(c), range(2,2000)) self.assertEqual(list(c), list(range(2,2000)))
# test values of n # test values of n
self.assertRaises(TypeError, tee, 'abc', 'invalid') self.assertRaises(TypeError, tee, 'abc', 'invalid')
self.assertRaises(ValueError, tee, [], -1) self.assertRaises(ValueError, tee, [], -1)
for n in xrange(5): for n in range(5):
result = tee('abc', n) result = tee('abc', n)
self.assertEqual(type(result), tuple) self.assertEqual(type(result), tuple)
self.assertEqual(len(result), n) self.assertEqual(len(result), n)
@ -444,7 +446,7 @@ class TestBasicOps(unittest.TestCase):
self.assert_(list(t1) == list(t2) == list(t3) == list('abc')) self.assert_(list(t1) == list(t2) == list(t3) == list('abc'))
# test that tee objects are weak referencable # test that tee objects are weak referencable
a, b = tee(xrange(10)) a, b = tee(range(10))
p = proxy(a) p = proxy(a)
self.assertEqual(getattr(p, '__class__'), type(b)) self.assertEqual(getattr(p, '__class__'), type(b))
del a del a
@ -608,7 +610,7 @@ def L(seqn):
class TestVariousIteratorArgs(unittest.TestCase): class TestVariousIteratorArgs(unittest.TestCase):
def test_chain(self): def test_chain(self):
for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)): for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
for g in (G, I, Ig, S, L, R): for g in (G, I, Ig, S, L, R):
self.assertEqual(list(chain(g(s))), list(g(s))) self.assertEqual(list(chain(g(s))), list(g(s)))
self.assertEqual(list(chain(g(s), g(s))), list(g(s))+list(g(s))) self.assertEqual(list(chain(g(s), g(s))), list(g(s))+list(g(s)))
@ -617,7 +619,7 @@ class TestVariousIteratorArgs(unittest.TestCase):
self.assertRaises(ZeroDivisionError, list, chain(E(s))) self.assertRaises(ZeroDivisionError, list, chain(E(s)))
def test_cycle(self): def test_cycle(self):
for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)): for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
for g in (G, I, Ig, S, L, R): for g in (G, I, Ig, S, L, R):
tgtlen = len(s) * 3 tgtlen = len(s) * 3
expected = list(g(s))*3 expected = list(g(s))*3
@ -628,7 +630,7 @@ class TestVariousIteratorArgs(unittest.TestCase):
self.assertRaises(ZeroDivisionError, list, cycle(E(s))) self.assertRaises(ZeroDivisionError, list, cycle(E(s)))
def test_groupby(self): def test_groupby(self):
for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)): for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)):
for g in (G, I, Ig, S, L, R): for g in (G, I, Ig, S, L, R):
self.assertEqual([k for k, sb in groupby(g(s))], list(g(s))) self.assertEqual([k for k, sb in groupby(g(s))], list(g(s)))
self.assertRaises(TypeError, groupby, X(s)) self.assertRaises(TypeError, groupby, X(s))
@ -636,7 +638,7 @@ class TestVariousIteratorArgs(unittest.TestCase):
self.assertRaises(ZeroDivisionError, list, groupby(E(s))) self.assertRaises(ZeroDivisionError, list, groupby(E(s)))
def test_ifilter(self): def test_ifilter(self):
for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)): for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)):
for g in (G, I, Ig, S, L, R): for g in (G, I, Ig, S, L, R):
self.assertEqual(list(ifilter(isEven, g(s))), filter(isEven, g(s))) self.assertEqual(list(ifilter(isEven, g(s))), filter(isEven, g(s)))
self.assertRaises(TypeError, ifilter, isEven, X(s)) self.assertRaises(TypeError, ifilter, isEven, X(s))
@ -644,7 +646,7 @@ class TestVariousIteratorArgs(unittest.TestCase):
self.assertRaises(ZeroDivisionError, list, ifilter(isEven, E(s))) self.assertRaises(ZeroDivisionError, list, ifilter(isEven, E(s)))
def test_ifilterfalse(self): def test_ifilterfalse(self):
for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)): for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)):
for g in (G, I, Ig, S, L, R): for g in (G, I, Ig, S, L, R):
self.assertEqual(list(ifilterfalse(isEven, g(s))), filter(isOdd, g(s))) self.assertEqual(list(ifilterfalse(isEven, g(s))), filter(isOdd, g(s)))
self.assertRaises(TypeError, ifilterfalse, isEven, X(s)) self.assertRaises(TypeError, ifilterfalse, isEven, X(s))
@ -652,7 +654,7 @@ class TestVariousIteratorArgs(unittest.TestCase):
self.assertRaises(ZeroDivisionError, list, ifilterfalse(isEven, E(s))) self.assertRaises(ZeroDivisionError, list, ifilterfalse(isEven, E(s)))
def test_izip(self): def test_izip(self):
for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)): for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
for g in (G, I, Ig, S, L, R): for g in (G, I, Ig, S, L, R):
self.assertEqual(list(izip(g(s))), lzip(g(s))) self.assertEqual(list(izip(g(s))), lzip(g(s)))
self.assertEqual(list(izip(g(s), g(s))), lzip(g(s), g(s))) self.assertEqual(list(izip(g(s), g(s))), lzip(g(s), g(s)))
@ -661,7 +663,7 @@ class TestVariousIteratorArgs(unittest.TestCase):
self.assertRaises(ZeroDivisionError, list, izip(E(s))) self.assertRaises(ZeroDivisionError, list, izip(E(s)))
def test_iziplongest(self): def test_iziplongest(self):
for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)): for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
for g in (G, I, Ig, S, L, R): for g in (G, I, Ig, S, L, R):
self.assertEqual(list(izip_longest(g(s))), list(zip(g(s)))) self.assertEqual(list(izip_longest(g(s))), list(zip(g(s))))
self.assertEqual(list(izip_longest(g(s), g(s))), list(zip(g(s), g(s)))) self.assertEqual(list(izip_longest(g(s), g(s))), list(zip(g(s), g(s))))
@ -670,7 +672,7 @@ class TestVariousIteratorArgs(unittest.TestCase):
self.assertRaises(ZeroDivisionError, list, izip_longest(E(s))) self.assertRaises(ZeroDivisionError, list, izip_longest(E(s)))
def test_imap(self): def test_imap(self):
for s in (range(10), range(0), range(100), (7,11), xrange(20,50,5)): for s in (range(10), range(0), range(100), (7,11), range(20,50,5)):
for g in (G, I, Ig, S, L, R): for g in (G, I, Ig, S, L, R):
self.assertEqual(list(imap(onearg, g(s))), map(onearg, g(s))) self.assertEqual(list(imap(onearg, g(s))), map(onearg, g(s)))
self.assertEqual(list(imap(operator.pow, g(s), g(s))), map(operator.pow, g(s), g(s))) self.assertEqual(list(imap(operator.pow, g(s), g(s))), map(operator.pow, g(s), g(s)))
@ -679,7 +681,7 @@ class TestVariousIteratorArgs(unittest.TestCase):
self.assertRaises(ZeroDivisionError, list, imap(onearg, E(s))) self.assertRaises(ZeroDivisionError, list, imap(onearg, E(s)))
def test_islice(self): def test_islice(self):
for s in ("12345", "", range(1000), ('do', 1.2), xrange(2000,2200,5)): for s in ("12345", "", range(1000), ('do', 1.2), range(2000,2200,5)):
for g in (G, I, Ig, S, L, R): for g in (G, I, Ig, S, L, R):
self.assertEqual(list(islice(g(s),1,None,2)), list(g(s))[1::2]) self.assertEqual(list(islice(g(s),1,None,2)), list(g(s))[1::2])
self.assertRaises(TypeError, islice, X(s), 10) self.assertRaises(TypeError, islice, X(s), 10)
@ -687,7 +689,7 @@ class TestVariousIteratorArgs(unittest.TestCase):
self.assertRaises(ZeroDivisionError, list, islice(E(s), 10)) self.assertRaises(ZeroDivisionError, list, islice(E(s), 10))
def test_starmap(self): def test_starmap(self):
for s in (range(10), range(0), range(100), (7,11), xrange(20,50,5)): for s in (range(10), range(0), range(100), (7,11), range(20,50,5)):
for g in (G, I, Ig, S, L, R): for g in (G, I, Ig, S, L, R):
ss = lzip(s, s) ss = lzip(s, s)
self.assertEqual(list(starmap(operator.pow, g(ss))), map(operator.pow, g(s), g(s))) self.assertEqual(list(starmap(operator.pow, g(ss))), map(operator.pow, g(s), g(s)))
@ -696,7 +698,7 @@ class TestVariousIteratorArgs(unittest.TestCase):
self.assertRaises(ZeroDivisionError, list, starmap(operator.pow, E(ss))) self.assertRaises(ZeroDivisionError, list, starmap(operator.pow, E(ss)))
def test_takewhile(self): def test_takewhile(self):
for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)): for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)):
for g in (G, I, Ig, S, L, R): for g in (G, I, Ig, S, L, R):
tgt = [] tgt = []
for elem in g(s): for elem in g(s):
@ -708,7 +710,7 @@ class TestVariousIteratorArgs(unittest.TestCase):
self.assertRaises(ZeroDivisionError, list, takewhile(isEven, E(s))) self.assertRaises(ZeroDivisionError, list, takewhile(isEven, E(s)))
def test_dropwhile(self): def test_dropwhile(self):
for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)): for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)):
for g in (G, I, Ig, S, L, R): for g in (G, I, Ig, S, L, R):
tgt = [] tgt = []
for elem in g(s): for elem in g(s):
@ -720,7 +722,7 @@ class TestVariousIteratorArgs(unittest.TestCase):
self.assertRaises(ZeroDivisionError, list, dropwhile(isOdd, E(s))) self.assertRaises(ZeroDivisionError, list, dropwhile(isOdd, E(s)))
def test_tee(self): def test_tee(self):
for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)): for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
for g in (G, I, Ig, S, L, R): for g in (G, I, Ig, S, L, R):
it1, it2 = tee(g(s)) it1, it2 = tee(g(s))
self.assertEqual(list(it1), list(g(s))) self.assertEqual(list(it1), list(g(s)))
@ -824,7 +826,7 @@ Check 1201 is for $764.05
Check 1202 is for $823.14 Check 1202 is for $823.14
>>> import operator >>> import operator
>>> for cube in imap(operator.pow, xrange(1,4), repeat(3)): >>> for cube in imap(operator.pow, range(1,4), repeat(3)):
... print(cube) ... print(cube)
... ...
1 1
@ -968,7 +970,7 @@ True
>>> no([1, 2, 5, 9], lambda x: x%2==0) >>> no([1, 2, 5, 9], lambda x: x%2==0)
False False
>>> quantify(xrange(99), lambda x: x%2==0) >>> quantify(range(99), lambda x: x%2==0)
50 50
>>> a = [[1, 2, 3], [4, 5, 6]] >>> a = [[1, 2, 3], [4, 5, 6]]
@ -1014,7 +1016,7 @@ def test_main(verbose=None):
if verbose and hasattr(sys, "gettotalrefcount"): if verbose and hasattr(sys, "gettotalrefcount"):
import gc import gc
counts = [None] * 5 counts = [None] * 5
for i in xrange(len(counts)): for i in range(len(counts)):
test_support.run_unittest(*test_classes) test_support.run_unittest(*test_classes)
gc.collect() gc.collect()
counts[i] = sys.gettotalrefcount() counts[i] = sys.gettotalrefcount()

View file

@ -26,7 +26,7 @@ def test_main(verbose=None):
if verbose and hasattr(sys, "gettotalrefcount"): if verbose and hasattr(sys, "gettotalrefcount"):
import gc import gc
counts = [None] * 5 counts = [None] * 5
for i in xrange(len(counts)): for i in range(len(counts)):
test_support.run_unittest(ListTest) test_support.run_unittest(ListTest)
gc.collect() gc.collect()
counts[i] = sys.gettotalrefcount() counts[i] = sys.gettotalrefcount()

View file

@ -43,20 +43,20 @@ Verify that syntax error's are raised for listcomps used as lvalues
Make a nested list comprehension that acts like range() Make a nested list comprehension that acts like range()
>>> def frange(n): >>> def frange(n):
... return [i for i in xrange(n)] ... return [i for i in range(n)]
>>> frange(10) >>> frange(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Same again, only as a lambda expression instead of a function definition Same again, only as a lambda expression instead of a function definition
>>> lrange = lambda n: [i for i in xrange(n)] >>> lrange = lambda n: [i for i in range(n)]
>>> lrange(10) >>> lrange(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Generators can call other generators: Generators can call other generators:
>>> def grange(n): >>> def grange(n):
... for x in [i for i in xrange(n)]: ... for x in [i for i in range(n)]:
... yield x ... yield x
>>> list(grange(5)) >>> list(grange(5))
[0, 1, 2, 3, 4] [0, 1, 2, 3, 4]
@ -64,7 +64,7 @@ Generators can call other generators:
Make sure that None is a valid return value Make sure that None is a valid return value
>>> [None for i in xrange(10)] >>> [None for i in range(10)]
[None, None, None, None, None, None, None, None, None, None] [None, None, None, None, None, None, None, None, None, None]
########### Tests for various scoping corner cases ############ ########### Tests for various scoping corner cases ############
@ -138,7 +138,7 @@ def test_main(verbose=None):
if verbose and hasattr(sys, "gettotalrefcount"): if verbose and hasattr(sys, "gettotalrefcount"):
import gc import gc
counts = [None] * 5 counts = [None] * 5
for i in xrange(len(counts)): for i in range(len(counts)):
test_support.run_doctest(test_genexps, verbose) test_support.run_doctest(test_genexps, verbose)
gc.collect() gc.collect()
counts[i] = sys.gettotalrefcount() counts[i] = sys.gettotalrefcount()
@ -191,20 +191,20 @@ Verify that syntax error's are raised for listcomps used as lvalues
Make a nested list comprehension that acts like range() Make a nested list comprehension that acts like range()
>>> def frange(n): >>> def frange(n):
... return [i for i in xrange(n)] ... return [i for i in range(n)]
>>> frange(10) >>> frange(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Same again, only as a lambda expression instead of a function definition Same again, only as a lambda expression instead of a function definition
>>> lrange = lambda n: [i for i in xrange(n)] >>> lrange = lambda n: [i for i in range(n)]
>>> lrange(10) >>> lrange(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Generators can call other generators: Generators can call other generators:
>>> def grange(n): >>> def grange(n):
... for x in [i for i in xrange(n)]: ... for x in [i for i in range(n)]:
... yield x ... yield x
>>> list(grange(5)) >>> list(grange(5))
[0, 1, 2, 3, 4] [0, 1, 2, 3, 4]
@ -212,7 +212,7 @@ Generators can call other generators:
Make sure that None is a valid return value Make sure that None is a valid return value
>>> [None for i in xrange(10)] >>> [None for i in range(10)]
[None, None, None, None, None, None, None, None, None, None] [None, None, None, None, None, None, None, None, None, None]
########### Tests for various scoping corner cases ############ ########### Tests for various scoping corner cases ############
@ -286,7 +286,7 @@ def test_main(verbose=None):
if verbose and hasattr(sys, "gettotalrefcount"): if verbose and hasattr(sys, "gettotalrefcount"):
import gc import gc
counts = [None] * 5 counts = [None] * 5
for i in xrange(len(counts)): for i in range(len(counts)):
test_support.run_doctest(test_genexps, verbose) test_support.run_doctest(test_genexps, verbose)
gc.collect() gc.collect()
counts[i] = sys.gettotalrefcount() counts[i] = sys.gettotalrefcount()
@ -339,20 +339,20 @@ Verify that syntax error's are raised for listcomps used as lvalues
Make a nested list comprehension that acts like range() Make a nested list comprehension that acts like range()
>>> def frange(n): >>> def frange(n):
... return [i for i in xrange(n)] ... return [i for i in range(n)]
>>> frange(10) >>> frange(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Same again, only as a lambda expression instead of a function definition Same again, only as a lambda expression instead of a function definition
>>> lrange = lambda n: [i for i in xrange(n)] >>> lrange = lambda n: [i for i in range(n)]
>>> lrange(10) >>> lrange(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Generators can call other generators: Generators can call other generators:
>>> def grange(n): >>> def grange(n):
... for x in [i for i in xrange(n)]: ... for x in [i for i in range(n)]:
... yield x ... yield x
>>> list(grange(5)) >>> list(grange(5))
[0, 1, 2, 3, 4] [0, 1, 2, 3, 4]
@ -360,7 +360,7 @@ Generators can call other generators:
Make sure that None is a valid return value Make sure that None is a valid return value
>>> [None for i in xrange(10)] >>> [None for i in range(10)]
[None, None, None, None, None, None, None, None, None, None] [None, None, None, None, None, None, None, None, None, None]
########### Tests for various scoping corner cases ############ ########### Tests for various scoping corner cases ############
@ -434,7 +434,7 @@ def test_main(verbose=None):
if verbose and hasattr(sys, "gettotalrefcount"): if verbose and hasattr(sys, "gettotalrefcount"):
import gc import gc
counts = [None] * 5 counts = [None] * 5
for i in xrange(len(counts)): for i in range(len(counts)):
test_support.run_doctest(test_genexps, verbose) test_support.run_doctest(test_genexps, verbose)
gc.collect() gc.collect()
counts[i] = sys.gettotalrefcount() counts[i] = sys.gettotalrefcount()

View file

@ -355,7 +355,7 @@ def test2():
logger.info("Info message") logger.info("Info message")
message("-- logging at WARNING, 3 messages should be seen --") message("-- logging at WARNING, 3 messages should be seen --")
logger.warn("Warn message") logger.warn("Warn message")
for i in xrange(102): for i in range(102):
message(MSG % i) message(MSG % i)
logger.info("Info index = %d", i) logger.info("Info index = %d", i)
mh.close() mh.close()

View file

@ -71,7 +71,7 @@ class LongTest(unittest.TestCase):
def getran2(ndigits): def getran2(ndigits):
answer = 0 answer = 0
for i in xrange(ndigits): for i in range(ndigits):
answer = (answer << SHIFT) | random.randint(0, MASK) answer = (answer << SHIFT) | random.randint(0, MASK)
if random.random() < 0.5: if random.random() < 0.5:
answer = -answer answer = -answer
@ -92,8 +92,8 @@ class LongTest(unittest.TestCase):
self.assert_(y < r <= 0, Frm("bad mod from divmod on %r and %r", x, y)) self.assert_(y < r <= 0, Frm("bad mod from divmod on %r and %r", x, y))
def test_division(self): def test_division(self):
digits = range(1, MAXDIGITS+1) + range(KARATSUBA_CUTOFF, digits = list(range(1, MAXDIGITS+1)) + list(range(KARATSUBA_CUTOFF,
KARATSUBA_CUTOFF + 14) KARATSUBA_CUTOFF + 14))
digits.append(KARATSUBA_CUTOFF * 3) digits.append(KARATSUBA_CUTOFF * 3)
for lenx in digits: for lenx in digits:
x = self.getran(lenx) x = self.getran(lenx)
@ -102,7 +102,8 @@ class LongTest(unittest.TestCase):
self.check_division(x, y) self.check_division(x, y)
def test_karatsuba(self): def test_karatsuba(self):
digits = range(1, 5) + range(KARATSUBA_CUTOFF, KARATSUBA_CUTOFF + 10) digits = list(range(1, 5)) + list(range(KARATSUBA_CUTOFF,
KARATSUBA_CUTOFF + 10))
digits.extend([KARATSUBA_CUTOFF * 10, KARATSUBA_CUTOFF * 100]) digits.extend([KARATSUBA_CUTOFF * 10, KARATSUBA_CUTOFF * 100])
bits = [digit * SHIFT for digit in digits] bits = [digit * SHIFT for digit in digits]
@ -140,7 +141,7 @@ class LongTest(unittest.TestCase):
eq(x ^ ~x, -1, Frm("x ^ ~x != -1 for x=%r", x)) eq(x ^ ~x, -1, Frm("x ^ ~x != -1 for x=%r", x))
eq(-x, 1 + ~x, Frm("not -x == 1 + ~x for x=%r", x)) eq(-x, 1 + ~x, Frm("not -x == 1 + ~x for x=%r", x))
eq(-x, ~(x-1), Frm("not -x == ~(x-1) forx =%r", x)) eq(-x, ~(x-1), Frm("not -x == ~(x-1) forx =%r", x))
for n in xrange(2*SHIFT): for n in range(2*SHIFT):
p2 = 2 ** n p2 = 2 ** n
eq(x << n >> n, x, eq(x << n >> n, x,
Frm("x << n >> n != x for x=%r, n=%r", (x, n))) Frm("x << n >> n != x for x=%r, n=%r", (x, n)))
@ -184,7 +185,7 @@ class LongTest(unittest.TestCase):
def test_bitop_identities(self): def test_bitop_identities(self):
for x in special: for x in special:
self.check_bitop_identities_1(x) self.check_bitop_identities_1(x)
digits = xrange(1, MAXDIGITS+1) digits = range(1, MAXDIGITS+1)
for lenx in digits: for lenx in digits:
x = self.getran(lenx) x = self.getran(lenx)
self.check_bitop_identities_1(x) self.check_bitop_identities_1(x)
@ -229,8 +230,8 @@ class LongTest(unittest.TestCase):
def test_format(self): def test_format(self):
for x in special: for x in special:
self.check_format_1(x) self.check_format_1(x)
for i in xrange(10): for i in range(10):
for lenx in xrange(1, MAXDIGITS+1): for lenx in range(1, MAXDIGITS+1):
x = self.getran(lenx) x = self.getran(lenx)
self.check_format_1(x) self.check_format_1(x)
@ -399,7 +400,7 @@ class LongTest(unittest.TestCase):
LOG10E = math.log10(math.e) LOG10E = math.log10(math.e)
for exp in range(10) + [100, 1000, 10000]: for exp in list(range(10)) + [100, 1000, 10000]:
value = 10 ** exp value = 10 ** exp
log10 = math.log10(value) log10 = math.log10(value)
self.assertAlmostEqual(log10, exp) self.assertAlmostEqual(log10, exp)

View file

@ -208,7 +208,7 @@ class TestMailbox(TestBase):
for value in method(): for value in method():
self.fail("Not empty") self.fail("Not empty")
keys, values = [], [] keys, values = [], []
for i in xrange(repetitions): for i in range(repetitions):
keys.append(self._box.add(self._template % i)) keys.append(self._box.add(self._template % i))
values.append(self._template % i) values.append(self._template % i)
if do_keys and not do_values: if do_keys and not do_values:
@ -254,11 +254,11 @@ class TestMailbox(TestBase):
def test_len(self, repetitions=10): def test_len(self, repetitions=10):
# Get message count # Get message count
keys = [] keys = []
for i in xrange(repetitions): for i in range(repetitions):
self.assert_(len(self._box) == i) self.assert_(len(self._box) == i)
keys.append(self._box.add(self._template % i)) keys.append(self._box.add(self._template % i))
self.assert_(len(self._box) == i + 1) self.assert_(len(self._box) == i + 1)
for i in xrange(repetitions): for i in range(repetitions):
self.assert_(len(self._box) == repetitions - i) self.assert_(len(self._box) == repetitions - i)
self._box.remove(keys[i]) self._box.remove(keys[i])
self.assert_(len(self._box) == repetitions - i - 1) self.assert_(len(self._box) == repetitions - i - 1)
@ -293,7 +293,7 @@ class TestMailbox(TestBase):
def test_clear(self, iterations=10): def test_clear(self, iterations=10):
# Remove all messages using clear() # Remove all messages using clear()
keys = [] keys = []
for i in xrange(iterations): for i in range(iterations):
self._box.add(self._template % i) self._box.add(self._template % i)
for i, key in enumerate(keys): for i, key in enumerate(keys):
self.assert_(self._box.get_string(key) == self._template % i) self.assert_(self._box.get_string(key) == self._template % i)
@ -323,10 +323,10 @@ class TestMailbox(TestBase):
def test_popitem(self, iterations=10): def test_popitem(self, iterations=10):
# Get and remove an arbitrary (key, message) using popitem() # Get and remove an arbitrary (key, message) using popitem()
keys = [] keys = []
for i in xrange(10): for i in range(10):
keys.append(self._box.add(self._template % i)) keys.append(self._box.add(self._template % i))
seen = [] seen = []
for i in xrange(10): for i in range(10):
key, msg = self._box.popitem() key, msg = self._box.popitem()
self.assert_(key in keys) self.assert_(key in keys)
self.assert_(key not in seen) self.assert_(key not in seen)
@ -387,7 +387,7 @@ class TestMailbox(TestBase):
self._test_flush_or_close(self._box.close) self._test_flush_or_close(self._box.close)
def _test_flush_or_close(self, method): def _test_flush_or_close(self, method):
contents = [self._template % i for i in xrange(3)] contents = [self._template % i for i in range(3)]
self._box.add(contents[0]) self._box.add(contents[0])
self._box.add(contents[1]) self._box.add(contents[1])
self._box.add(contents[2]) self._box.add(contents[2])
@ -599,7 +599,7 @@ class TestMaildir(TestMailbox):
pattern = re.compile(r"(?P<time>\d+)\.M(?P<M>\d{1,6})P(?P<P>\d+)" pattern = re.compile(r"(?P<time>\d+)\.M(?P<M>\d{1,6})P(?P<P>\d+)"
r"Q(?P<Q>\d+)\.(?P<host>[^:/]+)") r"Q(?P<Q>\d+)\.(?P<host>[^:/]+)")
previous_groups = None previous_groups = None
for x in xrange(repetitions): for x in range(repetitions):
tmp_file = self._box._create_tmp() tmp_file = self._box._create_tmp()
head, tail = os.path.split(tmp_file.name) head, tail = os.path.split(tmp_file.name)
self.assertEqual(head, os.path.abspath(os.path.join(self._path, self.assertEqual(head, os.path.abspath(os.path.join(self._path,
@ -703,7 +703,7 @@ class _TestMboxMMDF(TestMailbox):
def test_open_close_open(self): def test_open_close_open(self):
# Open and inspect previously-created mailbox # Open and inspect previously-created mailbox
values = [self._template % i for i in xrange(3)] values = [self._template % i for i in range(3)]
for value in values: for value in values:
self._box.add(value) self._box.add(value)
self._box.close() self._box.close()
@ -718,7 +718,7 @@ class _TestMboxMMDF(TestMailbox):
def test_add_and_close(self): def test_add_and_close(self):
# Verifying that closing a mailbox doesn't change added items # Verifying that closing a mailbox doesn't change added items
self._box.add(_sample_message) self._box.add(_sample_message)
for i in xrange(3): for i in range(3):
self._box.add(self._template % i) self._box.add(self._template % i)
self._box.add(_sample_message) self._box.add(_sample_message)
self._box._file.flush() self._box._file.flush()

View file

@ -121,7 +121,7 @@ class MhlibTests(unittest.TestCase):
'Date': '29 July 2001'}, "Hullo, Mrs. Premise!\n") 'Date': '29 July 2001'}, "Hullo, Mrs. Premise!\n")
# A folder with many messages # A folder with many messages
for i in range(5, 101)+range(101, 201, 2): for i in list(range(5, 101))+list(range(101, 201, 2)):
writeMessage('wide', i, writeMessage('wide', i,
{'From': 'nowhere', 'Subject': 'message #%s' % i}, {'From': 'nowhere', 'Subject': 'message #%s' % i},
"This is message number %s\n" % i) "This is message number %s\n" % i)
@ -203,7 +203,7 @@ class MhlibTests(unittest.TestCase):
f = mh.openfolder('wide') f = mh.openfolder('wide')
all = f.listmessages() all = f.listmessages()
eq(all, range(5, 101)+range(101, 201, 2)) eq(all, list(range(5, 101))+list(range(101, 201, 2)))
eq(f.getcurrent(), 55) eq(f.getcurrent(), 55)
f.setcurrent(99) f.setcurrent(99)
eq(readFile(os.path.join(_mhpath, 'wide', '.mh_sequences')), eq(readFile(os.path.join(_mhpath, 'wide', '.mh_sequences')),
@ -212,21 +212,21 @@ class MhlibTests(unittest.TestCase):
def seqeq(seq, val): def seqeq(seq, val):
eq(f.parsesequence(seq), val) eq(f.parsesequence(seq), val)
seqeq('5-55', range(5, 56)) seqeq('5-55', list(range(5, 56)))
seqeq('90-108', range(90, 101)+range(101, 109, 2)) seqeq('90-108', list(range(90, 101))+list(range(101, 109, 2)))
seqeq('90-108', range(90, 101)+range(101, 109, 2)) seqeq('90-108', list(range(90, 101))+list(range(101, 109, 2)))
seqeq('10:10', range(10, 20)) seqeq('10:10', list(range(10, 20)))
seqeq('10:+10', range(10, 20)) seqeq('10:+10', list(range(10, 20)))
seqeq('101:10', range(101, 121, 2)) seqeq('101:10', list(range(101, 121, 2)))
seqeq('cur', [99]) seqeq('cur', [99])
seqeq('.', [99]) seqeq('.', [99])
seqeq('prev', [98]) seqeq('prev', [98])
seqeq('next', [100]) seqeq('next', [100])
seqeq('cur:-3', [97, 98, 99]) seqeq('cur:-3', [97, 98, 99])
seqeq('first-cur', range(5, 100)) seqeq('first-cur', list(range(5, 100)))
seqeq('150-last', range(151, 201, 2)) seqeq('150-last', list(range(151, 201, 2)))
seqeq('prev-next', [98, 99, 100]) seqeq('prev-next', [98, 99, 100])
lowprimes = [5, 7, 11, 13, 17, 19, 23, 29] lowprimes = [5, 7, 11, 13, 17, 19, 23, 29]

View file

@ -26,7 +26,7 @@ class MimeToolsTest(unittest.TestCase):
def test_boundary(self): def test_boundary(self):
s = set([""]) s = set([""])
for i in xrange(100): for i in range(100):
nb = mimetools.choose_boundary() nb = mimetools.choose_boundary()
self.assert_(nb not in s) self.assert_(nb not in s)
s.add(nb) s.add(nb)

View file

@ -299,10 +299,10 @@ class MmapTests(unittest.TestCase):
def test_anonymous(self): def test_anonymous(self):
# anonymous mmap.mmap(-1, PAGE) # anonymous mmap.mmap(-1, PAGE)
m = mmap.mmap(-1, PAGESIZE) m = mmap.mmap(-1, PAGESIZE)
for x in xrange(PAGESIZE): for x in range(PAGESIZE):
self.assertEqual(m[x], '\0', "anonymously mmap'ed contents should be zero") self.assertEqual(m[x], '\0', "anonymously mmap'ed contents should be zero")
for x in xrange(PAGESIZE): for x in range(PAGESIZE):
m[x] = ch = chr(x & 255) m[x] = ch = chr(x & 255)
self.assertEqual(m[x], ch) self.assertEqual(m[x], ch)

View file

@ -214,7 +214,7 @@ class Test_ISO2022(unittest.TestCase):
else: else:
myunichr = lambda x: chr(0xD7C0+(x>>10)) + chr(0xDC00+(x&0x3FF)) myunichr = lambda x: chr(0xD7C0+(x>>10)) + chr(0xDC00+(x&0x3FF))
for x in xrange(0x10000, 0x110000): for x in range(0x10000, 0x110000):
# Any ISO 2022 codec will cause the segfault # Any ISO 2022 codec will cause the segfault
myunichr(x).encode('iso_2022_jp', 'ignore') myunichr(x).encode('iso_2022_jp', 'ignore')

View file

@ -145,7 +145,7 @@ class TestBase:
def test_incrementalencoder(self): def test_incrementalencoder(self):
UTF8Reader = codecs.getreader('utf-8') UTF8Reader = codecs.getreader('utf-8')
for sizehint in [None] + range(1, 33) + \ for sizehint in [None] + list(range(1, 33)) + \
[64, 128, 256, 512, 1024]: [64, 128, 256, 512, 1024]:
istream = UTF8Reader(StringIO(self.tstring[1])) istream = UTF8Reader(StringIO(self.tstring[1]))
ostream = StringIO() ostream = StringIO()
@ -165,7 +165,7 @@ class TestBase:
def test_incrementaldecoder(self): def test_incrementaldecoder(self):
UTF8Writer = codecs.getwriter('utf-8') UTF8Writer = codecs.getwriter('utf-8')
for sizehint in [None, -1] + range(1, 33) + \ for sizehint in [None, -1] + list(range(1, 33)) + \
[64, 128, 256, 512, 1024]: [64, 128, 256, 512, 1024]:
istream = StringIO(self.tstring[0]) istream = StringIO(self.tstring[0])
ostream = UTF8Writer(StringIO()) ostream = UTF8Writer(StringIO())
@ -203,7 +203,7 @@ class TestBase:
def test_streamreader(self): def test_streamreader(self):
UTF8Writer = codecs.getwriter('utf-8') UTF8Writer = codecs.getwriter('utf-8')
for name in ["read", "readline", "readlines"]: for name in ["read", "readline", "readlines"]:
for sizehint in [None, -1] + range(1, 33) + \ for sizehint in [None, -1] + list(range(1, 33)) + \
[64, 128, 256, 512, 1024]: [64, 128, 256, 512, 1024]:
istream = self.reader(StringIO(self.tstring[0])) istream = self.reader(StringIO(self.tstring[0]))
ostream = UTF8Writer(StringIO()) ostream = UTF8Writer(StringIO())
@ -223,7 +223,7 @@ class TestBase:
readfuncs = ('read', 'readline', 'readlines') readfuncs = ('read', 'readline', 'readlines')
UTF8Reader = codecs.getreader('utf-8') UTF8Reader = codecs.getreader('utf-8')
for name in readfuncs: for name in readfuncs:
for sizehint in [None] + range(1, 33) + \ for sizehint in [None] + list(range(1, 33)) + \
[64, 128, 256, 512, 1024]: [64, 128, 256, 512, 1024]:
istream = UTF8Reader(StringIO(self.tstring[1])) istream = UTF8Reader(StringIO(self.tstring[1]))
ostream = self.writer(StringIO()) ostream = self.writer(StringIO())

View file

@ -113,7 +113,7 @@ class Horrid:
def fill_dict(d, candidates, numentries): def fill_dict(d, candidates, numentries):
d.clear() d.clear()
for i in xrange(numentries): for i in range(numentries):
d[Horrid(random.choice(candidates))] = \ d[Horrid(random.choice(candidates))] = \
Horrid(random.choice(candidates)) Horrid(random.choice(candidates))
return list(d.keys()) return list(d.keys())
@ -152,7 +152,7 @@ def test_one(n):
# leak). # leak).
def test(n): def test(n):
for i in xrange(n): for i in range(n):
test_one(random.randrange(1, 100)) test_one(random.randrange(1, 100))
# See last comment block for clues about good values for n. # See last comment block for clues about good values for n.

View file

@ -138,7 +138,7 @@ class OperatorTestCase(unittest.TestCase):
self.assert_(a == [4, 2, 1]) self.assert_(a == [4, 2, 1])
def test_delslice(self): def test_delslice(self):
a = range(10) a = list(range(10))
self.failUnlessRaises(TypeError, operator.delslice, a) self.failUnlessRaises(TypeError, operator.delslice, a)
self.failUnlessRaises(TypeError, operator.delslice, a, None, None) self.failUnlessRaises(TypeError, operator.delslice, a, None, None)
self.failUnless(operator.delslice(a, 2, 8) is None) self.failUnless(operator.delslice(a, 2, 8) is None)
@ -163,7 +163,7 @@ class OperatorTestCase(unittest.TestCase):
self.failUnless(operator.getitem(a, 2) == 2) self.failUnless(operator.getitem(a, 2) == 2)
def test_getslice(self): def test_getslice(self):
a = range(10) a = list(range(10))
self.failUnlessRaises(TypeError, operator.getslice) self.failUnlessRaises(TypeError, operator.getslice)
self.failUnlessRaises(TypeError, operator.getslice, a, None, None) self.failUnlessRaises(TypeError, operator.getslice, a, None, None)
self.failUnless(operator.getslice(a, 4, 6) == [4, 5]) self.failUnless(operator.getslice(a, 4, 6) == [4, 5])
@ -200,7 +200,7 @@ class OperatorTestCase(unittest.TestCase):
self.failUnlessRaises(TypeError, operator.isSequenceType) self.failUnlessRaises(TypeError, operator.isSequenceType)
self.failUnless(operator.isSequenceType(dir())) self.failUnless(operator.isSequenceType(dir()))
self.failUnless(operator.isSequenceType(())) self.failUnless(operator.isSequenceType(()))
self.failUnless(operator.isSequenceType(xrange(10))) self.failUnless(operator.isSequenceType(range(10)))
self.failUnless(operator.isSequenceType('yeahbuddy')) self.failUnless(operator.isSequenceType('yeahbuddy'))
self.failIf(operator.isSequenceType(3)) self.failIf(operator.isSequenceType(3))
class Dict(dict): pass class Dict(dict): pass
@ -253,7 +253,7 @@ class OperatorTestCase(unittest.TestCase):
self.assertRaises(TypeError, operator.pow, 1, 2, 3) self.assertRaises(TypeError, operator.pow, 1, 2, 3)
def test_repeat(self): def test_repeat(self):
a = range(3) a = list(range(3))
self.failUnlessRaises(TypeError, operator.repeat) self.failUnlessRaises(TypeError, operator.repeat)
self.failUnlessRaises(TypeError, operator.repeat, a, None) self.failUnlessRaises(TypeError, operator.repeat, a, None)
self.failUnless(operator.repeat(a, 2) == a+a) self.failUnless(operator.repeat(a, 2) == a+a)
@ -291,7 +291,7 @@ class OperatorTestCase(unittest.TestCase):
self.failIf(operator.contains(range(4), 5)) self.failIf(operator.contains(range(4), 5))
def test_setitem(self): def test_setitem(self):
a = range(3) a = list(range(3))
self.failUnlessRaises(TypeError, operator.setitem, a) self.failUnlessRaises(TypeError, operator.setitem, a)
self.failUnlessRaises(TypeError, operator.setitem, a, None, None) self.failUnlessRaises(TypeError, operator.setitem, a, None, None)
self.failUnless(operator.setitem(a, 0, 2) is None) self.failUnless(operator.setitem(a, 0, 2) is None)
@ -299,7 +299,7 @@ class OperatorTestCase(unittest.TestCase):
self.assertRaises(IndexError, operator.setitem, a, 4, 2) self.assertRaises(IndexError, operator.setitem, a, 4, 2)
def test_setslice(self): def test_setslice(self):
a = range(4) a = list(range(4))
self.failUnlessRaises(TypeError, operator.setslice, a) self.failUnlessRaises(TypeError, operator.setslice, a)
self.failUnlessRaises(TypeError, operator.setslice, a, None, None, None) self.failUnlessRaises(TypeError, operator.setslice, a, None, None, None)
self.failUnless(operator.setslice(a, 1, 3, [2, 1]) is None) self.failUnless(operator.setslice(a, 1, 3, [2, 1]) is None)
@ -459,7 +459,7 @@ def test_main(verbose=None):
if verbose and hasattr(sys, "gettotalrefcount"): if verbose and hasattr(sys, "gettotalrefcount"):
import gc import gc
counts = [None] * 5 counts = [None] * 5
for i in xrange(len(counts)): for i in range(len(counts)):
test_support.run_unittest(*test_classes) test_support.run_unittest(*test_classes)
gc.collect() gc.collect()
counts[i] = sys.gettotalrefcount() counts[i] = sys.gettotalrefcount()

View file

@ -220,7 +220,7 @@ def test_main(verbose=None):
if verbose and hasattr(sys, "gettotalrefcount"): if verbose and hasattr(sys, "gettotalrefcount"):
import gc import gc
counts = [None] * 5 counts = [None] * 5
for i in xrange(len(counts)): for i in range(len(counts)):
test_support.run_unittest(*test_classes) test_support.run_unittest(*test_classes)
gc.collect() gc.collect()
counts[i] = sys.gettotalrefcount() counts[i] = sys.gettotalrefcount()

View file

@ -36,7 +36,8 @@ class ExceptionClassTests(unittest.TestCase):
last_exc = getattr(__builtin__, superclass_name) last_exc = getattr(__builtin__, superclass_name)
except AttributeError: except AttributeError:
self.fail("base class %s not a built-in" % superclass_name) self.fail("base class %s not a built-in" % superclass_name)
self.failUnless(superclass_name in exc_set) self.failUnless(superclass_name in exc_set,
'%s not found' % superclass_name)
exc_set.discard(superclass_name) exc_set.discard(superclass_name)
superclasses = [] # Loop will insert base exception superclasses = [] # Loop will insert base exception
last_depth = 0 last_depth = 0

View file

@ -19,7 +19,7 @@ class PowTest(unittest.TestCase):
if i != 30 : pow2 = pow2*2 if i != 30 : pow2 = pow2*2
for othertype in int, int: for othertype in int, int:
for i in range(-10, 0) + range(1, 10): for i in list(range(-10, 0)) + list(range(1, 10)):
ii = type(i) ii = type(i)
for j in range(1, 11): for j in range(1, 11):
jj = -othertype(j) jj = -othertype(j)

View file

@ -33,8 +33,8 @@ class dict3(dict):
class QueryTestCase(unittest.TestCase): class QueryTestCase(unittest.TestCase):
def setUp(self): def setUp(self):
self.a = range(100) self.a = list(range(100))
self.b = range(200) self.b = list(range(200))
self.a[-12] = self.b self.a[-12] = self.b
def test_basic(self): def test_basic(self):

View file

@ -60,7 +60,7 @@ class PwdTest(unittest.TestCase):
fakename = allnames[namei] fakename = allnames[namei]
while fakename in bynames: while fakename in bynames:
chars = map(None, fakename) chars = map(None, fakename)
for i in xrange(len(chars)): for i in range(len(chars)):
if chars[i] == 'z': if chars[i] == 'z':
chars[i] = 'A' chars[i] = 'A'
break break

View file

@ -243,7 +243,7 @@ def QueueJoinTest(q):
cum = 0 cum = 0
for i in (0,1): for i in (0,1):
threading.Thread(target=worker, args=(q,)).start() threading.Thread(target=worker, args=(q,)).start()
for i in xrange(100): for i in range(100):
q.put(i) q.put(i)
q.join() q.join()
verify(cum==sum(range(100)), "q.join() did not block until all tasks were done") verify(cum==sum(range(100)), "q.join() did not block until all tasks were done")

Some files were not shown because too many files have changed in this diff Show more