]> granicus.if.org Git - python/commitdiff
Merged revisions 55007-55179 via svnmerge from
authorGuido van Rossum <guido@python.org>
Mon, 7 May 2007 22:24:25 +0000 (22:24 +0000)
committerGuido van Rossum <guido@python.org>
Mon, 7 May 2007 22:24:25 +0000 (22:24 +0000)
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).
........

150 files changed:
Demo/tix/grid.py
Doc/lib/libdbhash.tex
Doc/lib/libfuncs.tex
Doc/lib/libitertools.tex
Doc/lib/librandom.tex
Doc/lib/libstdtypes.tex
Doc/lib/libtimeit.tex
Doc/lib/libtypes.tex
Doc/tut/tut.tex
Doc/whatsnew/Makefile [deleted file]
Lib/Cookie.py
Lib/bsddb/test/test_thread.py
Lib/calendar.py
Lib/copy.py
Lib/ctypes/test/test_arrays.py
Lib/ctypes/test/test_slicing.py
Lib/difflib.py
Lib/distutils/command/install.py
Lib/doctest.py
Lib/genericpath.py
Lib/gettext.py
Lib/heapq.py
Lib/hmac.py
Lib/idlelib/CodeContext.py
Lib/mhlib.py
Lib/pickle.py
Lib/plat-mac/EasyDialogs.py
Lib/plat-mac/applesingle.py
Lib/plat-riscos/riscospath.py
Lib/popen2.py
Lib/pydoc.py
Lib/random.py
Lib/sqlite3/test/regression.py
Lib/sre_compile.py
Lib/string.py
Lib/stringprep.py
Lib/subprocess.py
Lib/tarfile.py
Lib/tempfile.py
Lib/test/fork_wait.py
Lib/test/list_tests.py
Lib/test/output/test_cProfile
Lib/test/output/test_profile
Lib/test/pickletester.py
Lib/test/seq_tests.py
Lib/test/sortperf.py
Lib/test/string_tests.py
Lib/test/test_array.py
Lib/test/test_binascii.py
Lib/test/test_bisect.py
Lib/test/test_bsddb.py
Lib/test/test_bufio.py
Lib/test/test_builtin.py
Lib/test/test_bz2.py
Lib/test/test_calendar.py
Lib/test/test_codeccallbacks.py
Lib/test/test_codecs.py
Lib/test/test_compile.py
Lib/test/test_complex.py
Lib/test/test_contains.py
Lib/test/test_copy.py
Lib/test/test_csv.py
Lib/test/test_datetime.py
Lib/test/test_decimal.py
Lib/test/test_deque.py
Lib/test/test_descr.py
Lib/test/test_dis.py
Lib/test/test_doctest.py
Lib/test/test_dummy_thread.py
Lib/test/test_enumerate.py
Lib/test/test_functools.py
Lib/test/test_gc.py
Lib/test/test_generators.py
Lib/test/test_genexps.py
Lib/test/test_grp.py
Lib/test/test_heapq.py
Lib/test/test_index.py
Lib/test/test_io.py
Lib/test/test_isinstance.py
Lib/test/test_iter.py
Lib/test/test_iterlen.py
Lib/test/test_itertools.py
Lib/test/test_list.py
Lib/test/test_listcomps.py
Lib/test/test_logging.py
Lib/test/test_long.py
Lib/test/test_mailbox.py
Lib/test/test_mhlib.py
Lib/test/test_mimetools.py
Lib/test/test_mmap.py
Lib/test/test_multibytecodec.py
Lib/test/test_multibytecodec_support.py
Lib/test/test_mutants.py
Lib/test/test_operator.py
Lib/test/test_peepholer.py
Lib/test/test_pep352.py
Lib/test/test_pow.py
Lib/test/test_pprint.py
Lib/test/test_pwd.py
Lib/test/test_queue.py
Lib/test/test_random.py
Lib/test/test_repr.py
Lib/test/test_richcmp.py
Lib/test/test_set.py
Lib/test/test_setcomps.py
Lib/test/test_slice.py
Lib/test/test_sort.py
Lib/test/test_struct.py
Lib/test/test_structseq.py
Lib/test/test_tempfile.py
Lib/test/test_trace.py
Lib/test/test_tuple.py
Lib/test/test_ucn.py
Lib/test/test_unicode.py
Lib/test/test_unicodedata.py
Lib/test/test_userdict.py
Lib/test/test_userlist.py
Lib/test/test_warnings.py
Lib/test/test_winsound.py
Lib/test/test_xdrlib.py
Lib/test/test_xrange.py
Lib/test/test_zipfile.py
Lib/test/test_zipfile64.py
Lib/test/time_hashlib.py
Lib/types.py
Lib/urllib.py
Misc/NEWS
Objects/rangeobject.c
Parser/asdl.py
Parser/asdl_c.py
Parser/spark.py
Python/bltinmodule.c
Tools/pybench/Arithmetic.py
Tools/pybench/Calls.py
Tools/pybench/Constructs.py
Tools/pybench/Dict.py
Tools/pybench/Exceptions.py
Tools/pybench/Imports.py
Tools/pybench/Instances.py
Tools/pybench/Lists.py
Tools/pybench/Lookups.py
Tools/pybench/NewInstances.py
Tools/pybench/Numbers.py
Tools/pybench/Strings.py
Tools/pybench/Tuples.py
Tools/pybench/Unicode.py
Tools/pybench/systimes.py
Tools/scripts/reindent.py
Tools/unicode/makeunicodedata.py
Tools/unicode/mkstringprep.py

index 07ca87f8e95e84fd881cdd0fb88f37bdbfef65c2..79b888642246c108cdbe00d0ea88d67457787ae8 100644 (file)
@@ -18,8 +18,8 @@ class MyGrid(tk.Grid):
 g = MyGrid(r, name="a_grid",
 selectunit="cell")
 g.pack(fill=tk.BOTH)
-for x in xrange(5):
-    for y in xrange(5):
+for x in range(5):
+    for y in range(5):
         g.set(x,y,text=str((x,y)))
 
 c = tk.Button(r, text="Close", command=r.destroy)
index cf4470721eabc5ac80af26e0f56d83b4c41e671b..5852b732ae85ffb4a6e1cf571b4104452bda6aa7 100644 (file)
@@ -72,7 +72,7 @@ methods are available in addition to the standard methods.
 
 \begin{verbatim}
 print db.first()
-for i in xrange(1, len(db)):
+for i in range(1, len(db)):
     print db.next()
 \end{verbatim}
 \end{methoddesc}
index 09003174f3d5f0c31dd4e4057469a68fd4614200..c02f6f1f9e55365ebef2888cc5416cfd4b7f9922 100644 (file)
@@ -868,7 +868,7 @@ class Parrot(object):
 \end{funcdesc}
 
 \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
   arguments must be plain integers.  If the \var{step} 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:
 
 \begin{verbatim}
->>> range(10)
+>>> list(range(10))
 [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]
->>> range(0, 30, 5)
+>>> list(range(0, 30, 5))
 [0, 5, 10, 15, 20, 25]
->>> range(0, 10, 3)
+>>> list(range(0, 10, 3))
 [0, 3, 6, 9]
->>> range(0, -10, -1)
+>>> list(range(0, -10, -1))
 [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{funcdesc}
@@ -1230,24 +1230,6 @@ class C(B):
     other scopes (such as modules) can be.  This may change.}
 \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}}
   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.
index a2f37d737db0aa7e869865152fab9f177c168d92..681738de77ff3b7e3127a8a9f63bf436906066c1 100644 (file)
@@ -161,7 +161,7 @@ by functions or loops that truncate the stream.
                 key = lambda x: x
             self.keyfunc = key
             self.it = iter(iterable)
-            self.tgtkey = self.currkey = self.currvalue = xrange(0)
+            self.tgtkey = self.currkey = self.currvalue = []
         def __iter__(self):
             return self
         def __next__(self):
@@ -252,7 +252,7 @@ by functions or loops that truncate the stream.
   \begin{verbatim}
      def islice(iterable, *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)
          for i, element in enumerate(iterable):
              if i == nexti:
@@ -342,7 +342,7 @@ by functions or loops that truncate the stream.
              while True:
                  yield object
          else:
-             for i in xrange(times):
+             for i in range(times):
                  yield object
   \end{verbatim}
 \end{funcdesc}
@@ -425,7 +425,7 @@ Check 1201 is for $764.05
 Check 1202 is for $823.14
 
 >>> 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
 ...
 1
index 78c536b32169b2de2ae8012427fcfe132a1cb327..a9bd5ac0237c63cd9cfc22d3ef480aa885fa3a95 100644 (file)
@@ -163,9 +163,9 @@ Functions for sequences:
   population contains repeats, then each occurrence is a possible
   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
-  sampling from a large population:  \code{sample(xrange(10000000), 60)}.
+  sampling from a large population:  \code{sample(range(10000000), 60)}.
 \end{funcdesc}
 
 
index 0c45f18760eb008c15cc13713e35f21e5301f6aa..ef8415737d00d8990aff4227a19dc18342e8ab39 100644 (file)
@@ -403,11 +403,11 @@ methods.
 
 \section{Sequence Types ---
            \class{str}, \class{unicode}, \class{list},
-           \class{tuple}, \class{buffer}, \class{xrange}
+           \class{tuple}, \class{buffer}, \class{range}
            \label{typesseq}}
 
 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:
 \code{'xyzzy'}, \code{"frobozz"}.  See chapter 2 of the
@@ -433,11 +433,11 @@ concatenation or repetition.
 \obindex{buffer}
 
 Xrange objects are similar to buffers in that there is no specific
-syntax to create them, but they are created using the \function{xrange()}
-function.\bifuncindex{xrange}  They don't support slicing,
+syntax to create them, but they are created using the \function{range()}
+function.\bifuncindex{range}  They don't support slicing,
 concatenation or repetition, and using \code{in}, \code{not in},
 \function{min()} or \function{max()} on them is inefficient.
-\obindex{xrange}
+\obindex{range}
 
 Most sequence types support the following operations.  The \samp{in} and
 \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}
 
 
-\subsection{XRange Type \label{typesseq-xrange}}
+\subsection{XRange Type \label{typesseq-range}}
 
-The \class{xrange}\obindex{xrange} type is an immutable sequence which
-is commonly used for looping.  The advantage of the \class{xrange}
-type is that an \class{xrange} object will always take the same amount
+The \class{range}\obindex{range} type is an immutable sequence which
+is commonly used for looping.  The advantage of the \class{range}
+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
 no consistent performance advantages.
 
index 7f38a7eab1bacf63556481cc2d746aafdf4198ba..968728f58ffbefd7b6a3a9b335916483826f70d5 100644 (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
 \var{setup} string.  For example:
 \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{notice}
 \end{methoddesc}
index c80a87aba52b877a181438dc94a04f87a8a10654..455430570f3981ccfeb9dd5e4c0ad9ed2dda7ffd 100644 (file)
@@ -147,9 +147,9 @@ The type of modules.
 The type of open file objects such as \code{sys.stdout}.
 \end{datadesc}
 
-\begin{datadesc}{XRangeType}
+\begin{datadesc}{RangeType}
 The type of range objects returned by
-\function{xrange()}\bifuncindex{xrange}.
+\function{range()}\bifuncindex{range}.
 \end{datadesc}
 
 \begin{datadesc}{SliceType}
index a5e535ddb516209735298ace0b6481cecf69d19f..6558be2abe4c40f5cde5483d5601abfe80e63138 100644 (file)
@@ -2260,7 +2260,7 @@ in a forward direction and then call the \function{reversed()}
 function.
 
 \begin{verbatim}
->>> for i in reversed(xrange(1,10,2)):
+>>> for i in reversed(range(1,10,2)):
 ...     print i
 ...
 9
@@ -2700,12 +2700,12 @@ standard module \module{__builtin__}\refbimodindex{__builtin__}:
  'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod',
  'enumerate', 'eval', 'exec', 'execfile', 'exit', 'file', 'filter', 'float',
  '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',
  'object', 'oct', 'open', 'ord', 'pow', 'property', 'quit', 'range',
  'reload', 'repr', 'reversed', 'round', 'set',
  'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super',
- 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip']
+ 'tuple', 'type', 'unichr', 'unicode', 'vars', 'zip']
 \end{verbatim}
 
 
@@ -4762,7 +4762,7 @@ module provides tools for making random selections:
 >>> import random
 >>> random.choice(['apple', 'pear', 'banana'])
 '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]
 >>> random.random()    # random float
 0.17970987693706186
diff --git a/Doc/whatsnew/Makefile b/Doc/whatsnew/Makefile
deleted file mode 100644 (file)
index d11f97b..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-
-check:
-       ../../python.exe ../../Tools/scripts/texcheck.py whatsnew25.tex
index 4a34ff46ac12376ee8511eaabe757616e63490d5..153adc5684bff7669ab0565607339e03b3dcbf1b 100644 (file)
@@ -305,7 +305,7 @@ _Translator       = {
     '\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):
     #
index eabf96a72154d237d854f46048362962539383f6..fca4466f9a7f474cb01bd0637243cdc3e10f6891 100644 (file)
@@ -229,7 +229,7 @@ class SimpleThreadedBase(BaseThreadedTestCase):
             print("%s: creating records %d - %d" % (name, start, stop))
 
         # create a bunch of records
-        for x in xrange(start, stop):
+        for x in range(start, stop):
             key = '%04d' % x
             dbutils.DeadlockWrap(d.put, key, self.makeData(key),
                                  max_retries=12)
@@ -239,7 +239,7 @@ class SimpleThreadedBase(BaseThreadedTestCase):
 
             # do a bit or reading too
             if random() <= 0.05:
-                for y in xrange(start, x):
+                for y in range(start, x):
                     key = '%04d' % x
                     data = dbutils.DeadlockWrap(d.get, key, max_retries=12)
                     self.assertEqual(data, self.makeData(key))
@@ -252,7 +252,7 @@ class SimpleThreadedBase(BaseThreadedTestCase):
                 print("could not complete sync()...")
 
         # read them back, deleting a few
-        for x in xrange(start, stop):
+        for x in range(start, stop):
             key = '%04d' % x
             data = dbutils.DeadlockWrap(d.get, key, max_retries=12)
             if verbose and x % 100 == 0:
index 149c7adadb1961e5aff6f3a718807368bc6cffb4..e243255b6793a1926ec464e6fdba92c9489a3b6d 100644 (file)
@@ -45,7 +45,7 @@ mdays = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
 
 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: "")
 
     def __init__(self, format):
@@ -65,7 +65,7 @@ class _localized_month:
 class _localized_day:
 
     # 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):
         self.format = format
@@ -144,7 +144,7 @@ class Calendar(object):
         Return a iterator for one week of weekday numbers starting with the
         configured first one.
         """
-        for i in xrange(self.firstweekday, self.firstweekday + 7):
+        for i in range(self.firstweekday, self.firstweekday + 7):
             yield i%7
 
     def itermonthdates(self, year, month):
@@ -192,7 +192,7 @@ class Calendar(object):
         Each row represents a week; week entries are datetime.date values.
         """
         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):
         """
@@ -202,7 +202,7 @@ class Calendar(object):
         are zero.
         """
         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):
         """
@@ -210,7 +210,7 @@ class Calendar(object):
         Each row represents a week; days outside this month are zero.
         """
         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):
         """
@@ -221,9 +221,9 @@ class Calendar(object):
         """
         months = [
             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):
         """
@@ -234,9 +234,9 @@ class Calendar(object):
         """
         months = [
             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):
         """
@@ -246,9 +246,9 @@ class Calendar(object):
         """
         months = [
             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):
@@ -341,7 +341,7 @@ class TextCalendar(Calendar):
         header = self.formatweekheader(w)
         for (i, row) in enumerate(self.yeardays2calendar(theyear, m)):
             # 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)
             names = (self.formatmonthname(theyear, k, colwidth, False)
                      for k in months)
@@ -352,7 +352,7 @@ class TextCalendar(Calendar):
             a('\n'*l)
             # max number of weeks for this row
             height = max(len(cal) for cal in row)
-            for j in xrange(height):
+            for j in range(height):
                 weeks = []
                 for cal in row:
                     if j >= len(cal):
@@ -444,9 +444,9 @@ class HTMLCalendar(Calendar):
         a('<table border="0" cellpadding="0" cellspacing="0" class="year">')
         a('\n')
         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 = xrange(i, min(i+width, 13))
+            months = range(i, min(i+width, 13))
             a('<tr>')
             for m in months:
                 a('<td>')
index fae57c272428829464a157804d625a7635a6b577..cba83c1f3dfdd65302705d6117e3e152ef4baea2 100644 (file)
@@ -100,7 +100,7 @@ _copy_dispatch = d = {}
 def _copy_immutable(x):
     return x
 for t in (type(None), int, float, bool, str, tuple,
-          frozenset, type, xrange, types.ClassType,
+          frozenset, type, range, types.ClassType,
           types.BuiltinFunctionType,
           types.FunctionType):
     d[t] = _copy_immutable
@@ -194,7 +194,7 @@ try:
 except AttributeError:
     pass
 d[type] = _deepcopy_atomic
-d[xrange] = _deepcopy_atomic
+d[range] = _deepcopy_atomic
 d[types.ClassType] = _deepcopy_atomic
 d[types.BuiltinFunctionType] = _deepcopy_atomic
 d[types.FunctionType] = _deepcopy_atomic
index c812ff627d11a88189285ab9a51ad3e972b2243b..e94e9bd519115b21d555ab58eb4b62181e387b49 100644 (file)
@@ -11,7 +11,7 @@ class ArrayTestCase(unittest.TestCase):
         # create classes holding simple numeric types, and check
         # various properties.
 
-        init = range(15, 25)
+        init = list(range(15, 25))
 
         for fmt in formats:
             alen = len(init)
@@ -27,7 +27,7 @@ class ArrayTestCase(unittest.TestCase):
 
             # change the items
             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)]
             values = [ia[i] for i in range(len(init))]
             self.failUnlessEqual(values, new_values)
index 54fbfaaad530e599b3b57add0076fa6f6e37b310..8e43a395199c23b79418b316692c4d2941c8e849 100644 (file)
@@ -5,8 +5,8 @@ import _ctypes_test
 
 class SlicesTestCase(unittest.TestCase):
     def test_getslice_cint(self):
-        a = (c_int * 100)(*xrange(1100, 1200))
-        b = range(1100, 1200)
+        a = (c_int * 100)(*range(1100, 1200))
+        b = list(range(1100, 1200))
         self.failUnlessEqual(a[0:2], b[0:2])
         self.failUnlessEqual(len(a), len(b))
         self.failUnlessEqual(a[5:7], b[5:7])
@@ -14,14 +14,14 @@ class SlicesTestCase(unittest.TestCase):
         self.failUnlessEqual(a[:], b[:])
 
         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):
-        a = (c_int * 100)(*xrange(1100, 1200))
-        b = range(1100, 1200)
+        a = (c_int * 100)(*range(1100, 1200))
+        b = list(range(1100, 1200))
 
-        a[32:47] = range(32, 47)
-        self.failUnlessEqual(a[32:47], range(32, 47))
+        a[32:47] = list(range(32, 47))
+        self.failUnlessEqual(a[32:47], list(range(32, 47)))
 
         from operator import setslice
 
@@ -50,7 +50,7 @@ class SlicesTestCase(unittest.TestCase):
 
         dll.my_strdup.restype = POINTER(c_byte)
         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)
 
     def test_char_ptr_with_free(self):
@@ -111,7 +111,8 @@ class SlicesTestCase(unittest.TestCase):
             else:
                 return
             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)
 
 ################################################################
index 5b42d072aec0f3e090fac502d64bdc2842339097..601479cbfd4554663576d4b181a5ce94e900012b 100644 (file)
@@ -407,7 +407,7 @@ class SequenceMatcher:
         # junk-free match ending with a[i-1] and b[j]
         j2len = {}
         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
             # b2j has no junk keys, the loop is skipped if a[i] is junk
             j2lenget = j2len.get
@@ -921,7 +921,7 @@ class Differ:
 
     def _dump(self, tag, x, lo, hi):
         """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])
 
     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
         # (identical lines must be junk lines, & we don't want to synch up
         # on junk -- unless we have to)
-        for j in xrange(blo, bhi):
+        for j in range(blo, bhi):
             bj = b[j]
             cruncher.set_seq2(bj)
-            for i in xrange(alo, ahi):
+            for i in range(alo, ahi):
                 ai = a[i]
                 if ai == bj:
                     if eqi is None:
index cc92e96368101ebdf19f4e84e383cf0e60cfd33f..a6543ba6a206da9635808b9403dc7bcf79e5c00f 100644 (file)
@@ -517,7 +517,7 @@ class install (Command):
             outputs = self.get_outputs()
             if self.root:               # strip any package prefix
                 root_len = len(self.root)
-                for counter in xrange(len(outputs)):
+                for counter in range(len(outputs)):
                     outputs[counter] = outputs[counter][root_len:]
             self.execute(write_file,
                          (self.record, outputs),
index cb29fcb7824d0b5e78b3bd5d02e4e1bbbf7af1bf..bd7a91834641010c597da9c71ab06ef1786531d1 100644 (file)
@@ -2610,14 +2610,14 @@ __test__ = {"_TestClass": _TestClass,
             "ellipsis": r"""
                 If the ellipsis flag is used, then '...' can be used to
                 elide substrings in the desired output:
-                    >>> print(range(1000)) #doctest: +ELLIPSIS
+                    >>> print(list(range(1000))) #doctest: +ELLIPSIS
                     [0, 1, 2, ..., 999]
             """,
 
             "whitespace normalization": r"""
                 If the whitespace normalization flag is used, then
                 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,
                      15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
                      27, 28, 29]
index e2bc7da0abad753d89431a89c76558c8d6c79aaf..ef8ea7fd4efa9fdf928244fe5c179192c9bc5665 100644 (file)
@@ -71,7 +71,7 @@ def commonprefix(m):
     s1 = min(m)
     s2 = max(m)
     n = min(len(s1), len(s2))
-    for i in xrange(n):
+    for i in range(n):
         if s1[i] != s2[i]:
             return s1[:i]
     return s1[:n]
index ffe48244b852252c0aee5f48740f8e33ff3afaa7..311e923861d0f685d623fac0620b641be209b744 100644 (file)
@@ -281,7 +281,7 @@ class GNUTranslations(NullTranslations):
             raise IOError(0, 'Bad magic number', filename)
         # Now put all messages from the .mo file buffer into the catalog
         # dictionary.
-        for i in xrange(0, msgcount):
+        for i in range(0, msgcount):
             mlen, moff = unpack(ii, buf[masteridx:masteridx+8])
             mend = moff + mlen
             tlen, toff = unpack(ii, buf[transidx:transidx+8])
index d34ea3b3752b1c8c4dca6fa10883ffe1f16454be..f64d8ba8628bf90f5654b4cb9e4ef7870d65060c 100644 (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
     # 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.
-    for i in reversed(xrange(n//2)):
+    for i in reversed(range(n//2)):
         _siftup(x, i)
 
 def nlargest(n, iterable):
index 88c3fd5377a56c651df305d0f570b10a3b8f0fb8..52af5909e19d6f3749058fc42fa310636ae07c33 100644 (file)
@@ -3,8 +3,8 @@
 Implements the HMAC algorithm as described by RFC 2104.
 """
 
-trans_5C = "".join ([chr (x ^ 0x5C) for x in xrange(256)])
-trans_36 = "".join ([chr (x ^ 0x36) 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 range(256)])
 
 # The size of the digests returned by HMAC depends on the underlying
 # hashing module used.  Use digest_size from the instance of HMAC instead.
index 420ec339ca2704f3ce9b761eb4a2a332abeaf153..2037d6fffd0ca11145502da68e7b5d2cd26c4fb0 100644 (file)
@@ -117,7 +117,7 @@ class CodeContext:
         lastindent = INFINITY
         # For a line to be interesting, it must begin with a block opening
         # 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)
             if indent < lastindent:
                 lastindent = indent
index 64aa6f74b21eb88b43df4a3f061028cc141da74d..cbe8cb1dd617104ca5c48d1cfdffa6e87a2cbd72 100644 (file)
@@ -828,7 +828,7 @@ class IntSet:
     def tolist(self):
         l = []
         for lo, hi in self.pairs:
-            m = range(lo, hi+1)
+            m = list(range(lo, hi+1))
             l = l + m
         return l
 
index 6b33514c847cfa12bc435a4221778d147923d2a9..675fa1f4041dde9e8baa14692871d0831bf7b422 100644 (file)
@@ -604,7 +604,7 @@ class Pickler:
                 write(APPEND)
             return
 
-        r = xrange(self._BATCHSIZE)
+        r = range(self._BATCHSIZE)
         while items is not None:
             tmp = []
             for i in r:
@@ -652,7 +652,7 @@ class Pickler:
                 write(SETITEM)
             return
 
-        r = xrange(self._BATCHSIZE)
+        r = range(self._BATCHSIZE)
         while items is not None:
             tmp = []
             for i in r:
index dfed24f13abf6e9f76192ac153e038a060f1b5a7..e33b24e5dd70f91fc241a8cf3a2baa5b4e420c9f 100644 (file)
@@ -814,11 +814,11 @@ def test():
     try:
         if hasattr(MacOS, 'SchedParams'):
             appsw = MacOS.SchedParams(1, 0)
-        for i in xrange(20):
+        for i in range(20):
             bar.inc()
             time.sleep(0.05)
         bar.set(0,100)
-        for i in xrange(100):
+        for i in range(100):
             bar.set(i)
             time.sleep(0.05)
             if i % 10 == 0:
index 2e0e96708a14fc194e1ceb0b9f5879c600fd847e..d29ad23e2e78e44739496826f35f1a58ed6e9c04 100644 (file)
@@ -60,7 +60,7 @@ class AppleSingle(object):
             raise Error, "Unknown AppleSingle version number 0x%8.8x" % (version,)
         if nentry <= 0:
             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 = []
         for hdr in headers:
             try:
index af89eb3d6cb2694a550941bb6e4247c89d5cd13e..b9d1062d3037e966989f41ebd89e85e231263f0f 100644 (file)
@@ -174,7 +174,7 @@ def commonprefix(m):
     s1 = min(m)
     s2 = max(m)
     n = min(len(s1), len(s2))
-    for i in xrange(n):
+    for i in range(n):
         if s1[i] != s2[i]:
             return s1[:i]
     return s1[:n]
index ab30463e24ad0b730bf89c13d8ee42cdcecfc5d1..6c5cd6198dbdf9c898ed342c2111727f3af523fc 100644 (file)
@@ -79,7 +79,7 @@ class Popen3:
     def _run_child(self, cmd):
         if isinstance(cmd, basestring):
             cmd = ['/bin/sh', '-c', cmd]
-        for i in xrange(3, MAXFD):
+        for i in range(3, MAXFD):
             try:
                 os.close(i)
             except OSError:
index 6a272ce12880121525fe386a21c925abf07db233..5e91ad21ee0cd562fc125e39deee63e8a20b6430 100755 (executable)
@@ -1582,7 +1582,7 @@ class Helper:
         'INTEGER': ('ref/integers', 'int range'),
         'FLOAT': ('ref/floating', 'float math'),
         'COMPLEX': ('ref/imaginary', 'complex cmath'),
-        'SEQUENCES': ('lib/typesseq', 'STRINGMETHODS FORMATTING xrange LISTS'),
+        'SEQUENCES': ('lib/typesseq', 'STRINGMETHODS FORMATTING range LISTS'),
         'MAPPINGS': 'DICTIONARIES',
         'FUNCTIONS': ('lib/typesfunctions', 'def TYPES'),
         'METHODS': ('lib/typesmethods', 'class def CLASSES TYPES'),
index 99ae75027176553224b412da1d6ebb2cbb997d36..075c3b7926174ccfe6b85a5b9899b4aa7f944c50 100644 (file)
@@ -256,7 +256,7 @@ class Random(_random.Random):
 
         if random is None:
             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]
             j = int(random() * (i+1))
             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
         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
-        large population:   sample(xrange(10000000), 60)
+        large population:   sample(range(10000000), 60)
         """
 
         # 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
             # mapping type so the other algorithm wouldn't work.
             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))
                 result[i] = pool[j]
                 pool[j] = pool[n-i-1]   # move non-selected item into vacancy
@@ -319,7 +319,7 @@ class Random(_random.Random):
             try:
                 selected = set()
                 selected_add = selected.add
-                for i in xrange(k):
+                for i in range(k):
                     j = _int(random() * n)
                     while j in selected:
                         j = _int(random() * n)
index addedb17714d935a22b12e9672fc2a90e82ba724..df2a6fb96e7952de8f86e6e8e891284779d2359f 100644 (file)
@@ -51,10 +51,10 @@ class RegressionTests(unittest.TestCase):
         # reset before a rollback, but only those that are still in the
         # statement cache. The others are not accessible from the connection object.
         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)")
         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):
             cursors[i].execute(" " * i + "select x from test")
index 4f2fb0461279874ab1cdf6b337bd9e72d0400d4c..6b280520b3887a6f2d28680751cf9e2c747024d4 100644 (file)
@@ -318,7 +318,7 @@ def _optimize_unicode(charset, fixup):
             elif op is LITERAL:
                 charmap[fixup(av)] = 1
             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
             elif op is CATEGORY:
                 # XXX: could expand category
@@ -330,13 +330,13 @@ def _optimize_unicode(charset, fixup):
         if sys.maxunicode != 65535:
             # XXX: negation does not work with big charsets
             return charset
-        for i in xrange(65536):
+        for i in range(65536):
             charmap[i] = not charmap[i]
     comps = {}
     mapping = [0]*256
     block = 0
     data = []
-    for i in xrange(256):
+    for i in range(256):
         chunk = tuple(charmap[i*256:(i+1)*256])
         new = comps.setdefault(chunk, block)
         mapping[i] = new
@@ -461,7 +461,7 @@ def _compile_info(code, pattern, flags):
         code.extend(prefix)
         # generate overlap table
         table = [-1] + ([0]*len(prefix))
-        for i in xrange(len(prefix)):
+        for i in range(len(prefix)):
             table[i+1] = table[i]+1
             while table[i+1] > 0 and prefix[i] != prefix[table[i+1]-1]:
                 table[i+1] = table[table[i+1]-1]+1
index e5b5284572ff80d4a98015e320bddbabcd0ac41a..2bf4995cacf56a43766c05a3f3254d3ff7ff11f5 100644 (file)
@@ -30,7 +30,7 @@ printable = digits + letters + punctuation + whitespace
 
 # Case conversion helpers
 # Use str to convert Unicode literal in case of -U
-l = map(chr, xrange(256))
+l = map(chr, range(256))
 _idmap = str('').join(l)
 del l
 
index 5dbf91a9badd65430fbad64a91c57b8e77dd0915..44ecdb266ce8b95a0e5c9142ded9e43ac2e0235a 100644 (file)
@@ -16,7 +16,7 @@ def in_table_a1(code):
     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):
     return ord(code) in b1_set
 
@@ -217,7 +217,7 @@ def in_table_c11_c12(code):
 def in_table_c21(code):
     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):
     c = ord(code)
     if c < 128: return False
@@ -254,12 +254,12 @@ def in_table_c7(code):
     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):
     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):
     return ord(code) in c9_set
 
index 363c827f9f046618004c0b43060f90f364b8c64f..53d5db0eb1123d6e3186622254a058ad1e8c24c0 100644 (file)
@@ -969,7 +969,7 @@ class Popen(object):
 
 
         def _close_fds(self, but):
-            for i in xrange(3, MAXFD):
+            for i in range(3, MAXFD):
                 if i == but:
                     continue
                 try:
index 3eb77040490b3c2a00c222eb326bd6bc88e44845..36bdfa6ce075b362e89ac6b2bba7598e76a54e6b 100644 (file)
@@ -188,7 +188,7 @@ def nti(s):
             raise HeaderError("invalid header")
     else:
         n = 0
-        for i in xrange(len(s) - 1):
+        for i in range(len(s) - 1):
             n <<= 8
             n += ord(s[i + 1])
     return n
@@ -214,7 +214,7 @@ def itn(n, digits=8, format=DEFAULT_FORMAT):
             n = struct.unpack("L", struct.pack("l", n))[0]
 
         s = ""
-        for i in xrange(digits - 1):
+        for i in range(digits - 1):
             s = chr(n & 0377) + s
             n >>= 8
         s = chr(0200) + s
@@ -245,7 +245,7 @@ def copyfileobj(src, dst, length=None):
 
     BUFSIZE = 16 * 1024
     blocks, remainder = divmod(length, BUFSIZE)
-    for b in xrange(blocks):
+    for b in range(blocks):
         buf = src.read(BUFSIZE)
         if len(buf) < BUFSIZE:
             raise IOError("end of file reached")
@@ -514,7 +514,7 @@ class _Stream:
         """
         if pos - self.pos >= 0:
             blocks, remainder = divmod(pos - self.pos, self.bufsize)
-            for i in xrange(blocks):
+            for i in range(blocks):
                 self.read(self.bufsize)
             self.read(remainder)
         else:
@@ -1297,7 +1297,7 @@ class TarInfo(object):
         realpos = 0
         # There are 4 possible sparse structs in the
         # first header.
-        for i in xrange(4):
+        for i in range(4):
             try:
                 offset = nti(buf[pos:pos + 12])
                 numbytes = nti(buf[pos + 12:pos + 24])
@@ -1318,7 +1318,7 @@ class TarInfo(object):
         while isextended == 1:
             buf = tarfile.fileobj.read(BLOCKSIZE)
             pos = 0
-            for i in xrange(21):
+            for i in range(21):
                 try:
                     offset = nti(buf[pos:pos + 12])
                     numbytes = nti(buf[pos + 12:pos + 24])
@@ -2304,7 +2304,7 @@ class TarFile(object):
         else:
             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:
                 return members[i]
 
index b63a46a45b0e438dae598718cab20b93d0775195..bcd91893b5f906ef5c2ef522135a59b48c1fd1e5 100644 (file)
@@ -196,7 +196,7 @@ def _get_default_tempdir():
         if dir != _os.curdir:
             dir = _os.path.normcase(_os.path.abspath(dir))
         # Try only a few names per directory.
-        for seq in xrange(100):
+        for seq in range(100):
             name = next(namer)
             filename = _os.path.join(dir, name)
             try:
@@ -235,7 +235,7 @@ def _mkstemp_inner(dir, pre, suf, flags):
 
     names = _get_candidate_names()
 
-    for seq in xrange(TMP_MAX):
+    for seq in range(TMP_MAX):
         name = next(names)
         file = _os.path.join(dir, pre + name + suf)
         try:
@@ -327,7 +327,7 @@ def mkdtemp(suffix="", prefix=template, dir=None):
 
     names = _get_candidate_names()
 
-    for seq in xrange(TMP_MAX):
+    for seq in range(TMP_MAX):
         name = next(names)
         file = _os.path.join(dir, prefix + name + suffix)
         try:
@@ -362,7 +362,7 @@ def mktemp(suffix="", prefix=template, dir=None):
         dir = gettempdir()
 
     names = _get_candidate_names()
-    for seq in xrange(TMP_MAX):
+    for seq in range(TMP_MAX):
         name = next(names)
         file = _os.path.join(dir, prefix + name + suffix)
         if not _exists(file):
index 9c4df4b14d4915af586b764d1e8e1358e37ac188..3b222a8701ba1d2da1b34b4f097288d621b82299 100644 (file)
@@ -52,7 +52,7 @@ class ForkWait(unittest.TestCase):
         time.sleep(LONGSLEEP)
 
         a = sorted(self.alive.keys())
-        self.assertEquals(a, range(NUM_THREADS))
+        self.assertEquals(a, list(range(NUM_THREADS)))
 
         prefork_lives = self.alive.copy()
 
index ad1052365ebaa29d43e1425484bbccc190b1273c..a5790c3c9f7a35594a889787b868a24641d1f7d6 100644 (file)
@@ -47,9 +47,9 @@ class CommonTest(seq_tests.CommonTest):
         self.assertEqual(repr(a2), "[0, 1, 2, [...], 3]")
 
     def test_print(self):
-        d = self.type2test(xrange(200))
+        d = self.type2test(range(200))
         d.append(d)
-        d.extend(xrange(200,400))
+        d.extend(range(200,400))
         d.append(d)
         d.append(400)
         try:
@@ -398,7 +398,7 @@ class CommonTest(seq_tests.CommonTest):
                 del self.victim[:]
                 return False
         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
         self.assertRaises(ValueError, a.index, None)
 
index 973f47ac37f665151d429334c63cd5c418fb49a9..30d53b4f8963b032af10d63757bd71bb805291f4 100644 (file)
@@ -1,5 +1,5 @@
 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
 
@@ -18,7 +18,6 @@ test_cProfile
        12    0.000    0.000    0.012    0.001 {hasattr}
         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}
-        8    0.000    0.000    0.000    0.000 {range}
         4    0.000    0.000    0.000    0.000 {sys.exc_info}
 
 
@@ -28,7 +27,6 @@ Function                                          called...
                                                       ncalls  tottime  cumtime
 <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__)
-                                                           8    0.000    0.000  {range}
 test_cProfile.py:115(__getattr__)                 -> 
 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)
@@ -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__)
 {method 'append' of 'list' objects}               -> 
 {method 'disable' of '_lsprof.Profiler' objects}  -> 
-{range}                                           -> 
 {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)
 {method 'append' of 'list' objects}               <-       4    0.000    0.000  test_cProfile.py:78(helper1)
 {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)
 
 
index 6f82ee4b0af971dd24c3811ce5abaaa58967abc1..cecc8c0e029b573f12e512fa93b5acbd643dec25 100644 (file)
@@ -1,5 +1,5 @@
 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
 
@@ -8,7 +8,6 @@ test_profile
         4    0.000    0.000    0.000    0.000 :0(exc_info)
         1    0.000    0.000    1.000    1.000 :0(exec)
        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    1.000    1.000 <string>:1(<module>)
         0    0.000             0.000          profile:0(profiler)
@@ -31,14 +30,12 @@ Function                              called...
 :0(exc_info)                          -> 
 :0(exec)                              -> <string>:1(<module>)(1)    1.000
 :0(hasattr)                           -> test_profile.py:115(__getattr__)(12)    0.028
-:0(range)                             -> 
 :0(setprofile)                        -> 
 <string>:1(<module>)                  -> test_profile.py:30(testfunc)(1)    1.000
 profile:0(profiler)                   -> profile:0(testfunc())(1)    1.000
 profile:0(testfunc())                 -> :0(exec)(1)    1.000
                                          :0(setprofile)(1)    0.000
-test_profile.py:103(subhelper)        -> :0(range)(8)    0.000
-                                         test_profile.py:115(__getattr__)(16)    0.028
+test_profile.py:103(subhelper)        -> test_profile.py:115(__getattr__)(16)    0.028
 test_profile.py:115(__getattr__)      -> 
 test_profile.py:30(testfunc)          -> test_profile.py:40(factorial)(1)    0.170
                                          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(hasattr)                           <- test_profile.py:78(helper1)(4)    0.120
                                          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
 <string>:1(<module>)                  <- :0(exec)(1)    1.000
 profile:0(profiler)                   <- 
index 4cd9073c2701a7bae60be692f6fc127daaebb8cc..5d84eff4dc83f89d820b5ef4f8de3a17ac308b99 100644 (file)
@@ -745,7 +745,7 @@ class AbstractPickleTests(unittest.TestCase):
 
     def test_list_chunking(self):
         n = 10  # too small to chunk
-        x = range(n)
+        x = list(range(n))
         for proto in protocols:
             s = self.dumps(x, proto)
             y = self.loads(s)
@@ -754,7 +754,7 @@ class AbstractPickleTests(unittest.TestCase):
             self.assertEqual(num_appends, proto > 0)
 
         n = 2500  # expect at least two chunks when proto > 0
-        x = range(n)
+        x = list(range(n))
         for proto in protocols:
             s = self.dumps(x, proto)
             y = self.loads(s)
@@ -991,7 +991,7 @@ class AbstractPersistentPicklerTests(unittest.TestCase):
     def test_persistence(self):
         self.id_count = 0
         self.load_count = 0
-        L = range(10)
+        L = list(range(10))
         self.assertEqual(self.loads(self.dumps(L)), L)
         self.assertEqual(self.id_count, 5)
         self.assertEqual(self.load_count, 5)
@@ -999,7 +999,7 @@ class AbstractPersistentPicklerTests(unittest.TestCase):
     def test_bin_persistence(self):
         self.id_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.id_count, 5)
         self.assertEqual(self.load_count, 5)
index d4e72e146e7328806c38feee1050420904576b62..6ec03e8a5f5f8cbf8cf92462ef3b36fc5c854501 100644 (file)
@@ -120,7 +120,7 @@ class CommonTest(unittest.TestCase):
         self.assertEqual(len(vv), len(s))
 
         # 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,
                       itermulti, iterfunc):
                 self.assertEqual(self.type2test(g(s)), self.type2test(s))
@@ -136,10 +136,10 @@ class CommonTest(unittest.TestCase):
 
     def test_getitem(self):
         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[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[int(i)], len(u)+i)
         self.assertRaises(IndexError, u.__getitem__, -len(u)-1)
@@ -299,9 +299,9 @@ class CommonTest(unittest.TestCase):
         self.assertEqual(next(iter(T((1,2)))), 1)
 
     def test_repeat(self):
-        for m in xrange(4):
+        for m in range(4):
             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)*(-4), self.type2test([]))
             self.assertEqual(id(s), id(s*1))
index 205ff87098057b6e35e609ad256a453709ef860a..44fc1b0acf71d25cd7ff63b478bb1a4b71fe99e0 100644 (file)
@@ -24,7 +24,7 @@ def randfloats(n):
         fp = open(fn, "rb")
     except IOError:
         r = random.random
-        result = [r() for i in xrange(n)]
+        result = [r() for i in range(n)]
         try:
             try:
                 fp = open(fn, "wb")
@@ -108,7 +108,7 @@ def tabulate(r):
         doit(L) # +sort
 
         # 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()
         doit(L) # %sort
 
index f169fde0a42aea2c582df593188abbccdf77b0bc..b1b64a877e631ccdc2ff9a78f9c487a9100e9f63 100644 (file)
@@ -112,9 +112,9 @@ class BaseTest(unittest.TestCase):
         digits = 7
         base = len(charset)
         teststrings = set()
-        for i in xrange(base ** digits):
+        for i in range(base ** digits):
             entry = []
-            for j in xrange(digits):
+            for j in range(digits):
                 i, m = divmod(i, base)
                 entry.append(charset[m])
             teststrings.add(''.join(entry))
@@ -151,9 +151,9 @@ class BaseTest(unittest.TestCase):
         digits = 5
         base = len(charset)
         teststrings = set()
-        for i in xrange(base ** digits):
+        for i in range(base ** digits):
             entry = []
-            for j in xrange(digits):
+            for j in range(digits):
                 i, m = divmod(i, base)
                 entry.append(charset[m])
             teststrings.add(''.join(entry))
@@ -1006,10 +1006,10 @@ class MixinStrUnicodeUserStringTest:
 
     def test_floatformatting(self):
         # float formatting
-        for prec in xrange(100):
+        for prec in range(100):
             format = '%%.%if' % prec
             value = 0.01
-            for x in xrange(60):
+            for x in range(60):
                 value = value * 3.141592655 / 3.0 * 10.0
                 # The formatfloat() code in stringobject.c and
                 # unicodeobject.c uses a 120 byte buffer and switches from
@@ -1076,7 +1076,7 @@ class MixinStrStringUserStringTest:
 
     def test_maketrans(self):
         self.assertEqual(
-           ''.join(map(chr, xrange(256))).replace('abc', 'xyz'),
+           ''.join(map(chr, range(256))).replace('abc', 'xyz'),
            string.maketrans('abc', 'xyz')
         )
         self.assertRaises(ValueError, string.maketrans, 'abc', 'xyzw')
index 5278f2329dd8d798749c12f5bc60777e21adb401..3f8df52cdfa3b78b1c55dd47a32bbe41336e8e1d 100755 (executable)
@@ -836,7 +836,7 @@ class NumberTest(BaseTest):
 
     def test_iterationcontains(self):
         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])
         self.assertEqual(a[-1] 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"):
         import gc
         counts = [None] * 5
-        for i in xrange(len(counts)):
+        for i in range(len(counts)):
             test_support.run_unittest(*tests)
             gc.collect()
             counts[i] = sys.gettotalrefcount()
index f16258e3de961b2f9370606d16abf87bf07e7fc1..6a295e984e0af85451ee09d704b15f7b60777797 100755 (executable)
@@ -9,7 +9,7 @@ class BinASCIITest(unittest.TestCase):
     # Create binary test data
     data = "The quick brown fox jumps over the lazy dog.\r\n"
     # 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"
 
     def test_exceptions(self):
@@ -58,7 +58,7 @@ class BinASCIITest(unittest.TestCase):
 
         fillers = ""
         valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/"
-        for i in xrange(256):
+        for i in range(256):
             c = chr(i)
             if c not in valid:
                 fillers += c
index 1d62352f171ee7d788f6112644595a1b06a900ac..0baeb1414fe9402c54e13115e050963ad6ed47dc 100644 (file)
@@ -94,8 +94,8 @@ class TestBisect(unittest.TestCase):
 
     def test_random(self, n=25):
         from random import randrange
-        for i in xrange(n):
-            data = [randrange(0, n, 2) for j in xrange(i)]
+        for i in range(n):
+            data = [randrange(0, n, 2) for j in range(i)]
             data.sort()
             elem = randrange(-1, n+1)
             ip = bisect_left(data, elem)
@@ -111,9 +111,9 @@ class TestBisect(unittest.TestCase):
 
     def test_optionalSlicing(self):
         for func, data, elem, expected in self.precomputedCases:
-            for lo in xrange(4):
+            for lo in range(4):
                 lo = min(len(data), lo)
-                for hi in xrange(3,8):
+                for hi in range(3,8):
                     hi = min(len(data), hi)
                     ip = func(data, elem, lo, hi)
                     self.failUnless(lo <= ip <= hi)
@@ -147,7 +147,7 @@ class TestInsort(unittest.TestCase):
     def test_vsBuiltinSort(self, n=500):
         from random import choice
         for insorted in (list(), UserList()):
-            for i in xrange(n):
+            for i in range(n):
                 digit = choice("0123456789")
                 if digit in "02468":
                     f = insort_left
@@ -248,7 +248,7 @@ def test_main(verbose=None):
     if verbose and hasattr(sys, "gettotalrefcount"):
         import gc
         counts = [None] * 5
-        for i in xrange(len(counts)):
+        for i in range(len(counts)):
             test_support.run_unittest(*test_classes)
             gc.collect()
             counts[i] = sys.gettotalrefcount()
index 876a1000dd3b5b6a4c1b0126801cffc7574307c7..7413307448ab0c4808db477fced9e66e60e57646 100755 (executable)
@@ -117,13 +117,13 @@ class TestBSDDB(unittest.TestCase):
 
     def test_first_next_looping(self):
         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())
         self.assertSetEquals(items, self.d.items())
 
     def test_previous_last_looping(self):
         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())
         self.assertSetEquals(items, self.d.items())
 
index 14a926a570444899ea19e1fc54a7c1ea49aa7b98..c3a02d1cc7b507757dc5f337dadabf5e120ab5aa 100644 (file)
@@ -5,8 +5,8 @@ from test import test_support
 # the expected results.  For best testing, run this under a debug-build
 # Python too (to exercise asserts in the C code).
 
-lengths = range(1, 257) + [512, 1000, 1024, 2048, 4096, 8192, 10000,
-                           16384, 32768, 65536, 1000000]
+lengths = list(range(1, 257)) + [512, 1000, 1024, 2048, 4096, 8192, 10000,
+                                 16384, 32768, 65536, 1000000]
 
 class BufferSizeTest(unittest.TestCase):
     def try_one(self, s):
index eae28b0e18fba02e5e45a0fe1e4e6bb2e4e38b3b..3ea8ffb55fc71bb9f7aee2880281e71ed0a3f933 100644 (file)
@@ -990,7 +990,7 @@ class BuiltinTest(unittest.TestCase):
             # thread for the details:
 
             #     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
         x = []
@@ -1454,38 +1454,39 @@ class BuiltinTest(unittest.TestCase):
         self.assertRaises(TypeError, pow)
 
     def test_range(self):
-        self.assertEqual(range(3), [0, 1, 2])
-        self.assertEqual(range(1, 5), [1, 2, 3, 4])
-        self.assertEqual(range(0), [])
-        self.assertEqual(range(-3), [])
-        self.assertEqual(range(1, 10, 3), [1, 4, 7])
-        self.assertEqual(range(5, -5, -3), [5, 2, -1, -4])
-
+        self.assertEqual(list(range(3)), [0, 1, 2])
+        self.assertEqual(list(range(1, 5)), [1, 2, 3, 4])
+        self.assertEqual(list(range(0)), [])
+        self.assertEqual(list(range(-3)), [])
+        self.assertEqual(list(range(1, 10, 3)), [1, 4, 7])
+        #self.assertEqual(list(range(5, -5, -3)), [5, 2, -1, -4])
+
+        """ XXX(nnorwitz):
         # Now test range() with longs
-        self.assertEqual(range(-2**100), [])
-        self.assertEqual(range(0, -2**100), [])
-        self.assertEqual(range(0, 2**100, -1), [])
-        self.assertEqual(range(0, 2**100, -1), [])
+        self.assertEqual(list(range(-2**100)), [])
+        self.assertEqual(list(range(0, -2**100)), [])
+        self.assertEqual(list(range(0, 2**100, -1)), [])
+        self.assertEqual(list(range(0, 2**100, -1)), [])
 
         a = int(10 * sys.maxint)
         b = int(100 * sys.maxint)
         c = int(50 * sys.maxint)
 
-        self.assertEqual(range(a, a+2), [a, a+1])
-        self.assertEqual(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, a+2)), [a, a+1])
+        self.assertEqual(list(range(a+2, a, -1)), [a+2, a+1])
+        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_(b not in seq)
         self.assertEqual(len(seq), 2)
 
-        seq = range(b, a, -c)
+        seq = list(range(b, a, -c))
         self.assert_(b in seq)
         self.assert_(a not in seq)
         self.assertEqual(len(seq), 2)
 
-        seq = range(-a, -b, -c)
+        seq = list(range(-a, -b, -c))
         self.assert_(-a in seq)
         self.assert_(-b not in seq)
         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...
         self.assertRaises(RuntimeError, range, a, a + 1, badzero(1))
+        """
 
         # Reject floats when it would require PyLongs to represent.
         # (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, 42, "spam")
 
-        self.assertRaises(OverflowError, range, -sys.maxint, sys.maxint)
-        self.assertRaises(OverflowError, range, 0, 2*sys.maxint)
+        #NEAL self.assertRaises(OverflowError, range, -sys.maxint, sys.maxint)
+        #NEAL self.assertRaises(OverflowError, range, 0, 2*sys.maxint)
+
+        self.assertRaises(OverflowError, len, range(0, sys.maxint**10))
 
     def test_input(self):
         self.write_testfile()
@@ -1630,8 +1634,8 @@ class BuiltinTest(unittest.TestCase):
 
     def test_sum(self):
         self.assertEqual(sum([]), 0)
-        self.assertEqual(sum(range(2,8)), 27)
-        self.assertEqual(sum(iter(range(2,8))), 27)
+        self.assertEqual(sum(list(range(2,8))), 27)
+        self.assertEqual(sum(iter(list(range(2,8)))), 27)
         self.assertEqual(sum(Squares(10)), 285)
         self.assertEqual(sum(iter(Squares(10))), 285)
         self.assertEqual(sum([[1], [2], [3]], []), [1, 2, 3])
@@ -1728,7 +1732,7 @@ class BuiltinTest(unittest.TestCase):
                 else:
                     return i
         self.assertEqual(
-            list(zip(SequenceWithoutALength(), xrange(2**30))),
+            list(zip(SequenceWithoutALength(), range(2**30))),
             list(enumerate(range(5)))
         )
 
@@ -1743,7 +1747,7 @@ class BuiltinTest(unittest.TestCase):
 class TestSorted(unittest.TestCase):
 
     def test_basic(self):
-        data = range(100)
+        data = list(range(100))
         copy = data[:]
         random.shuffle(copy)
         self.assertEqual(data, sorted(copy))
@@ -1788,7 +1792,7 @@ def test_main(verbose=None):
     if verbose and hasattr(sys, "gettotalrefcount"):
         import gc
         counts = [None] * 5
-        for i in xrange(len(counts)):
+        for i in range(len(counts)):
             run_unittest(*test_classes)
             gc.collect()
             counts[i] = sys.gettotalrefcount()
index 635c828d55e3500adcd5cfb650eca10f2ed14090..44684c3c94b317449268656cdaf5741c9278e5e7 100644 (file)
@@ -230,7 +230,7 @@ class BZ2FileTest(BaseTest):
     def testOpenDel(self):
         # "Test opening and deleting a file many times"
         self.createTempFile()
-        for i in xrange(10000):
+        for i in range(10000):
             o = BZ2File(self.filename)
             del o
 
index 893890d12b8cacb1631758d62ba232ca0212a864..8cbf5e0974a55fbc684f62a951d3ab0f2741cfc7 100644 (file)
@@ -260,7 +260,7 @@ class MonthCalendarTestCase(unittest.TestCase):
     def check_weeks(self, year, month, weeks):
         cal = calendar.monthcalendar(year, month)
         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]))
 
 
index 5215b87254e7ebb57eb5c3f681bd623d01018e74..d980a4f99888555d74bf0888d9d1f888bb3eb40f 100644 (file)
@@ -234,7 +234,7 @@ class CodecCallbackTest(unittest.TestCase):
             if not isinstance(exc, UnicodeEncodeError) \
                and not isinstance(exc, UnicodeDecodeError):
                 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)
 
         codecs.register_error("test.handler1", handler1)
@@ -242,7 +242,7 @@ class CodecCallbackTest(unittest.TestCase):
         def handler2(exc):
             if not isinstance(exc, UnicodeDecodeError):
                 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
 
         codecs.register_error("test.handler2", handler2)
@@ -308,13 +308,13 @@ class CodecCallbackTest(unittest.TestCase):
         self.assertRaises(TypeError, exctype, *(args + ["too much"]))
         # check with one argument of the wrong type
         wrongargs = [ "spam", "eggs", 42, 1.0, None ]
-        for i in xrange(len(args)):
+        for i in range(len(args)):
             for wrongarg in wrongargs:
                 if type(wrongarg) is type(args[i]):
                     continue
                 # build argument array
                 callargs = []
-                for j in xrange(len(args)):
+                for j in range(len(args)):
                     if i==j:
                         callargs.append(wrongarg)
                     else:
@@ -469,7 +469,7 @@ class CodecCallbackTest(unittest.TestCase):
             codecs.replace_errors,
             BadObjectUnicodeDecodeError()
         )
-        # With the correct exception, "replace" returns an "?" or u"\ufffd" replacement
+        # With the correct exception, "replace" returns an "?" or "\ufffd" replacement
         self.assertEquals(
             codecs.replace_errors(UnicodeEncodeError("ascii", "\u3042", 0, 1, "ouch")),
             ("?", 1)
index 10e4c36c68d5100e9375b234f498dffef41ec681..69f941d944314c6a16725ebb9e00ca5817a667e9 100644 (file)
@@ -25,7 +25,7 @@ class Queue(object):
 
 class MixInCheckStateHandling:
     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)()
             part1 = d.decode(s[:i])
             state = d.getstate()
@@ -47,7 +47,7 @@ class MixInCheckStateHandling:
             self.assertEqual(u, part1+part2)
 
     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)()
             part1 = d.encode(u[:i])
             state = d.getstate()
@@ -135,17 +135,17 @@ class ReadTest(unittest.TestCase, MixInCheckStateHandling):
 
         # 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
-        for size in xrange(80):
+        for size in range(80):
             for lineend in "\n \r\n \r \u2028".split():
                 s = 10*(size*"a" + lineend + "xxx\n")
                 reader = getreader(s)
-                for i in xrange(10):
+                for i in range(10):
                     self.assertEqual(
                         reader.readline(keepends=True),
                         size*"a" + lineend,
                     )
                 reader = getreader(s)
-                for i in xrange(10):
+                for i in range(10):
                     self.assertEqual(
                         reader.readline(keepends=False),
                         size*"a",
@@ -1251,7 +1251,7 @@ class BasicUnicodeTest(unittest.TestCase, MixInCheckStateHandling):
             if encoding in broken_unicode_with_streams:
                 continue
             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
                 reader.seek(0, 0)
                 line = reader.readline()
@@ -1319,7 +1319,7 @@ class CharmapTest(unittest.TestCase):
             ("ab", 3)
         )
 
-        allbytes = bytes(xrange(256))
+        allbytes = bytes(range(256))
         self.assertEquals(
             codecs.charmap_decode(allbytes, "ignore", ""),
             ("", len(allbytes))
index 5cfe27c3e223dfc0b39ebcf485bca070bd83decf..213cca806729b711f14b1834ec688142dfaf8039 100644 (file)
@@ -399,11 +399,11 @@ if 1:
         # is the max. Ensure the result of too many annotations is a
         # SyntaxError.
         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')
         # Test that the max # of annotations compiles.
         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')
 
     def test_mangling(self):
index 39520f111e9dc0b3118f4066f6e171063cbb96d4..43a57c8501d84837683a49f5352d07d1e2e22e61 100644 (file)
@@ -64,7 +64,7 @@ class ComplexTest(unittest.TestCase):
             self.assertClose(q, x)
 
     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]
         for x 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)
 
         # Just for fun.
-        for i in xrange(100):
+        for i in range(100):
             self.check_div(complex(random(), random()),
                            complex(random(), random()))
 
@@ -158,7 +158,7 @@ class ComplexTest(unittest.TestCase):
         self.assertRaises(ValueError, pow, a, b, 0)
 
     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_(not complex(0.0, 0.0))
 
@@ -296,13 +296,13 @@ class ComplexTest(unittest.TestCase):
         self.assertRaises(TypeError, complex, complex2(1j))
 
     def test_hash(self):
-        for x in xrange(-30, 30):
+        for x in range(-30, 30):
             self.assertEqual(hash(x), hash(complex(x, 0)))
             x /= 3.0    # now check against floating point
             self.assertEqual(hash(x), hash(complex(x, 0.)))
 
     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:
             self.assertAlmostEqual((num.real**2 + num.imag**2)  ** 0.5, abs(num))
 
index c9024218066e07d77aef4c90d3b7421ca7b1cd8d..f3287bf6997b0392da7696b02c336d86b886dbc7 100644 (file)
@@ -86,7 +86,7 @@ if have_unicode:
     check(str('d') not in 'abc', "u'd' in 'abc'")
 
 # A collection of tests on builtin sequence types
-a = range(10)
+a = list(range(10))
 for i in a:
     check(i in a, "%r not in %r" % (i, 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.
     """
 
-    aList = range(15)
+    aList = list(range(15))
 
     def __cmp__(self, other):
         if other == 12:
index 48710076310e88484a79788cdd6aaf717180e58a..dfdea845ecdcb477a809efa637013df803b2f0f6 100644 (file)
@@ -84,7 +84,7 @@ class TestCopy(unittest.TestCase):
             pass
         tests = [None, 42, 2**100, 3.14, True, False, 1j,
                  "hello", "hello\u1234", f.__code__,
-                 NewStyle, xrange(10), Classic, max]
+                 NewStyle, range(10), Classic, max]
         for x in tests:
             self.assert_(copy.copy(x) is x, repr(x))
 
@@ -257,7 +257,7 @@ class TestCopy(unittest.TestCase):
             pass
         tests = [None, 42, 2**100, 3.14, True, False, 1j,
                  "hello", "hello\u1234", f.__code__,
-                 NewStyle, xrange(10), Classic, max]
+                 NewStyle, range(10), Classic, max]
         for x in tests:
             self.assert_(copy.deepcopy(x) is x, repr(x))
 
index 0ca6b788aa2087deeb569d89dda8de96d65a1ffb..d655bf06d77961468463a7bd931c6563a7faf9bf 100644 (file)
@@ -909,7 +909,7 @@ else:
         def test_create_read(self):
             delta = 0
             lastrc = sys.gettotalrefcount()
-            for i in xrange(20):
+            for i in range(20):
                 gc.collect()
                 self.assertEqual(gc.garbage, [])
                 rc = sys.gettotalrefcount()
@@ -925,7 +925,7 @@ else:
             delta = 0
             lastrc = sys.gettotalrefcount()
             s = NUL()
-            for i in xrange(20):
+            for i in range(20):
                 gc.collect()
                 self.assertEqual(gc.garbage, [])
                 rc = sys.gettotalrefcount()
@@ -941,7 +941,7 @@ else:
             delta = 0
             rows = ["a,b,c\r\n"]*5
             lastrc = sys.gettotalrefcount()
-            for i in xrange(20):
+            for i in range(20):
                 gc.collect()
                 self.assertEqual(gc.garbage, [])
                 rc = sys.gettotalrefcount()
@@ -958,7 +958,7 @@ else:
             rows = [[1,2,3]]*5
             s = NUL()
             lastrc = sys.gettotalrefcount()
-            for i in xrange(20):
+            for i in range(20):
                 gc.collect()
                 self.assertEqual(gc.garbage, [])
                 rc = sys.gettotalrefcount()
index 287585ed3e5d6935ce4aff1a20c3955c0aedffe4..4ab2f7bc69f8d59f483e94f46dae587894a8a49f 100644 (file)
@@ -569,7 +569,7 @@ class TestDate(HarmlessMixedComparison, unittest.TestCase):
 
         # Check first and last days of year spottily across the whole
         # 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.
             d = self.theclass(year, 1, 1)
             n = d.toordinal()
index c39a8e31b712ab5456e5dc33e55b8618a458548a..641f51c3c337b8a07238ad9fcb22603449d1de2d 100644 (file)
@@ -842,7 +842,7 @@ class DecimalUsabilityTest(unittest.TestCase):
         self.assertNotEqual(da, object)
 
         # sortable
-        a = map(Decimal, xrange(100))
+        a = map(Decimal, range(100))
         b =  a[:]
         random.shuffle(a)
         a.sort()
index 4f7e60ce888195b39602e8c09314b2c005a455a7..e2254d6e6c62d80592d564e9afd853dc523bffc6 100644 (file)
@@ -29,23 +29,23 @@ class MutateCmp:
 class TestBasic(unittest.TestCase):
 
     def test_basics(self):
-        d = deque(xrange(100))
-        d.__init__(xrange(100, 200))
-        for i in xrange(200, 400):
+        d = deque(range(100))
+        d.__init__(range(100, 200))
+        for i in range(200, 400):
             d.append(i)
-        for i in reversed(xrange(-200, 0)):
+        for i in reversed(range(-200, 0)):
             d.appendleft(i)
-        self.assertEqual(list(d), range(-200, 400))
+        self.assertEqual(list(d), list(range(-200, 400)))
         self.assertEqual(len(d), 600)
 
-        left = [d.popleft() for i in xrange(250)]
-        self.assertEqual(left, range(-200, 50))
-        self.assertEqual(list(d), range(50, 400))
+        left = [d.popleft() for i in range(250)]
+        self.assertEqual(left, list(range(-200, 50)))
+        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()
-        self.assertEqual(right, range(150, 400))
-        self.assertEqual(list(d), range(50, 150))
+        self.assertEqual(right, list(range(150, 400)))
+        self.assertEqual(list(d), list(range(50, 150)))
 
     def test_comparisons(self):
         d = deque('xabc'); d.popleft()
@@ -82,15 +82,15 @@ class TestBasic(unittest.TestCase):
 
     def test_getitem(self):
         n = 200
-        d = deque(xrange(n))
-        l = range(n)
-        for i in xrange(n):
+        d = deque(range(n))
+        l = list(range(n))
+        for i in range(n):
             d.popleft()
             l.pop(0)
             if random.random() < 0.5:
                 d.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]
 
         d = deque('superman')
@@ -102,22 +102,22 @@ class TestBasic(unittest.TestCase):
 
     def test_setitem(self):
         n = 200
-        d = deque(xrange(n))
-        for i in xrange(n):
+        d = deque(range(n))
+        for i in range(n):
             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)
-        for i in xrange(1-n, 0, -1):
+        for i in range(1-n, 0, -1):
             d[i] = 7*i
             l[i] = 7*i
         self.assertEqual(list(d), l)
 
     def test_delitem(self):
         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)
-        for i in xrange(n):
+        for i in range(n):
             self.assertEqual(len(d), n-i)
             j = random.randrange(-len(d), len(d))
             val = d[j]
@@ -140,11 +140,11 @@ class TestBasic(unittest.TestCase):
         d.rotate()              # check default to 1
         self.assertEqual(tuple(d), s)
 
-        for i in xrange(n*3):
+        for i in range(n*3):
             d = deque(s)
             e = deque(d)
             d.rotate(i)         # check vs. rot(1) n times
-            for j in xrange(i):
+            for j in range(i):
                 e.rotate(1)
             self.assertEqual(tuple(d), tuple(e))
             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
             self.assertEqual(tuple(e), s)
 
-        for i in xrange(n*3):
+        for i in range(n*3):
             d = deque(s)
             e = deque(d)
             d.rotate(-i)
-            for j in xrange(i):
+            for j in range(i):
                 e.rotate(-1)    # check vs. rot(-1) n times
             self.assertEqual(tuple(d), tuple(e))
             d.rotate(i)         # check that it works in reverse
@@ -168,7 +168,7 @@ class TestBasic(unittest.TestCase):
         e = deque(s)
         e.rotate(BIG+17)        # verify on long series of rotates
         dr = d.rotate
-        for i in xrange(BIG+17):
+        for i in range(BIG+17):
             dr()
         self.assertEqual(tuple(d), tuple(e))
 
@@ -201,7 +201,7 @@ class TestBasic(unittest.TestCase):
         self.assertRaises(IndexError, d.popleft)
 
     def test_clear(self):
-        d = deque(xrange(100))
+        d = deque(range(100))
         self.assertEqual(len(d), 100)
         d.clear()
         self.assertEqual(len(d), 0)
@@ -234,14 +234,14 @@ class TestBasic(unittest.TestCase):
             self.assertEqual(d, deque())
 
     def test_repr(self):
-        d = deque(xrange(200))
+        d = deque(range(200))
         e = eval(repr(d))
         self.assertEqual(list(d), list(e))
         d.append(d)
         self.assert_('...' in repr(d))
 
     def test_print(self):
-        d = deque(xrange(200))
+        d = deque(range(200))
         d.append(d)
         try:
             fo = open(test_support.TESTFN, "wb")
@@ -262,33 +262,34 @@ class TestBasic(unittest.TestCase):
 
     def test_long_steadystate_queue_popleft(self):
         for size in (0, 1, 2, 100, 1000):
-            d = deque(xrange(size))
+            d = deque(range(size))
             append, pop = d.append, d.popleft
-            for i in xrange(size, BIG):
+            for i in range(size, BIG):
                 append(i)
                 x = pop()
                 if 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):
         for size in (0, 1, 2, 100, 1000):
-            d = deque(reversed(xrange(size)))
+            d = deque(reversed(range(size)))
             append, pop = d.appendleft, d.pop
-            for i in xrange(size, BIG):
+            for i in range(size, BIG):
                 append(i)
                 x = pop()
                 if 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):
         pass
         d = deque()
         append, pop = d.append, d.popleft
-        for i in xrange(BIG):
+        for i in range(BIG):
             append(i)
-        for i in xrange(BIG):
+        for i in range(BIG):
             x = pop()
             if x != i:
                 self.assertEqual(x, i)
@@ -296,9 +297,9 @@ class TestBasic(unittest.TestCase):
     def test_big_queue_popright(self):
         d = deque()
         append, pop = d.appendleft, d.pop
-        for i in xrange(BIG):
+        for i in range(BIG):
             append(i)
-        for i in xrange(BIG):
+        for i in range(BIG):
             x = pop()
             if x != i:
                 self.assertEqual(x, i)
@@ -306,9 +307,9 @@ class TestBasic(unittest.TestCase):
     def test_big_stack_right(self):
         d = deque()
         append, pop = d.append, d.pop
-        for i in xrange(BIG):
+        for i in range(BIG):
             append(i)
-        for i in reversed(xrange(BIG)):
+        for i in reversed(range(BIG)):
             x = pop()
             if x != i:
                 self.assertEqual(x, i)
@@ -317,22 +318,22 @@ class TestBasic(unittest.TestCase):
     def test_big_stack_left(self):
         d = deque()
         append, pop = d.appendleft, d.popleft
-        for i in xrange(BIG):
+        for i in range(BIG):
             append(i)
-        for i in reversed(xrange(BIG)):
+        for i in reversed(range(BIG)):
             x = pop()
             if x != i:
                 self.assertEqual(x, i)
         self.assertEqual(len(d), 0)
 
     def test_roundtrip_iter_init(self):
-        d = deque(xrange(200))
+        d = deque(range(200))
         e = deque(d)
         self.assertNotEqual(id(d), id(e))
         self.assertEqual(list(d), list(e))
 
     def test_pickle(self):
-        d = deque(xrange(200))
+        d = deque(range(200))
         for i in (0, 1, 2):
             s = pickle.dumps(d, i)
             e = pickle.loads(s)
@@ -366,7 +367,7 @@ class TestBasic(unittest.TestCase):
         self.assertEqual(list(d), list(e))
 
     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)))
 
     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
         # build, or run wild with a NULL pointer in a release build.
         d = deque()
-        for i in xrange(100):
+        for i in range(100):
             d.append(1)
             gc.collect()
 
 class TestVariousIteratorArgs(unittest.TestCase):
 
     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,
                       seq_tests.IterGen, seq_tests.IterFuncStop,
                       seq_tests.itermulti, seq_tests.iterfunc):
@@ -412,23 +413,23 @@ class DequeWithBadIter(deque):
 class TestSubclass(unittest.TestCase):
 
     def test_basics(self):
-        d = Deque(xrange(100))
-        d.__init__(xrange(100, 200))
-        for i in xrange(200, 400):
+        d = Deque(range(100))
+        d.__init__(range(100, 200))
+        for i in range(200, 400):
             d.append(i)
-        for i in reversed(xrange(-200, 0)):
+        for i in reversed(range(-200, 0)):
             d.appendleft(i)
-        self.assertEqual(list(d), range(-200, 400))
+        self.assertEqual(list(d), list(range(-200, 400)))
         self.assertEqual(len(d), 600)
 
-        left = [d.popleft() for i in xrange(250)]
-        self.assertEqual(left, range(-200, 50))
-        self.assertEqual(list(d), range(50, 400))
+        left = [d.popleft() for i in range(250)]
+        self.assertEqual(left, list(range(-200, 50)))
+        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()
-        self.assertEqual(right, range(150, 400))
-        self.assertEqual(list(d), range(50, 150))
+        self.assertEqual(right, list(range(150, 400)))
+        self.assertEqual(list(d), list(range(50, 150)))
 
         d.clear()
         self.assertEqual(len(d), 0)
@@ -618,7 +619,7 @@ def test_main(verbose=None):
     if verbose and hasattr(sys, "gettotalrefcount"):
         import gc
         counts = [None] * 5
-        for i in xrange(len(counts)):
+        for i in range(len(counts)):
             test_support.run_unittest(*test_classes)
             gc.collect()
             counts[i] = sys.gettotalrefcount()
index 4ae8f6098c8b9e9c1e4aaa7d827183120d97d5d8..efdf9b02365e9bc6fa7051a5f303ad9621ed0e5c 100644 (file)
@@ -1181,7 +1181,7 @@ def slots():
             return 0
     g = G()
     orig_objects = len(gc.get_objects())
-    for i in xrange(10):
+    for i in range(10):
         g==g
     new_objects = len(gc.get_objects())
     vereq(orig_objects, new_objects)
@@ -2363,24 +2363,24 @@ def inherits():
     class sublist(list):
         pass
     a = sublist(range(5))
-    vereq(a, range(5))
+    vereq(a, list(range(5)))
     a.append("hello")
-    vereq(a, range(5) + ["hello"])
+    vereq(a, list(range(5)) + ["hello"])
     a[5] = 5
-    vereq(a, range(6))
+    vereq(a, list(range(6)))
     a.extend(range(6, 20))
-    vereq(a, range(20))
+    vereq(a, list(range(20)))
     a[-5:] = []
-    vereq(a, range(15))
+    vereq(a, list(range(15)))
     del a[10:15]
     vereq(len(a), 10)
-    vereq(a, range(10))
-    vereq(list(a), range(10))
+    vereq(a, list(range(10)))
+    vereq(list(a), list(range(10)))
     vereq(a[0], 0)
     vereq(a[9], 9)
     vereq(a[-10], 0)
     vereq(a[-1], 9)
-    vereq(a[:5], range(5))
+    vereq(a[:5], list(range(5)))
 
     class CountedInput(file):
         """Counts lines read by self.readline().
@@ -2412,7 +2412,7 @@ def inherits():
         f.writelines(lines)
         f.close()
         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()
             vereq(expected, got)
             vereq(f.lineno, i)
@@ -2439,7 +2439,7 @@ def keywords():
     vereq(str(object=500), '500')
     vereq(str(string='abc', errors='strict'), 'abc')
     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
 
     for constructor in (int, float, int, complex, str, str,
@@ -3502,7 +3502,7 @@ def slottrash():
         def __init__(self, x):
             self.x = x
     o = None
-    for i in xrange(50000):
+    for i in range(50000):
         o = trash(o)
     del o
 
@@ -3959,7 +3959,7 @@ def weakref_segfault():
 def wrapper_segfault():
     # SF 927248: deeply nested wrappers could cause stack overflow
     f = lambda:None
-    for i in xrange(1000000):
+    for i in range(1000000):
         f = f.__call__
     f = None
 
index 5d82cd7c15a17ce8a8ceb3b5408fd3175afee16f..dfb307ddaf9a4e57560b6b7fb709e18666066a5a 100644 (file)
@@ -144,12 +144,12 @@ class DisTests(unittest.TestCase):
             return namespace['foo']
 
         # Test all small ranges
-        for i in xrange(1, 300):
+        for i in range(1, 300):
             expected = _BIG_LINENO_FORMAT % (i + 2)
             self.do_disassembly_test(func(i), expected)
 
         # 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)
             self.do_disassembly_test(func(i), expected)
 
index 60079a69040b13c3b5e42e206b05abc74552645d..3adb98c31ff1c22caa65ad927c06463b5b450770 100644 (file)
@@ -34,8 +34,8 @@ class SampleClass:
     >>> sc = SampleClass(3)
     >>> for i in range(10):
     ...     sc = sc.double()
-    ...     print(sc.get(), end=' ')
-    6 12 24 48 96 192 384 768 1536 3072
+    ...     print(' ', sc.get(), sep='', end='')
+     6 12 24 48 96 192 384 768 1536 3072
     """
     def __init__(self, val):
         """
@@ -996,7 +996,7 @@ treated as equal:
     (0, 1)
 
     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,
     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:
 
     >>> 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:
     >>> test = doctest.DocTestFinder().find(f)[0]
@@ -1013,7 +1013,7 @@ output to match any substring in the actual output:
     **********************************************************************
     File ..., line 2, in f
     Failed example:
-        print(range(15))
+        print(list(range(15)))
     Expected:
         [0, 1, 2, ..., 14]
     Got:
@@ -1044,10 +1044,10 @@ output to match any substring in the actual output:
 
     Examples from the docs:
 
-    >>> print(range(20)) # doctest:+ELLIPSIS
+    >>> print(list(range(20))) # doctest:+ELLIPSIS
     [0, 1, ..., 18, 19]
 
-    >>> print(range(20)) # doctest: +ELLIPSIS
+    >>> print(list(range(20))) # doctest: +ELLIPSIS
     ...                 # doctest: +NORMALIZE_WHITESPACE
     [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``:
 
     >>> def f(x): r'''
-    ...     >>> print(range(10))      # should fail: no ellipsis
+    ...     >>> print(list(range(10)))      # should fail: no ellipsis
     ...     [0, 1, ..., 9]
     ...
-    ...     >>> print(range(10))      # doctest: +ELLIPSIS
+    ...     >>> print(list(range(10)))      # doctest: +ELLIPSIS
     ...     [0, 1, ..., 9]
     ...     '''
     >>> test = doctest.DocTestFinder().find(f)[0]
@@ -1314,7 +1314,7 @@ example with a comment of the form ``# doctest: +OPTION``:
     **********************************************************************
     File ..., line 2, in f
     Failed example:
-        print(range(10))      # should fail: no ellipsis
+        print(list(range(10)))      # should fail: no ellipsis
     Expected:
         [0, 1, ..., 9]
     Got:
@@ -1325,11 +1325,11 @@ To turn an option off for an example, follow that example with a
 comment of the form ``# doctest: -OPTION``:
 
     >>> def f(x): r'''
-    ...     >>> print(range(10))
+    ...     >>> print(list(range(10)))
     ...     [0, 1, ..., 9]
     ...
     ...     >>> # should fail: no ellipsis
-    ...     >>> print(range(10))      # doctest: -ELLIPSIS
+    ...     >>> print(list(range(10)))      # doctest: -ELLIPSIS
     ...     [0, 1, ..., 9]
     ...     '''
     >>> test = doctest.DocTestFinder().find(f)[0]
@@ -1339,7 +1339,7 @@ comment of the form ``# doctest: -OPTION``:
     **********************************************************************
     File ..., line 6, in f
     Failed example:
-        print(range(10))      # doctest: -ELLIPSIS
+        print(list(range(10)))      # doctest: -ELLIPSIS
     Expected:
         [0, 1, ..., 9]
     Got:
@@ -1350,13 +1350,13 @@ Option directives affect only the example that they appear with; they
 do not change the options for surrounding examples:
 
     >>> def f(x): r'''
-    ...     >>> print(range(10))      # Should fail: no ellipsis
+    ...     >>> print(list(range(10)))      # Should fail: no ellipsis
     ...     [0, 1, ..., 9]
     ...
-    ...     >>> print(range(10))      # doctest: +ELLIPSIS
+    ...     >>> print(list(range(10)))      # doctest: +ELLIPSIS
     ...     [0, 1, ..., 9]
     ...
-    ...     >>> print(range(10))      # Should fail: no ellipsis
+    ...     >>> print(list(range(10)))      # Should fail: no ellipsis
     ...     [0, 1, ..., 9]
     ...     '''
     >>> test = doctest.DocTestFinder().find(f)[0]
@@ -1365,7 +1365,7 @@ do not change the options for surrounding examples:
     **********************************************************************
     File ..., line 2, in f
     Failed example:
-        print(range(10))      # Should fail: no ellipsis
+        print(list(range(10)))      # Should fail: no ellipsis
     Expected:
         [0, 1, ..., 9]
     Got:
@@ -1373,7 +1373,7 @@ do not change the options for surrounding examples:
     **********************************************************************
     File ..., line 8, in f
     Failed example:
-        print(range(10))      # Should fail: no ellipsis
+        print(list(range(10)))      # Should fail: no ellipsis
     Expected:
         [0, 1, ..., 9]
     Got:
@@ -1384,9 +1384,9 @@ Multiple options may be modified by a single option directive.  They
 may be separated by whitespace, commas, or both:
 
     >>> def f(x): r'''
-    ...     >>> print(range(10))      # Should fail
+    ...     >>> print(list(range(10)))      # Should fail
     ...     [0, 1,  ...,   9]
-    ...     >>> print(range(10))      # Should succeed
+    ...     >>> print(list(range(10)))      # Should succeed
     ...     ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
     ...     [0, 1,  ...,   9]
     ...     '''
@@ -1396,7 +1396,7 @@ may be separated by whitespace, commas, or both:
     **********************************************************************
     File ..., line 2, in f
     Failed example:
-        print(range(10))      # Should fail
+        print(list(range(10)))      # Should fail
     Expected:
         [0, 1,  ...,   9]
     Got:
@@ -1404,9 +1404,9 @@ may be separated by whitespace, commas, or both:
     (1, 2)
 
     >>> def f(x): r'''
-    ...     >>> print(range(10))      # Should fail
+    ...     >>> print(list(range(10)))      # Should fail
     ...     [0, 1,  ...,   9]
-    ...     >>> print(range(10))      # Should succeed
+    ...     >>> print(list(range(10)))      # Should succeed
     ...     ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
     ...     [0, 1,  ...,   9]
     ...     '''
@@ -1416,7 +1416,7 @@ may be separated by whitespace, commas, or both:
     **********************************************************************
     File ..., line 2, in f
     Failed example:
-        print(range(10))      # Should fail
+        print(list(range(10)))      # Should fail
     Expected:
         [0, 1,  ...,   9]
     Got:
@@ -1424,9 +1424,9 @@ may be separated by whitespace, commas, or both:
     (1, 2)
 
     >>> def f(x): r'''
-    ...     >>> print(range(10))      # Should fail
+    ...     >>> print(list(range(10)))      # Should fail
     ...     [0, 1,  ...,   9]
-    ...     >>> print(range(10))      # Should succeed
+    ...     >>> print(list(range(10)))      # Should succeed
     ...     ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
     ...     [0, 1,  ...,   9]
     ...     '''
@@ -1436,7 +1436,7 @@ may be separated by whitespace, commas, or both:
     **********************************************************************
     File ..., line 2, in f
     Failed example:
-        print(range(10))      # Should fail
+        print(list(range(10)))      # Should fail
     Expected:
         [0, 1,  ...,   9]
     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:
 
     >>> def f(x): r'''
-    ...     >>> print(range(10))
+    ...     >>> print(list(range(10)))
     ...     ... # doctest: +ELLIPSIS
     ...     [0, 1, ..., 9]
     ...     '''
@@ -1460,12 +1460,12 @@ at the end of any line:
 
     >>> def f(x): r'''
     ...     >>> for x in range(10): # doctest: +ELLIPSIS
-    ...     ...     print(x, end=' ')
-    ...     0 1 2 ... 9
+    ...     ...     print(' ', x, end='', sep='')
+    ...      0 1 2 ... 9
     ...
     ...     >>> for x in range(10):
-    ...     ...     print(x, end=' ') # doctest: +ELLIPSIS
-    ...     0 1 2 ... 9
+    ...     ...     print(' ', x, end='', sep='') # doctest: +ELLIPSIS
+    ...      0 1 2 ... 9
     ...     '''
     >>> test = doctest.DocTestFinder().find(f)[0]
     >>> doctest.DocTestRunner(verbose=False).run(test)
index 288b6218c281404ce5a3ed1fedd59883f78a5e67..07466cea0b6e9b650c4e18fc0ba5b75e696750ed 100644 (file)
@@ -153,7 +153,7 @@ class ThreadTests(unittest.TestCase):
             print()
             print("*** Testing multiple thread creation "\
             "(will take approx. %s to %s sec.) ***" % (DELAY, thread_count))
-        for count in xrange(thread_count):
+        for count in range(thread_count):
             if DELAY:
                 local_delay = round(random.random(), 1)
             else:
index af7512d215b587207d387aee8f5fa02d54ead5b0..08229bfa7863a9356499acf86e6799b1d383f2e7 100644 (file)
@@ -134,18 +134,18 @@ class TestReversed(unittest.TestCase):
                 raise StopIteration
             def __len__(self):
                 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.assertRaises(TypeError, reversed, {})
 
-    def test_xrange_optimization(self):
-        x = xrange(1)
+    def test_range_optimization(self):
+        x = range(1)
         self.assertEqual(type(reversed(x)), type(iter(x)))
 
     def test_len(self):
         # This is an implementation detail, not an interface requirement
         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))
             r = reversed(s)
             list(r)
@@ -205,7 +205,7 @@ def test_main(verbose=None):
     import sys
     if verbose and hasattr(sys, "gettotalrefcount"):
         counts = [None] * 5
-        for i in xrange(len(counts)):
+        for i in range(len(counts)):
             test_support.run_unittest(*testclasses)
             counts[i] = sys.gettotalrefcount()
         print(counts)
index a2df21cb8aa72f422a9d37f74c60623ecc07bb2a..55c549f6ab244a0fdaff075aaff977ffcf6da0c5 100644 (file)
@@ -352,7 +352,7 @@ def test_main(verbose=None):
     if verbose and hasattr(sys, "gettotalrefcount"):
         import gc
         counts = [None] * 5
-        for i in xrange(len(counts)):
+        for i in range(len(counts)):
             test_support.run_unittest(*test_classes)
             gc.collect()
             counts[i] = sys.gettotalrefcount()
index 10b02dab992374712e061bfef7afab764a1137dd..bae00381dfc7c18131641ca656e2fee8f120912d 100644 (file)
@@ -399,7 +399,7 @@ class GCTests(unittest.TestCase):
 
         got = gc.get_referents([1, 2], {3: 4}, (0, 0, 0))
         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), [])
 
index 08d354a13c480a18d11b6a864c10169351c13bf0..a3b7870460d7abef2f2427ab99d6e9d28383236c 100644 (file)
@@ -343,7 +343,7 @@ Next one was posted to c.l.py.
 ...         for c in gcomb(rest, k):
 ...             yield c
 
->>> seq = range(1, 5)
+>>> seq = list(range(1, 5))
 >>> for k in range(len(seq) + 2):
 ...     print("%d-combs of %s:" % (k, seq))
 ...     for c in gcomb(seq, k):
index cafca5723483b456fd94a10d38355fbf1087cee9..7b5fdc451e1deccfd3fd4f0e2687e29f626688b0 100644 (file)
@@ -59,16 +59,16 @@ Does it stay stopped?
 Test running gen when defining function is out of scope
 
     >>> def f(n):
-    ...     return (i*i for i in xrange(n))
+    ...     return (i*i for i in range(n))
     >>> list(f(10))
     [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
 
     >>> 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))
     [(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):
-    ...     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))
     [(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))
@@ -77,21 +77,21 @@ Test running gen when defining function is out of scope
 Verify that parenthesis are required in a statement
 
     >>> def f(n):
-    ...     return i*i for i in xrange(n)
+    ...     return i*i for i in range(n)
     Traceback (most recent call last):
        ...
     SyntaxError: invalid syntax
 
 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):
        ...
     SyntaxError: invalid syntax
 
 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 ...>}
 
 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)
 
-    >>> 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))
     0
 
@@ -149,7 +149,7 @@ Verify that syntax error's are raised for genexps used as lvalues
 
 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))
     [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:
 
-    >>> g = (next(me) for i in xrange(10))
+    >>> g = (next(me) for i in range(10))
     >>> me = g
     >>> next(me)
     Traceback (most recent call last):
       File "<pyshell#30>", line 1, in -toplevel-
         next(me)
       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
 
 Verify exception propagation
@@ -211,7 +211,7 @@ Verify exception propagation
 
 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]
 
 Check that generator attributes are present
@@ -270,7 +270,7 @@ def test_main(verbose=None):
     if verbose and hasattr(sys, "gettotalrefcount"):
         import gc
         counts = [None] * 5
-        for i in xrange(len(counts)):
+        for i in range(len(counts)):
             test_support.run_doctest(test_genexps, verbose)
             gc.collect()
             counts[i] = sys.gettotalrefcount()
index 337f05776e4030b2c7f0e8eb7c5e8af25cf2bed5..ede9c72821be181f9497e629bcdbf0a1a7efdb6c 100755 (executable)
@@ -55,7 +55,7 @@ class GroupDatabaseTestCase(unittest.TestCase):
         fakename = allnames[namei]
         while fakename in bynames:
             chars = map(None, fakename)
-            for i in xrange(len(chars)):
+            for i in range(len(chars)):
                 if chars[i] == 'z':
                     chars[i] = 'A'
                     break
index dbbfcb0f6d02041aafdb31b98f0b3ecf8b8d0043..ceaf3cc0eed564d267e092c887d8f2dd9a1e85a2 100644 (file)
@@ -90,7 +90,7 @@ class TestHeap(unittest.TestCase):
 
     def test_heapsort(self):
         # Exercise everything with repeated heapsort checks
-        for trial in xrange(100):
+        for trial in range(100):
             size = random.randrange(50)
             data = [random.randrange(25) for i in range(size)]
             if trial & 1:     # Half of the time, use heapify
@@ -105,7 +105,7 @@ class TestHeap(unittest.TestCase):
 
     def test_merge(self):
         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)))
             inputs.append(row)
         self.assertEqual(sorted(chain(*inputs)), list(merge(*inputs)))
@@ -277,7 +277,7 @@ class TestErrorHandling(unittest.TestCase):
 
     def test_iterable_args(self):
         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):
                     self.assertEqual(f(2, g(s)), f(2,s))
                 self.assertEqual(f(2, S(s)), [])
@@ -300,7 +300,7 @@ def test_main(verbose=None):
     if verbose and hasattr(sys, "gettotalrefcount"):
         import gc
         counts = [None] * 5
-        for i in xrange(len(counts)):
+        for i in range(len(counts)):
             test_support.run_unittest(*test_classes)
             gc.collect()
             counts[i] = sys.gettotalrefcount()
index b930c295888c736f20294d1fc3f76375635e2463..8055c332b1c4d5d184878daa2c4a8155124529c1 100644 (file)
@@ -49,7 +49,7 @@ class BaseTestCase(unittest.TestCase):
         self.assertEqual(self.n.__index__(), 5)
 
     def test_subclasses(self):
-        r = range(10)
+        r = list(range(10))
         self.assertEqual(r[TrapInt(5):TrapInt(10)], r[5:10])
         self.assertEqual(r[TrapLong(5):TrapLong(10)], r[5:10])
         self.assertEqual(slice(TrapInt()).indices(0), (0,0,1))
@@ -164,14 +164,6 @@ class UnicodeTestCase(SeqTestCase):
     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):
 
     def setUp(self):
@@ -215,7 +207,6 @@ def test_main():
         TupleTestCase,
         StringTestCase,
         UnicodeTestCase,
-        XRangeTestCase,
         OverflowTestCase,
     )
 
index 9b05aa96458469a925aa2f5609c54cc6915f2c8f..957ce299e10485c05fb5ee65c9e4188d742a3830 100644 (file)
@@ -546,7 +546,7 @@ class TextIOWrapperTest(unittest.TestCase):
         wlines = []
         for size in (0, 1, 2, 3, 4, 5, 30, 31, 32, 33, 62, 63, 64, 65, 1000):
             chars = []
-            for i in xrange(size):
+            for i in range(size):
                 chars.append(sample[i % len(sample)])
             line = "".join(chars) + "\n"
             wlines.append((f.tell(), line))
index 074409000554b780a85595dff5c8ed1a03a7d645..691482e7cab29bfbc7be72a9d28f71f6d94f814e 100644 (file)
@@ -259,7 +259,7 @@ def blowstack(fxn, arg, compare_to):
     # Make sure that calling isinstance with a deeply nested tuple for its
     # argument will raise RuntimeError eventually.
     tuple_arg = (compare_to,)
-    for cnt in xrange(sys.getrecursionlimit()+5):
+    for cnt in range(sys.getrecursionlimit()+5):
         tuple_arg = (tuple_arg,)
         fxn(arg, tuple_arg)
 
index 5a75c50094921277ad44974db84f827148143a65..22595fc09db8e90fa5a39e9bc28c53c0dfa7b443 100644 (file)
@@ -68,18 +68,18 @@ class TestCase(unittest.TestCase):
 
     # Test basic use of iter() function
     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)
     def test_iter_idempotency(self):
-        seq = range(10)
+        seq = list(range(10))
         it = iter(seq)
         it2 = iter(it)
         self.assert_(it is it2)
 
     # Test that for loops over iterators work
     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
     def test_iter_independence(self):
@@ -106,19 +106,19 @@ class TestCase(unittest.TestCase):
 
     # Test a class with __iter__ in a for loop
     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()
     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__
     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__
     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
     def test_iter_callable(self):
@@ -131,7 +131,7 @@ class TestCase(unittest.TestCase):
                 if i > 100:
                     raise IndexError # Emergency stop
                 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
     def test_iter_function(self):
@@ -139,7 +139,7 @@ class TestCase(unittest.TestCase):
             i = state[0]
             state[0] = i+1
             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
     def test_iter_function_stop(self):
@@ -149,7 +149,7 @@ class TestCase(unittest.TestCase):
                 raise StopIteration
             state[0] = i+1
             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
     def test_exception_function(self):
@@ -164,7 +164,7 @@ class TestCase(unittest.TestCase):
             for x in iter(spam, 20):
                 res.append(x)
         except RuntimeError:
-            self.assertEqual(res, range(10))
+            self.assertEqual(res, list(range(10)))
         else:
             self.fail("should have raised RuntimeError")
 
@@ -180,7 +180,7 @@ class TestCase(unittest.TestCase):
             for x in MySequenceClass(20):
                 res.append(x)
         except RuntimeError:
-            self.assertEqual(res, range(10))
+            self.assertEqual(res, list(range(10)))
         else:
             self.fail("should have raised RuntimeError")
 
@@ -191,11 +191,11 @@ class TestCase(unittest.TestCase):
                 if i == 10:
                     raise StopIteration
                 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
     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
     def test_iter_empty(self):
@@ -203,11 +203,11 @@ class TestCase(unittest.TestCase):
 
     # Test a tuple
     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
-    def test_iter_xrange(self):
-        self.check_for_loop(iter(xrange(10)), range(10))
+    # Test a range
+    def test_iter_range(self):
+        self.check_for_loop(iter(range(10)), list(range(10)))
 
     # Test a string
     def test_iter_string(self):
@@ -248,10 +248,9 @@ class TestCase(unittest.TestCase):
 
     # Test list()'s use of iterators.
     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(()), [])
-        self.assertEqual(list(range(10, -1, -1)), range(10, -1, -1))
 
         d = {"one": 1, "two": 2, "three": 3}
         self.assertEqual(list(d), list(d.keys()))
@@ -313,7 +312,7 @@ class TestCase(unittest.TestCase):
 
     # Test filter()'s use of iterators.
     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, ()), ())
         self.assertEqual(filter(None, "abc"), "abc")
@@ -389,8 +388,8 @@ class TestCase(unittest.TestCase):
 
     # Test map()'s use of iterators.
     def test_builtin_map(self):
-        self.assertEqual(map(None, SequenceClass(5)), range(5))
-        self.assertEqual(map(lambda x: x+1, SequenceClass(5)), range(1, 6))
+        self.assertEqual(map(None, SequenceClass(5)), list(range(5)))
+        self.assertEqual(map(lambda x: x+1, SequenceClass(5)), list(range(1, 6)))
 
         d = {"one": 1, "two": 2, "three": 3}
         self.assertEqual(map(None, d), list(d.keys()))
@@ -413,7 +412,7 @@ class TestCase(unittest.TestCase):
             f.close()
         f = open(TESTFN, "r")
         try:
-            self.assertEqual(map(len, f), range(1, 21, 2))
+            self.assertEqual(map(len, f), list(range(1, 21, 2)))
         finally:
             f.close()
             try:
@@ -470,7 +469,7 @@ class TestCase(unittest.TestCase):
             except OSError:
                 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.
         class NoGuessLen5:
@@ -799,16 +798,16 @@ class TestCase(unittest.TestCase):
 
     def test_sinkstate_list(self):
         # This used to fail
-        a = range(5)
+        a = list(range(5))
         b = iter(a)
-        self.assertEqual(list(b), range(5))
+        self.assertEqual(list(b), list(range(5)))
         a.extend(range(5, 10))
         self.assertEqual(list(b), [])
 
     def test_sinkstate_tuple(self):
         a = (0, 1, 2, 3, 4)
         b = iter(a)
-        self.assertEqual(list(b), range(5))
+        self.assertEqual(list(b), list(range(5)))
         self.assertEqual(list(b), [])
 
     def test_sinkstate_string(self):
@@ -821,7 +820,7 @@ class TestCase(unittest.TestCase):
         # This used to fail
         a = SequenceClass(5)
         b = iter(a)
-        self.assertEqual(list(b), range(5))
+        self.assertEqual(list(b), list(range(5)))
         a.n = 10
         self.assertEqual(list(b), [])
 
@@ -834,7 +833,7 @@ class TestCase(unittest.TestCase):
                 raise AssertionError, "shouldn't have gotten this far"
             return i
         b = iter(spam, 5)
-        self.assertEqual(list(b), range(5))
+        self.assertEqual(list(b), list(range(5)))
         self.assertEqual(list(b), [])
 
     def test_sinkstate_dict(self):
@@ -851,13 +850,13 @@ class TestCase(unittest.TestCase):
             for i in range(5):
                 yield i
         b = gen()
-        self.assertEqual(list(b), range(5))
+        self.assertEqual(list(b), list(range(5)))
         self.assertEqual(list(b), [])
 
     def test_sinkstate_range(self):
-        a = xrange(5)
+        a = range(5)
         b = iter(a)
-        self.assertEqual(list(b), range(5))
+        self.assertEqual(list(b), list(range(5)))
         self.assertEqual(list(b), [])
 
     def test_sinkstate_enumerate(self):
index 28f25676e226e1198ca8b6e965e1cfe531403b81..afd7287aa78b65d77b29fb790787fe7b4def8e25 100644 (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
 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,
-but it=iter(xrange(10)) starts at ten, and then goes to nine after next(it).
+For instance, an iterable such as range(10) always reports its length as ten,
+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
 map(func, iterable) and map(func, iter(iterable)).
 
 When the iterable is immutable, the implementation can straight-forwardly
 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
 dicts, sets, and collections.deque.  Their implementation is equally simple
@@ -65,7 +65,7 @@ class TestInvariantWithoutMutations(unittest.TestCase):
 
     def test_invariant(self):
         it = self.it
-        for i in reversed(xrange(1, n+1)):
+        for i in reversed(range(1, n+1)):
             self.assertEqual(len(it), i)
             next(it)
         self.assertEqual(len(it), 0)
@@ -100,59 +100,59 @@ class TestRepeat(TestInvariantWithoutMutations):
 class TestXrange(TestInvariantWithoutMutations):
 
     def setUp(self):
-        self.it = iter(xrange(n))
+        self.it = iter(range(n))
 
 class TestXrangeCustomReversed(TestInvariantWithoutMutations):
 
     def setUp(self):
-        self.it = reversed(xrange(n))
+        self.it = reversed(range(n))
 
 class TestTuple(TestInvariantWithoutMutations):
 
     def setUp(self):
-        self.it = iter(tuple(xrange(n)))
+        self.it = iter(tuple(range(n)))
 
 ## ------- Types that should not be mutated during iteration -------
 
 class TestDeque(TestTemporarilyImmutable):
 
     def setUp(self):
-        d = deque(xrange(n))
+        d = deque(range(n))
         self.it = iter(d)
         self.mutate = d.pop
 
 class TestDequeReversed(TestTemporarilyImmutable):
 
     def setUp(self):
-        d = deque(xrange(n))
+        d = deque(range(n))
         self.it = reversed(d)
         self.mutate = d.pop
 
 class TestDictKeys(TestTemporarilyImmutable):
 
     def setUp(self):
-        d = dict.fromkeys(xrange(n))
+        d = dict.fromkeys(range(n))
         self.it = iter(d)
         self.mutate = d.popitem
 
 class TestDictItems(TestTemporarilyImmutable):
 
     def setUp(self):
-        d = dict.fromkeys(xrange(n))
+        d = dict.fromkeys(range(n))
         self.it = iter(d.items())
         self.mutate = d.popitem
 
 class TestDictValues(TestTemporarilyImmutable):
 
     def setUp(self):
-        d = dict.fromkeys(xrange(n))
+        d = dict.fromkeys(range(n))
         self.it = iter(d.values())
         self.mutate = d.popitem
 
 class TestSet(TestTemporarilyImmutable):
 
     def setUp(self):
-        d = set(xrange(n))
+        d = set(range(n))
         self.it = iter(d)
         self.mutate = d.pop
 
@@ -164,7 +164,7 @@ class TestList(TestInvariantWithoutMutations):
         self.it = iter(range(n))
 
     def test_mutation(self):
-        d = range(n)
+        d = list(range(n))
         it = iter(d)
         next(it)
         next(it)
@@ -174,7 +174,7 @@ class TestList(TestInvariantWithoutMutations):
         d[1:] = []
         self.assertEqual(len(it), 0)
         self.assertEqual(list(it), [])
-        d.extend(xrange(20))
+        d.extend(range(20))
         self.assertEqual(len(it), 0)
 
 class TestListReversed(TestInvariantWithoutMutations):
@@ -183,7 +183,7 @@ class TestListReversed(TestInvariantWithoutMutations):
         self.it = reversed(range(n))
 
     def test_mutation(self):
-        d = range(n)
+        d = list(range(n))
         it = reversed(d)
         next(it)
         next(it)
@@ -193,7 +193,7 @@ class TestListReversed(TestInvariantWithoutMutations):
         d[1:] = []
         self.assertEqual(len(it), 0)
         self.assertEqual(list(it), [])  # confirm invariant
-        d.extend(xrange(20))
+        d.extend(range(20))
         self.assertEqual(len(it), 0)
 
 class TestSeqIter(TestInvariantWithoutMutations):
@@ -212,7 +212,7 @@ class TestSeqIter(TestInvariantWithoutMutations):
         d[1:] = []
         self.assertEqual(len(it), 0)
         self.assertEqual(list(it), [])
-        d.extend(xrange(20))
+        d.extend(range(20))
         self.assertEqual(len(it), 0)
 
 class TestSeqIterReversed(TestInvariantWithoutMutations):
@@ -231,7 +231,7 @@ class TestSeqIterReversed(TestInvariantWithoutMutations):
         d[1:] = []
         self.assertEqual(len(it), 0)
         self.assertEqual(list(it), [])  # confirm invariant
-        d.extend(xrange(20))
+        d.extend(range(20))
         self.assertEqual(len(it), 0)
 
 
index 98c79c776322c4ad39e07db54e4c4e99d2b6ba7e..c2a539c30a35c692b5a2d1fc26ee14169b63311b 100644 (file)
@@ -248,7 +248,7 @@ class TestBasicOps(unittest.TestCase):
         self.assertEqual(len(dict.fromkeys(ids)), len(ids))
 
     def test_repeat(self):
-        self.assertEqual(lzip(xrange(3),repeat('a')),
+        self.assertEqual(lzip(range(3),repeat('a')),
                          [(0, 'a'), (1, 'a'), (2, 'a')])
         self.assertEqual(list(repeat('a', 3)), ['a', 'a', 'a'])
         self.assertEqual(take(3, repeat('a')), ['a', 'a', 'a'])
@@ -301,39 +301,41 @@ class TestBasicOps(unittest.TestCase):
                 (10, 3),
                 (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
                 ((10, 110, 3), ((10, 100, 3))),
                 ((10, 110), ((10, 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
-        self.assertEqual(list(islice(xrange(10), None)), range(10))
-        self.assertEqual(list(islice(xrange(10), None, None)), range(10))
-        self.assertEqual(list(islice(xrange(10), None, None, None)), range(10))
-        self.assertEqual(list(islice(xrange(10), 2, None)), range(2, 10))
-        self.assertEqual(list(islice(xrange(10), 1, None, 2)), range(1, 10, 2))
+        self.assertEqual(list(islice(range(10), None)), list(range(10)))
+        self.assertEqual(list(islice(range(10), None, None)), list(range(10)))
+        self.assertEqual(list(islice(range(10), None, None, None)), list(range(10)))
+        self.assertEqual(list(islice(range(10), 2, None)), list(range(2, 10)))
+        self.assertEqual(list(islice(range(10), 1, None, 2)), list(range(1, 10, 2)))
 
         # Test number of items consumed     SF #1171417
         it = iter(range(10))
-        self.assertEqual(list(islice(it, 3)), range(3))
-        self.assertEqual(list(it), range(3, 10))
+        self.assertEqual(list(islice(it, 3)), list(range(3)))
+        self.assertEqual(list(it), list(range(3, 10)))
 
         # Test invalid arguments
-        self.assertRaises(TypeError, islice, xrange(10))
-        self.assertRaises(TypeError, islice, xrange(10), 1, 2, 3, 4)
-        self.assertRaises(ValueError, islice, xrange(10), -5, 10, 1)
-        self.assertRaises(ValueError, islice, xrange(10), 1, -5, -1)
-        self.assertRaises(ValueError, islice, xrange(10), 1, 10, -1)
-        self.assertRaises(ValueError, islice, xrange(10), 1, 10, 0)
-        self.assertRaises(ValueError, islice, xrange(10), 'a')
-        self.assertRaises(ValueError, islice, xrange(10), 'a', 1)
-        self.assertRaises(ValueError, islice, xrange(10), 1, 'a')
-        self.assertRaises(ValueError, islice, xrange(10), 'a', 1, 1)
-        self.assertRaises(ValueError, islice, xrange(10), 1, 'a', 1)
+        self.assertRaises(TypeError, islice, range(10))
+        self.assertRaises(TypeError, islice, range(10), 1, 2, 3, 4)
+        self.assertRaises(ValueError, islice, range(10), -5, 10, 1)
+        self.assertRaises(ValueError, islice, range(10), 1, -5, -1)
+        self.assertRaises(ValueError, islice, range(10), 1, 10, -1)
+        self.assertRaises(ValueError, islice, range(10), 1, 10, 0)
+        self.assertRaises(ValueError, islice, range(10), 'a')
+        self.assertRaises(ValueError, islice, range(10), 'a', 1)
+        self.assertRaises(ValueError, islice, range(10), 1, 'a')
+        self.assertRaises(ValueError, islice, range(10), 'a', 1, 1)
+        self.assertRaises(ValueError, islice, range(10), 1, 'a', 1)
         self.assertEqual(len(list(islice(count(), 1, 10, sys.maxint))), 1)
 
     def test_takewhile(self):
@@ -364,7 +366,7 @@ class TestBasicOps(unittest.TestCase):
     def test_tee(self):
         n = 200
         def irange(n):
-            for i in xrange(n):
+            for i in range(n):
                 yield i
 
         a, b = tee([])        # test empty iterator
@@ -375,22 +377,22 @@ class TestBasicOps(unittest.TestCase):
         self.assertEqual(lzip(a,b), lzip(range(n), range(n)))
 
         a, b = tee(irange(n)) # test 0% interleaved
-        self.assertEqual(list(a), range(n))
-        self.assertEqual(list(b), range(n))
+        self.assertEqual(list(a), list(range(n)))
+        self.assertEqual(list(b), list(range(n)))
 
         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)
         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
-        for i in xrange(100):
+        for i in range(100):
             self.assertEqual(next(a), i)
         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
             random.shuffle(order)
             lists = ([], [])
@@ -398,8 +400,8 @@ class TestBasicOps(unittest.TestCase):
             for i in order:
                 value = next(its[i])
                 lists[i].append(value)
-            self.assertEqual(lists[0], range(n))
-            self.assertEqual(lists[1], range(n))
+            self.assertEqual(lists[0], list(range(n)))
+            self.assertEqual(lists[1], list(range(n)))
 
         # test argument format checking
         self.assertRaises(TypeError, tee)
@@ -413,18 +415,18 @@ class TestBasicOps(unittest.TestCase):
         self.assertEqual(list(c), list('def'))
 
         # test long-lagged and multi-way split
-        a, b, c = tee(xrange(2000), 3)
-        for i in xrange(100):
+        a, b, c = tee(range(2000), 3)
+        for i in range(100):
             self.assertEqual(next(a), i)
-        self.assertEqual(list(b), range(2000))
-        self.assertEqual([next(c), next(c)], range(2))
-        self.assertEqual(list(a), range(100,2000))
-        self.assertEqual(list(c), range(2,2000))
+        self.assertEqual(list(b), list(range(2000)))
+        self.assertEqual([next(c), next(c)], list(range(2)))
+        self.assertEqual(list(a), list(range(100,2000)))
+        self.assertEqual(list(c), list(range(2,2000)))
 
         # test values of n
         self.assertRaises(TypeError, tee, 'abc', 'invalid')
         self.assertRaises(ValueError, tee, [], -1)
-        for n in xrange(5):
+        for n in range(5):
             result = tee('abc', n)
             self.assertEqual(type(result), tuple)
             self.assertEqual(len(result), n)
@@ -444,7 +446,7 @@ class TestBasicOps(unittest.TestCase):
         self.assert_(list(t1) == list(t2) == list(t3) == list('abc'))
 
         # test that tee objects are weak referencable
-        a, b = tee(xrange(10))
+        a, b = tee(range(10))
         p = proxy(a)
         self.assertEqual(getattr(p, '__class__'), type(b))
         del a
@@ -608,7 +610,7 @@ def L(seqn):
 class TestVariousIteratorArgs(unittest.TestCase):
 
     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):
                 self.assertEqual(list(chain(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)))
 
     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):
                 tgtlen = len(s) * 3
                 expected = list(g(s))*3
@@ -628,7 +630,7 @@ class TestVariousIteratorArgs(unittest.TestCase):
             self.assertRaises(ZeroDivisionError, list, cycle(E(s)))
 
     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):
                 self.assertEqual([k for k, sb in groupby(g(s))], list(g(s)))
             self.assertRaises(TypeError, groupby, X(s))
@@ -636,7 +638,7 @@ class TestVariousIteratorArgs(unittest.TestCase):
             self.assertRaises(ZeroDivisionError, list, groupby(E(s)))
 
     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):
                 self.assertEqual(list(ifilter(isEven, g(s))), filter(isEven, g(s)))
             self.assertRaises(TypeError, ifilter, isEven, X(s))
@@ -644,7 +646,7 @@ class TestVariousIteratorArgs(unittest.TestCase):
             self.assertRaises(ZeroDivisionError, list, ifilter(isEven, E(s)))
 
     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):
                 self.assertEqual(list(ifilterfalse(isEven, g(s))), filter(isOdd, g(s)))
             self.assertRaises(TypeError, ifilterfalse, isEven, X(s))
@@ -652,7 +654,7 @@ class TestVariousIteratorArgs(unittest.TestCase):
             self.assertRaises(ZeroDivisionError, list, ifilterfalse(isEven, E(s)))
 
     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):
                 self.assertEqual(list(izip(g(s))), lzip(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)))
 
     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):
                 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))))
@@ -670,7 +672,7 @@ class TestVariousIteratorArgs(unittest.TestCase):
             self.assertRaises(ZeroDivisionError, list, izip_longest(E(s)))
 
     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):
                 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)))
@@ -679,7 +681,7 @@ class TestVariousIteratorArgs(unittest.TestCase):
             self.assertRaises(ZeroDivisionError, list, imap(onearg, E(s)))
 
     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):
                 self.assertEqual(list(islice(g(s),1,None,2)), list(g(s))[1::2])
             self.assertRaises(TypeError, islice, X(s), 10)
@@ -687,7 +689,7 @@ class TestVariousIteratorArgs(unittest.TestCase):
             self.assertRaises(ZeroDivisionError, list, islice(E(s), 10))
 
     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):
                 ss = lzip(s, 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)))
 
     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):
                 tgt = []
                 for elem in g(s):
@@ -708,7 +710,7 @@ class TestVariousIteratorArgs(unittest.TestCase):
             self.assertRaises(ZeroDivisionError, list, takewhile(isEven, E(s)))
 
     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):
                 tgt = []
                 for elem in g(s):
@@ -720,7 +722,7 @@ class TestVariousIteratorArgs(unittest.TestCase):
             self.assertRaises(ZeroDivisionError, list, dropwhile(isOdd, E(s)))
 
     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):
                 it1, it2 = tee(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
 
 >>> 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)
 ...
 1
@@ -968,7 +970,7 @@ True
 >>> no([1, 2, 5, 9], lambda x: x%2==0)
 False
 
->>> quantify(xrange(99), lambda x: x%2==0)
+>>> quantify(range(99), lambda x: x%2==0)
 50
 
 >>> a = [[1, 2, 3], [4, 5, 6]]
@@ -1014,7 +1016,7 @@ def test_main(verbose=None):
     if verbose and hasattr(sys, "gettotalrefcount"):
         import gc
         counts = [None] * 5
-        for i in xrange(len(counts)):
+        for i in range(len(counts)):
             test_support.run_unittest(*test_classes)
             gc.collect()
             counts[i] = sys.gettotalrefcount()
index 5d9983f454320bf8ae16ef532d6746f7deddcbcb..ea78773f7b9a4d1ca6cfa46ae5f14335a148f603 100644 (file)
@@ -26,7 +26,7 @@ def test_main(verbose=None):
     if verbose and hasattr(sys, "gettotalrefcount"):
         import gc
         counts = [None] * 5
-        for i in xrange(len(counts)):
+        for i in range(len(counts)):
             test_support.run_unittest(ListTest)
             gc.collect()
             counts[i] = sys.gettotalrefcount()
index bef4fff0ee3c4b681bbfd8150ecd3ad86df78226..65907775f913c0d229e1ac5150efd548414ad955 100644 (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()
 
     >>> def frange(n):
-    ...     return [i for i in xrange(n)]
+    ...     return [i for i in range(n)]
     >>> frange(10)
     [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 
 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)
     [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 
 Generators can call other generators:
 
     >>> def grange(n):
-    ...     for x in [i for i in xrange(n)]:
+    ...     for x in [i for i in range(n)]:
     ...         yield x
     >>> list(grange(5))
     [0, 1, 2, 3, 4]
@@ -64,7 +64,7 @@ Generators can call other generators:
 
 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]
 
 ########### Tests for various scoping corner cases ############
@@ -138,7 +138,7 @@ def test_main(verbose=None):
     if verbose and hasattr(sys, "gettotalrefcount"):
         import gc
         counts = [None] * 5
-        for i in xrange(len(counts)):
+        for i in range(len(counts)):
             test_support.run_doctest(test_genexps, verbose)
             gc.collect()
             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()
 
     >>> def frange(n):
-    ...     return [i for i in xrange(n)]
+    ...     return [i for i in range(n)]
     >>> frange(10)
     [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 
 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)
     [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 
 Generators can call other generators:
 
     >>> def grange(n):
-    ...     for x in [i for i in xrange(n)]:
+    ...     for x in [i for i in range(n)]:
     ...         yield x
     >>> list(grange(5))
     [0, 1, 2, 3, 4]
@@ -212,7 +212,7 @@ Generators can call other generators:
 
 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]
 
 ########### Tests for various scoping corner cases ############
@@ -286,7 +286,7 @@ def test_main(verbose=None):
     if verbose and hasattr(sys, "gettotalrefcount"):
         import gc
         counts = [None] * 5
-        for i in xrange(len(counts)):
+        for i in range(len(counts)):
             test_support.run_doctest(test_genexps, verbose)
             gc.collect()
             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()
 
     >>> def frange(n):
-    ...     return [i for i in xrange(n)]
+    ...     return [i for i in range(n)]
     >>> frange(10)
     [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 
 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)
     [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 
 Generators can call other generators:
 
     >>> def grange(n):
-    ...     for x in [i for i in xrange(n)]:
+    ...     for x in [i for i in range(n)]:
     ...         yield x
     >>> list(grange(5))
     [0, 1, 2, 3, 4]
@@ -360,7 +360,7 @@ Generators can call other generators:
 
 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]
 
 ########### Tests for various scoping corner cases ############
@@ -434,7 +434,7 @@ def test_main(verbose=None):
     if verbose and hasattr(sys, "gettotalrefcount"):
         import gc
         counts = [None] * 5
-        for i in xrange(len(counts)):
+        for i in range(len(counts)):
             test_support.run_doctest(test_genexps, verbose)
             gc.collect()
             counts[i] = sys.gettotalrefcount()
index e8e4a8dba9ffede8a6dd9488e4974d6ed2715299..c8e77e8bea835aaebc75233b89169bc3264fa681 100644 (file)
@@ -355,7 +355,7 @@ def test2():
     logger.info("Info message")
     message("-- logging at WARNING, 3 messages should be seen --")
     logger.warn("Warn message")
-    for i in xrange(102):
+    for i in range(102):
         message(MSG % i)
         logger.info("Info index = %d", i)
     mh.close()
index 1f652029a9b84fafdabc7b0fc5cbcc102bc6c5cd..c38056da0f87b6b74193b3f3b07d6d72539b1899 100644 (file)
@@ -71,7 +71,7 @@ class LongTest(unittest.TestCase):
 
     def getran2(ndigits):
         answer = 0
-        for i in xrange(ndigits):
+        for i in range(ndigits):
             answer = (answer << SHIFT) | random.randint(0, MASK)
         if random.random() < 0.5:
             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))
 
     def test_division(self):
-        digits = range(1, MAXDIGITS+1) + range(KARATSUBA_CUTOFF,
-                                               KARATSUBA_CUTOFF + 14)
+        digits = list(range(1, MAXDIGITS+1)) + list(range(KARATSUBA_CUTOFF,
+                                                      KARATSUBA_CUTOFF + 14))
         digits.append(KARATSUBA_CUTOFF * 3)
         for lenx in digits:
             x = self.getran(lenx)
@@ -102,7 +102,8 @@ class LongTest(unittest.TestCase):
                 self.check_division(x, y)
 
     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])
 
         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, 1 + ~x, Frm("not -x == 1 + ~x for x=%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
             eq(x << n >> n, x,
                 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):
         for x in special:
             self.check_bitop_identities_1(x)
-        digits = xrange(1, MAXDIGITS+1)
+        digits = range(1, MAXDIGITS+1)
         for lenx in digits:
             x = self.getran(lenx)
             self.check_bitop_identities_1(x)
@@ -229,8 +230,8 @@ class LongTest(unittest.TestCase):
     def test_format(self):
         for x in special:
             self.check_format_1(x)
-        for i in xrange(10):
-            for lenx in xrange(1, MAXDIGITS+1):
+        for i in range(10):
+            for lenx in range(1, MAXDIGITS+1):
                 x = self.getran(lenx)
                 self.check_format_1(x)
 
@@ -399,7 +400,7 @@ class LongTest(unittest.TestCase):
 
         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
             log10 = math.log10(value)
             self.assertAlmostEqual(log10, exp)
index 1972ca3690b405f65c018661912bc4f2d591161e..84a9e5cdc58aa2794f0910295332a0390dc1560c 100644 (file)
@@ -208,7 +208,7 @@ class TestMailbox(TestBase):
         for value in method():
             self.fail("Not empty")
         keys, values = [], []
-        for i in xrange(repetitions):
+        for i in range(repetitions):
             keys.append(self._box.add(self._template % i))
             values.append(self._template % i)
         if do_keys and not do_values:
@@ -254,11 +254,11 @@ class TestMailbox(TestBase):
     def test_len(self, repetitions=10):
         # Get message count
         keys = []
-        for i in xrange(repetitions):
+        for i in range(repetitions):
             self.assert_(len(self._box) == i)
             keys.append(self._box.add(self._template % i))
             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._box.remove(keys[i])
             self.assert_(len(self._box) == repetitions - i - 1)
@@ -293,7 +293,7 @@ class TestMailbox(TestBase):
     def test_clear(self, iterations=10):
         # Remove all messages using clear()
         keys = []
-        for i in xrange(iterations):
+        for i in range(iterations):
             self._box.add(self._template % i)
         for i, key in enumerate(keys):
             self.assert_(self._box.get_string(key) == self._template % i)
@@ -323,10 +323,10 @@ class TestMailbox(TestBase):
     def test_popitem(self, iterations=10):
         # Get and remove an arbitrary (key, message) using popitem()
         keys = []
-        for i in xrange(10):
+        for i in range(10):
             keys.append(self._box.add(self._template % i))
         seen = []
-        for i in xrange(10):
+        for i in range(10):
             key, msg = self._box.popitem()
             self.assert_(key in keys)
             self.assert_(key not in seen)
@@ -387,7 +387,7 @@ class TestMailbox(TestBase):
         self._test_flush_or_close(self._box.close)
 
     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[1])
         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+)"
                              r"Q(?P<Q>\d+)\.(?P<host>[^:/]+)")
         previous_groups = None
-        for x in xrange(repetitions):
+        for x in range(repetitions):
             tmp_file = self._box._create_tmp()
             head, tail = os.path.split(tmp_file.name)
             self.assertEqual(head, os.path.abspath(os.path.join(self._path,
@@ -703,7 +703,7 @@ class _TestMboxMMDF(TestMailbox):
 
     def test_open_close_open(self):
         # 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:
             self._box.add(value)
         self._box.close()
@@ -718,7 +718,7 @@ class _TestMboxMMDF(TestMailbox):
     def test_add_and_close(self):
         # Verifying that closing a mailbox doesn't change added items
         self._box.add(_sample_message)
-        for i in xrange(3):
+        for i in range(3):
             self._box.add(self._template % i)
         self._box.add(_sample_message)
         self._box._file.flush()
index 5c8b40dce6e819b251868a34372ce8fec1375f68..f425cb9c0b96362b2b6870ae86195d5de6607dcf 100644 (file)
@@ -121,7 +121,7 @@ class MhlibTests(unittest.TestCase):
                       'Date': '29 July 2001'}, "Hullo, Mrs. Premise!\n")
 
         # 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,
                          {'From': 'nowhere', 'Subject': 'message #%s' % i},
                          "This is message number %s\n" % i)
@@ -203,7 +203,7 @@ class MhlibTests(unittest.TestCase):
 
         f = mh.openfolder('wide')
         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)
         f.setcurrent(99)
         eq(readFile(os.path.join(_mhpath, 'wide', '.mh_sequences')),
@@ -212,21 +212,21 @@ class MhlibTests(unittest.TestCase):
         def seqeq(seq, val):
             eq(f.parsesequence(seq), val)
 
-        seqeq('5-55', range(5, 56))
-        seqeq('90-108', range(90, 101)+range(101, 109, 2))
-        seqeq('90-108', range(90, 101)+range(101, 109, 2))
+        seqeq('5-55', list(range(5, 56)))
+        seqeq('90-108', list(range(90, 101))+list(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', range(10, 20))
-        seqeq('101:10', range(101, 121, 2))
+        seqeq('10:10', list(range(10, 20)))
+        seqeq('10:+10', list(range(10, 20)))
+        seqeq('101:10', list(range(101, 121, 2)))
 
         seqeq('cur', [99])
         seqeq('.', [99])
         seqeq('prev', [98])
         seqeq('next', [100])
         seqeq('cur:-3', [97, 98, 99])
-        seqeq('first-cur', range(5, 100))
-        seqeq('150-last', range(151, 201, 2))
+        seqeq('first-cur', list(range(5, 100)))
+        seqeq('150-last', list(range(151, 201, 2)))
         seqeq('prev-next', [98, 99, 100])
 
         lowprimes = [5, 7, 11, 13, 17, 19, 23, 29]
index b0b5b01be54fcf7ecc64219c5c3b571e54e51e92..ad24776ac824abb18451435ad241b1ad2e4e573d 100644 (file)
@@ -26,7 +26,7 @@ class MimeToolsTest(unittest.TestCase):
 
     def test_boundary(self):
         s = set([""])
-        for i in xrange(100):
+        for i in range(100):
             nb = mimetools.choose_boundary()
             self.assert_(nb not in s)
             s.add(nb)
index 0b5382307619efc0d288624677f5cc94ec2d7141..605ad3dd4941d7245004380d95b37f1d39dddac4 100644 (file)
@@ -299,10 +299,10 @@ class MmapTests(unittest.TestCase):
     def test_anonymous(self):
         # anonymous mmap.mmap(-1, PAGE)
         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")
 
-        for x in xrange(PAGESIZE):
+        for x in range(PAGESIZE):
             m[x] = ch = chr(x & 255)
             self.assertEqual(m[x], ch)
 
index 0b2021a52568f290e43699ea26487d453b42e331..3725f9ea251577c5ede182f3913cf928020a55da 100644 (file)
@@ -214,7 +214,7 @@ class Test_ISO2022(unittest.TestCase):
         else:
             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
             myunichr(x).encode('iso_2022_jp', 'ignore')
 
index acfb2f1aa8185afea316373243fb5090027d18c5..0a3f9640640b68766d2ca17b7b43369caf2bf757 100644 (file)
@@ -145,7 +145,7 @@ class TestBase:
 
     def test_incrementalencoder(self):
         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]:
             istream = UTF8Reader(StringIO(self.tstring[1]))
             ostream = StringIO()
@@ -165,7 +165,7 @@ class TestBase:
 
     def test_incrementaldecoder(self):
         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]:
             istream = StringIO(self.tstring[0])
             ostream = UTF8Writer(StringIO())
@@ -203,7 +203,7 @@ class TestBase:
     def test_streamreader(self):
         UTF8Writer = codecs.getwriter('utf-8')
         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]:
                 istream = self.reader(StringIO(self.tstring[0]))
                 ostream = UTF8Writer(StringIO())
@@ -223,7 +223,7 @@ class TestBase:
         readfuncs = ('read', 'readline', 'readlines')
         UTF8Reader = codecs.getreader('utf-8')
         for name in readfuncs:
-            for sizehint in [None] + range(1, 33) + \
+            for sizehint in [None] + list(range(1, 33)) + \
                             [64, 128, 256, 512, 1024]:
                 istream = UTF8Reader(StringIO(self.tstring[1]))
                 ostream = self.writer(StringIO())
index d40e45fdb59ddeee724c562eb20b4ca58b507283..7fff78417c04551836fb24bedad216ee2eb656a1 100644 (file)
@@ -113,7 +113,7 @@ class Horrid:
 
 def fill_dict(d, candidates, numentries):
     d.clear()
-    for i in xrange(numentries):
+    for i in range(numentries):
         d[Horrid(random.choice(candidates))] = \
             Horrid(random.choice(candidates))
     return list(d.keys())
@@ -152,7 +152,7 @@ def test_one(n):
 # leak).
 
 def test(n):
-    for i in xrange(n):
+    for i in range(n):
         test_one(random.randrange(1, 100))
 
 # See last comment block for clues about good values for n.
index 8d70564e71993e117052cbadcf2f31b1c9f60887..8b705e4b3a33539e5ffcd7bea1ceedf4060f374f 100644 (file)
@@ -138,7 +138,7 @@ class OperatorTestCase(unittest.TestCase):
         self.assert_(a == [4, 2, 1])
 
     def test_delslice(self):
-        a = range(10)
+        a = list(range(10))
         self.failUnlessRaises(TypeError, operator.delslice, a)
         self.failUnlessRaises(TypeError, operator.delslice, a, None, 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)
 
     def test_getslice(self):
-        a = range(10)
+        a = list(range(10))
         self.failUnlessRaises(TypeError, operator.getslice)
         self.failUnlessRaises(TypeError, operator.getslice, a, None, None)
         self.failUnless(operator.getslice(a, 4, 6) == [4, 5])
@@ -200,7 +200,7 @@ class OperatorTestCase(unittest.TestCase):
         self.failUnlessRaises(TypeError, operator.isSequenceType)
         self.failUnless(operator.isSequenceType(dir()))
         self.failUnless(operator.isSequenceType(()))
-        self.failUnless(operator.isSequenceType(xrange(10)))
+        self.failUnless(operator.isSequenceType(range(10)))
         self.failUnless(operator.isSequenceType('yeahbuddy'))
         self.failIf(operator.isSequenceType(3))
         class Dict(dict): pass
@@ -253,7 +253,7 @@ class OperatorTestCase(unittest.TestCase):
         self.assertRaises(TypeError, operator.pow, 1, 2, 3)
 
     def test_repeat(self):
-        a = range(3)
+        a = list(range(3))
         self.failUnlessRaises(TypeError, operator.repeat)
         self.failUnlessRaises(TypeError, operator.repeat, a, None)
         self.failUnless(operator.repeat(a, 2) == a+a)
@@ -291,7 +291,7 @@ class OperatorTestCase(unittest.TestCase):
         self.failIf(operator.contains(range(4), 5))
 
     def test_setitem(self):
-        a = range(3)
+        a = list(range(3))
         self.failUnlessRaises(TypeError, operator.setitem, a)
         self.failUnlessRaises(TypeError, operator.setitem, a, None, 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)
 
     def test_setslice(self):
-        a = range(4)
+        a = list(range(4))
         self.failUnlessRaises(TypeError, operator.setslice, a)
         self.failUnlessRaises(TypeError, operator.setslice, a, None, None, 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"):
         import gc
         counts = [None] * 5
-        for i in xrange(len(counts)):
+        for i in range(len(counts)):
             test_support.run_unittest(*test_classes)
             gc.collect()
             counts[i] = sys.gettotalrefcount()
index 1611e39479dcdb94618032796b20b2cbe3df0f1e..b2901985147cfc4f20c0ad4c826f259ed01ed19c 100644 (file)
@@ -220,7 +220,7 @@ def test_main(verbose=None):
     if verbose and hasattr(sys, "gettotalrefcount"):
         import gc
         counts = [None] * 5
-        for i in xrange(len(counts)):
+        for i in range(len(counts)):
             test_support.run_unittest(*test_classes)
             gc.collect()
             counts[i] = sys.gettotalrefcount()
index 48862ce473efdac1e3dc25de86af7fc2a50221bb..e39a397fd351b0e7621de37dc150ef3f87f491f0 100644 (file)
@@ -36,7 +36,8 @@ class ExceptionClassTests(unittest.TestCase):
                 last_exc = getattr(__builtin__, superclass_name)
             except AttributeError:
                 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)
             superclasses = []  # Loop will insert base exception
             last_depth = 0
index 493aac2bb6472f9af638a72466c6f0d93291f127..62c641b10bd04903932e28d76cb3133623ba0bca 100644 (file)
@@ -14,12 +14,12 @@ class PowTest(unittest.TestCase):
                 self.assertEquals(pow(type(i), 3), i*i*i)
 
             pow2 = 1
-            for i in range(0,31):
+            for i in range(0, 31):
                 self.assertEquals(pow(2, i), pow2)
                 if i != 30 : pow2 = pow2*2
 
             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)
                     for j in range(1, 11):
                         jj = -othertype(j)
index c2818724506fc2dcb69d7a18f23db90ffe3b9a5f..f7f6ac6fd9377bcf804994949c1ed16fbc47fbf4 100644 (file)
@@ -33,8 +33,8 @@ class dict3(dict):
 class QueryTestCase(unittest.TestCase):
 
     def setUp(self):
-        self.a = range(100)
-        self.b = range(200)
+        self.a = list(range(100))
+        self.b = list(range(200))
         self.a[-12] = self.b
 
     def test_basic(self):
index 375b2e9dff75dea268ae10a176429a6889901a37..a50ed2168e7e493b785e32f9cfb54c9ff535f049 100644 (file)
@@ -60,7 +60,7 @@ class PwdTest(unittest.TestCase):
         fakename = allnames[namei]
         while fakename in bynames:
             chars = map(None, fakename)
-            for i in xrange(len(chars)):
+            for i in range(len(chars)):
                 if chars[i] == 'z':
                     chars[i] = 'A'
                     break
index ac382c14cfb33439cfe7ce8238aa122351f396ce..bfa5596cbb3c0e5a8cb62230d2d49f246836d48e 100644 (file)
@@ -243,7 +243,7 @@ def QueueJoinTest(q):
     cum = 0
     for i in (0,1):
         threading.Thread(target=worker, args=(q,)).start()
-    for i in xrange(100):
+    for i in range(100):
         q.put(i)
     q.join()
     verify(cum==sum(range(100)), "q.join() did not block until all tasks were done")
index e4a279256aaf25052e880aa3181a8274df99080c..d676a4e85625f52781adaec9a4ea953b9eedd795 100644 (file)
@@ -15,7 +15,7 @@ class TestBasicOps(unittest.TestCase):
 
     def randomlist(self, n):
         """Helper function to make a list of random numbers"""
-        return [self.gen.random() for i in xrange(n)]
+        return [self.gen.random() for i in range(n)]
 
     def test_autoseed(self):
         self.gen.seed()
@@ -37,7 +37,7 @@ class TestBasicOps(unittest.TestCase):
         for arg in [None, 0, 0, 1, 1, -1, -1, 10**20, -(10**20),
                     3.14, 1+2j, 'a', tuple('abc')]:
             self.gen.seed(arg)
-        for arg in [range(3), dict(one=1)]:
+        for arg in [list(range(3)), dict(one=1)]:
             self.assertRaises(TypeError, self.gen.seed, arg)
         self.assertRaises(TypeError, self.gen.seed, 1, 2)
         self.assertRaises(TypeError, type(self.gen), [])
@@ -61,8 +61,8 @@ class TestBasicOps(unittest.TestCase):
         # For the entire allowable range of 0 <= k <= N, validate that
         # the sample is of the correct length and contains only unique items
         N = 100
-        population = xrange(N)
-        for k in xrange(N+1):
+        population = range(N)
+        for k in range(N+1):
             s = self.gen.sample(population, k)
             self.assertEqual(len(s), k)
             uniq = set(s)
@@ -80,10 +80,10 @@ class TestBasicOps(unittest.TestCase):
             if n == 0:
                 return 1
             return n * factorial(n - 1)
-        for k in xrange(n):
+        for k in range(n):
             expected = factorial(n) // factorial(n-k)
             perms = {}
-            for i in xrange(trials):
+            for i in range(trials):
                 perms[tuple(self.gen.sample(pop, k))] = None
                 if len(perms) == expected:
                     break
@@ -94,7 +94,7 @@ class TestBasicOps(unittest.TestCase):
         # SF bug #801342 -- population can be any iterable defining __len__()
         self.gen.sample(set(range(20)), 2)
         self.gen.sample(range(20), 2)
-        self.gen.sample(xrange(20), 2)
+        self.gen.sample(range(20), 2)
         self.gen.sample(str('abcdefghijklmnopqrst'), 2)
         self.gen.sample(tuple('abcdefghijklmnopqrst'), 2)
 
@@ -102,21 +102,23 @@ class TestBasicOps(unittest.TestCase):
         self.gen.sample(dict.fromkeys('abcdefghijklmnopqrst'), 2)
 
         # SF bug #1460340 -- random.sample can raise KeyError
-        a = dict.fromkeys(range(10)+range(10,100,2)+range(100,110))
+        a = dict.fromkeys(list(range(10)) +
+                          list(range(10,100,2)) +
+                          list(range(100,110)))
         self.gen.sample(a, 3)
 
         # A followup to bug #1460340:  sampling from a dict could return
         # a subset of its keys or of its values, depending on the size of
         # the subset requested.
         N = 30
-        d = dict((i, complex(i, i)) for i in xrange(N))
-        for k in xrange(N+1):
+        d = dict((i, complex(i, i)) for i in range(N))
+        for k in range(N+1):
             samp = self.gen.sample(d, k)
             # Verify that we got ints back (keys); the values are complex.
             for x in samp:
                 self.assert_(type(x) is int)
         samp.sort()
-        self.assertEqual(samp, range(N))
+        self.assertEqual(samp, list(range(N)))
 
     def test_gauss(self):
         # Ensure that the seed() method initializes all the hidden state.  In
@@ -137,9 +139,9 @@ class TestBasicOps(unittest.TestCase):
 
     def test_pickling(self):
         state = pickle.dumps(self.gen)
-        origseq = [self.gen.random() for i in xrange(10)]
+        origseq = [self.gen.random() for i in range(10)]
         newgen = pickle.loads(state)
-        restoredseq = [newgen.random() for i in xrange(10)]
+        restoredseq = [newgen.random() for i in range(10)]
         self.assertEqual(origseq, restoredseq)
 
 class WichmannHill_TestBasicOps(TestBasicOps):
@@ -156,7 +158,7 @@ class WichmannHill_TestBasicOps(TestBasicOps):
         r1 = self.gen.random()
         # now do it the slow way
         self.gen.setstate(s)
-        for i in xrange(N):
+        for i in range(N):
             self.gen.random()
         r2 = self.gen.random()
         self.assertEqual(r1, r2)
@@ -215,7 +217,7 @@ class SystemRandom_TestBasicOps(TestBasicOps):
         # This should pass whenever a C double has 53 bit precision.
         span = 2 ** 53
         cum = 0
-        for i in xrange(100):
+        for i in range(100):
             cum |= int(self.gen.random() * span)
         self.assertEqual(cum, span-1)
 
@@ -224,7 +226,7 @@ class SystemRandom_TestBasicOps(TestBasicOps):
         # in stages so that all bit positions are active.
         span = 2 ** 500
         cum = 0
-        for i in xrange(100):
+        for i in range(100):
             r = self.gen.randrange(span)
             self.assert_(0 <= r < span)
             cum |= r
@@ -241,18 +243,18 @@ class SystemRandom_TestBasicOps(TestBasicOps):
     def test_rangelimits(self):
         for start, stop in [(-2,0), (-(2**60)-2,-(2**60)), (2**60,2**60+2)]:
             self.assertEqual(set(range(start,stop)),
-                set([self.gen.randrange(start,stop) for i in xrange(100)]))
+                set([self.gen.randrange(start,stop) for i in range(100)]))
 
     def test_genrandbits(self):
         # Verify ranges
-        for k in xrange(1, 1000):
+        for k in range(1, 1000):
             self.assert_(0 <= self.gen.getrandbits(k) < 2**k)
 
         # Verify all bits active
         getbits = self.gen.getrandbits
         for span in [1, 2, 3, 4, 31, 32, 32, 52, 53, 54, 119, 127, 128, 129]:
             cum = 0
-            for i in xrange(100):
+            for i in range(100):
                 cum |= getbits(span)
             self.assertEqual(cum, 2**span-1)
 
@@ -267,7 +269,7 @@ class SystemRandom_TestBasicOps(TestBasicOps):
         # check bitcount transition points:  2**i and 2**(i+1)-1
         # show that: k = int(1.001 + _log(n, 2))
         # is equal to or one greater than the number of bits in n
-        for i in xrange(1, 1000):
+        for i in range(1, 1000):
             n = 1 << i # check an exact power of two
             numbits = i+1
             k = int(1.00001 + _log(n, 2))
@@ -367,7 +369,7 @@ class MersenneTwister_TestBasicOps(TestBasicOps):
         # This should pass whenever a C double has 53 bit precision.
         span = 2 ** 53
         cum = 0
-        for i in xrange(100):
+        for i in range(100):
             cum |= int(self.gen.random() * span)
         self.assertEqual(cum, span-1)
 
@@ -376,7 +378,7 @@ class MersenneTwister_TestBasicOps(TestBasicOps):
         # in stages so that all bit positions are active.
         span = 2 ** 500
         cum = 0
-        for i in xrange(100):
+        for i in range(100):
             r = self.gen.randrange(span)
             self.assert_(0 <= r < span)
             cum |= r
@@ -393,7 +395,7 @@ class MersenneTwister_TestBasicOps(TestBasicOps):
     def test_rangelimits(self):
         for start, stop in [(-2,0), (-(2**60)-2,-(2**60)), (2**60,2**60+2)]:
             self.assertEqual(set(range(start,stop)),
-                set([self.gen.randrange(start,stop) for i in xrange(100)]))
+                set([self.gen.randrange(start,stop) for i in range(100)]))
 
     def test_genrandbits(self):
         # Verify cross-platform repeatability
@@ -401,14 +403,14 @@ class MersenneTwister_TestBasicOps(TestBasicOps):
         self.assertEqual(self.gen.getrandbits(100),
                          97904845777343510404718956115)
         # Verify ranges
-        for k in xrange(1, 1000):
+        for k in range(1, 1000):
             self.assert_(0 <= self.gen.getrandbits(k) < 2**k)
 
         # Verify all bits active
         getbits = self.gen.getrandbits
         for span in [1, 2, 3, 4, 31, 32, 32, 52, 53, 54, 119, 127, 128, 129]:
             cum = 0
-            for i in xrange(100):
+            for i in range(100):
                 cum |= getbits(span)
             self.assertEqual(cum, 2**span-1)
 
@@ -423,7 +425,7 @@ class MersenneTwister_TestBasicOps(TestBasicOps):
         # check bitcount transition points:  2**i and 2**(i+1)-1
         # show that: k = int(1.001 + _log(n, 2))
         # is equal to or one greater than the number of bits in n
-        for i in xrange(1, 1000):
+        for i in range(1, 1000):
             n = 1 << i # check an exact power of two
             numbits = i+1
             k = int(1.00001 + _log(n, 2))
@@ -455,7 +457,7 @@ _gammacoeff = (0.9999999999995183, 676.5203681218835, -1259.139216722289,
 def gamma(z, cof=_gammacoeff, g=7):
     z -= 1.0
     sum = cof[0]
-    for i in xrange(1,len(cof)):
+    for i in range(1,len(cof)):
         sum += cof[i] / (z+i)
     z += 0.5
     return (z+g)**z / exp(z+g) * sqrt(2*pi) * sum
@@ -464,7 +466,7 @@ class TestDistributions(unittest.TestCase):
     def test_zeroinputs(self):
         # Verify that distributions can handle a series of zero inputs'
         g = random.Random()
-        x = [g.random() for i in xrange(50)] + [0.0]*5
+        x = [g.random() for i in range(50)] + [0.0]*5
         g.random = x[:].pop; g.uniform(1,10)
         g.random = x[:].pop; g.paretovariate(1.0)
         g.random = x[:].pop; g.expovariate(1.0)
@@ -483,7 +485,7 @@ class TestDistributions(unittest.TestCase):
         # Only works for distributions which do not consume variates in pairs
         g = random.Random()
         N = 5000
-        x = [i/float(N) for i in xrange(1,N)]
+        x = [i/float(N) for i in range(1,N)]
         for variate, args, mu, sigmasqrd in [
                 (g.uniform, (1.0,10.0), (10.0+1.0)/2, (10.0-1.0)**2/12),
                 (g.expovariate, (1.5,), 1/1.5, 1/1.5**2),
@@ -493,7 +495,7 @@ class TestDistributions(unittest.TestCase):
                                   gamma(1+2/3.0)-gamma(1+1/3.0)**2) ]:
             g.random = x[:].pop
             y = []
-            for i in xrange(len(x)):
+            for i in range(len(x)):
                 try:
                     y.append(variate(*args))
                 except IndexError:
@@ -544,7 +546,7 @@ def test_main(verbose=None):
     import sys
     if verbose and hasattr(sys, "gettotalrefcount"):
         counts = [None] * 5
-        for i in xrange(len(counts)):
+        for i in range(len(counts)):
             test_support.run_unittest(*testclasses)
             counts[i] = sys.gettotalrefcount()
         print(counts)
index 1435c6f4a536ff7611ae6a3f787654554cadf50d..120a3cd6f14633e6b1b7ab6119daacd776228681 100644 (file)
@@ -135,11 +135,11 @@ class ReprTests(unittest.TestCase):
         self.failUnless(repr(''.split).startswith(
             '<built-in method split of str object at 0x'))
 
-    def test_xrange(self):
+    def test_range(self):
         eq = self.assertEquals
-        eq(repr(xrange(1)), 'xrange(1)')
-        eq(repr(xrange(1, 2)), 'xrange(1, 2)')
-        eq(repr(xrange(1, 2, 3)), 'xrange(1, 4, 3)')
+        eq(repr(range(1)), 'range(1)')
+        eq(repr(range(1, 2)), 'range(1, 2)')
+        eq(repr(range(1, 4, 3)), 'range(1, 4, 3)')
 
     def test_nesting(self):
         eq = self.assertEquals
index 99ddc30d9bda8d6f9db327c1d814beb283437779..ae33c92ef20ae34cc8666d7732bdbdedcf14cb06 100644 (file)
@@ -105,7 +105,7 @@ class VectorTest(unittest.TestCase):
             realres = op(a, b)
             # can't use assertEqual(realres, expres) here
             self.assertEqual(len(realres), len(expres))
-            for i in xrange(len(realres)):
+            for i in range(len(realres)):
                 # results are bool, so we can use "is" here
                 self.assert_(realres[i] is expres[i])
 
@@ -119,7 +119,7 @@ class VectorTest(unittest.TestCase):
         for opname in opmap:
             self.checkfail(ValueError, opname, a, b)
 
-        a = range(5)
+        a = list(range(5))
         b = 5 * [2]
         # try mixed arguments (but not (a, b) as that won't return a bool vector)
         args = [(a, Vector(b)), (Vector(a), b), (Vector(a), Vector(b))]
@@ -142,8 +142,8 @@ class NumberTest(unittest.TestCase):
         # Check that comparisons involving Number objects
         # give the same results give as comparing the
         # corresponding ints
-        for a in xrange(3):
-            for b in xrange(3):
+        for a in range(3):
+            for b in range(3):
                 for typea in (int, Number):
                     for typeb in (int, Number):
                         if typea==typeb==int:
index 0e4762376940cd5a1d25727886da47606cdff34f..3b6247846e7438be9f7f6f995efabda6c160c7e3 100644 (file)
@@ -227,7 +227,7 @@ class TestJointOps(unittest.TestCase):
         # Create a nest of cycles to exercise overall ref count check
         class A:
             pass
-        s = set(A() for i in xrange(1000))
+        s = set(A() for i in range(1000))
         for elem in s:
             elem.cycle = s
             elem.sub = elem
@@ -283,7 +283,7 @@ class TestJointOps(unittest.TestCase):
 
     def test_do_not_rehash_dict_keys(self):
         n = 10
-        d = dict.fromkeys(map(HashCountingInt, xrange(n)))
+        d = dict.fromkeys(map(HashCountingInt, range(n)))
         self.assertEqual(sum(elem.hash_count for elem in d), n)
         s = self.thetype(d)
         self.assertEqual(sum(elem.hash_count for elem in d), n)
@@ -377,7 +377,7 @@ class TestSet(TestJointOps):
         s.discard(self.thetype(self.word))
 
     def test_pop(self):
-        for i in xrange(len(self.s)):
+        for i in range(len(self.s)):
             elem = self.s.pop()
             self.assert_(elem not in self.s)
         self.assertRaises(KeyError, self.s.pop)
@@ -525,7 +525,7 @@ class TestFrozenSet(TestJointOps):
         f = frozenset()
         efs = [frozenset(), frozenset([]), frozenset(()), frozenset(''),
                frozenset(), frozenset([]), frozenset(()), frozenset(''),
-               frozenset(xrange(0)), frozenset(frozenset()),
+               frozenset(range(0)), frozenset(frozenset()),
                frozenset(f), f]
         # All of the empty frozensets should have just one id()
         self.assertEqual(len(set(map(id, efs))), 1)
@@ -541,9 +541,9 @@ class TestFrozenSet(TestJointOps):
 
         # make sure that all permutations give the same hash value
         n = 100
-        seq = [randrange(n) for i in xrange(n)]
+        seq = [randrange(n) for i in range(n)]
         results = set()
-        for i in xrange(200):
+        for i in range(200):
             shuffle(seq)
             results.add(hash(self.thetype(seq)))
         self.assertEqual(len(results), 1)
@@ -553,7 +553,7 @@ class TestFrozenSet(TestJointOps):
         self.assertEqual(id(self.s), id(dup))
 
     def test_frozen_as_dictkey(self):
-        seq = range(10) + list('abcdefg') + ['apple']
+        seq = list(range(10)) + list('abcdefg') + ['apple']
         key1 = self.thetype(seq)
         key2 = self.thetype(reversed(seq))
         self.assertEqual(key1, key2)
@@ -571,7 +571,7 @@ class TestFrozenSet(TestJointOps):
         hashvalues = set()
         addhashvalue = hashvalues.add
         elemmasks = [(i+1, 1<<i) for i in range(n)]
-        for i in xrange(2**n):
+        for i in range(2**n):
             addhashvalue(hash(frozenset([e for e, m in elemmasks if m&i])))
         self.assertEqual(len(hashvalues), 2**n)
 
@@ -601,7 +601,7 @@ class TestFrozenSetSubclass(TestFrozenSet):
         F = Frozenset()
         efs = [Frozenset(), Frozenset([]), Frozenset(()), Frozenset(''),
                Frozenset(), Frozenset([]), Frozenset(()), Frozenset(''),
-               Frozenset(xrange(0)), Frozenset(Frozenset()),
+               Frozenset(range(0)), Frozenset(Frozenset()),
                Frozenset(frozenset()), f, F, Frozenset(f), Frozenset(F)]
         # All empty frozenset subclass instances should have different ids
         self.assertEqual(len(set(map(id, efs))), len(efs))
@@ -775,7 +775,7 @@ class TestExceptionPropagation(unittest.TestCase):
         set([1,2,3])
         set((1,2,3))
         set({'one':1, 'two':2, 'three':3})
-        set(xrange(3))
+        set(range(3))
         set('abc')
         set(gooditer())
 
@@ -1268,7 +1268,7 @@ class TestOnlySetsString(TestOnlySetsInBinaryOps):
 class TestOnlySetsGenerator(TestOnlySetsInBinaryOps):
     def setUp(self):
         def gen():
-            for i in xrange(0, 10, 2):
+            for i in range(0, 10, 2):
                 yield i
         self.set   = set((1, 2, 3))
         self.other = gen()
@@ -1451,7 +1451,7 @@ class TestVariousIteratorArgs(unittest.TestCase):
 
     def test_constructor(self):
         for cons in (set, frozenset):
-            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):
                     self.assertEqual(sorted(cons(g(s)), key=repr), sorted(g(s), key=repr))
                 self.assertRaises(TypeError, cons , X(s))
@@ -1460,7 +1460,7 @@ class TestVariousIteratorArgs(unittest.TestCase):
 
     def test_inline_methods(self):
         s = set('november')
-        for data in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5), 'december'):
+        for data in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5), 'december'):
             for meth in (s.union, s.intersection, s.difference, s.symmetric_difference):
                 for g in (G, I, Ig, L, R):
                     expected = meth(data)
@@ -1471,7 +1471,7 @@ class TestVariousIteratorArgs(unittest.TestCase):
                 self.assertRaises(ZeroDivisionError, meth, E(s))
 
     def test_inplace_methods(self):
-        for data in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5), 'december'):
+        for data in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5), 'december'):
             for methname in ('update', 'intersection_update',
                              'difference_update', 'symmetric_difference_update'):
                 for g in (G, I, Ig, S, L, R):
@@ -1529,7 +1529,7 @@ def test_main(verbose=None):
     if verbose and hasattr(sys, "gettotalrefcount"):
         import gc
         counts = [None] * 5
-        for i in xrange(len(counts)):
+        for i in range(len(counts)):
             test_support.run_unittest(*test_classes)
             gc.collect()
             counts[i] = sys.gettotalrefcount()
index c64e53e03da2ea8a1cd1501c9cc6b7c748b2dd10..021fd962c0640f9400f6e15dd38d1e836bc74b49 100644 (file)
@@ -43,23 +43,23 @@ Verify that syntax error's are raised for setcomps used as lvalues
     SyntaxError: ...
 
 
-Make a nested set comprehension that acts like set(xrange())
+Make a nested set comprehension that acts like set(range())
 
     >>> def srange(n):
-    ...     return {i for i in xrange(n)}
+    ...     return {i for i in range(n)}
     >>> list(sorted(srange(10)))
     [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 
 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)}
     >>> list(sorted(lrange(10)))
     [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 
 Generators can call other generators:
 
     >>> def grange(n):
-    ...     for x in {i for i in xrange(n)}:
+    ...     for x in {i for i in range(n)}:
     ...         yield x
     >>> list(sorted(grange(5)))
     [0, 1, 2, 3, 4]
@@ -67,7 +67,7 @@ Generators can call other generators:
 
 Make sure that None is a valid return value
 
-    >>> {None for i in xrange(10)}
+    >>> {None for i in range(10)}
     {None}
 
 ########### Tests for various scoping corner cases ############
@@ -141,7 +141,7 @@ def test_main(verbose=None):
     if verbose and hasattr(sys, "gettotalrefcount"):
         import gc
         counts = [None] * 5
-        for i in xrange(len(counts)):
+        for i in range(len(counts)):
             test_support.run_doctest(test_genexps, verbose)
             gc.collect()
             counts[i] = sys.gettotalrefcount()
@@ -194,23 +194,23 @@ Verify that syntax error's are raised for setcomps used as lvalues
     SyntaxError: ...
 
 
-Make a nested set comprehension that acts like set(xrange())
+Make a nested set comprehension that acts like set(range())
 
     >>> def srange(n):
-    ...     return {i for i in xrange(n)}
+    ...     return {i for i in range(n)}
     >>> list(sorted(srange(10)))
     [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 
 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)}
     >>> list(sorted(lrange(10)))
     [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 
 Generators can call other generators:
 
     >>> def grange(n):
-    ...     for x in {i for i in xrange(n)}:
+    ...     for x in {i for i in range(n)}:
     ...         yield x
     >>> list(sorted(grange(5)))
     [0, 1, 2, 3, 4]
@@ -218,7 +218,7 @@ Generators can call other generators:
 
 Make sure that None is a valid return value
 
-    >>> {None for i in xrange(10)}
+    >>> {None for i in range(10)}
     {None}
 
 ########### Tests for various scoping corner cases ############
@@ -292,7 +292,7 @@ def test_main(verbose=None):
     if verbose and hasattr(sys, "gettotalrefcount"):
         import gc
         counts = [None] * 5
-        for i in xrange(len(counts)):
+        for i in range(len(counts)):
             test_support.run_doctest(test_genexps, verbose)
             gc.collect()
             counts[i] = sys.gettotalrefcount()
@@ -345,23 +345,23 @@ Verify that syntax error's are raised for setcomps used as lvalues
     SyntaxError: ...
 
 
-Make a nested set comprehension that acts like set(xrange())
+Make a nested set comprehension that acts like set(range())
 
     >>> def srange(n):
-    ...     return {i for i in xrange(n)}
+    ...     return {i for i in range(n)}
     >>> list(sorted(srange(10)))
     [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 
 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)}
     >>> list(sorted(lrange(10)))
     [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 
 Generators can call other generators:
 
     >>> def grange(n):
-    ...     for x in {i for i in xrange(n)}:
+    ...     for x in {i for i in range(n)}:
     ...         yield x
     >>> list(sorted(grange(5)))
     [0, 1, 2, 3, 4]
@@ -369,7 +369,7 @@ Generators can call other generators:
 
 Make sure that None is a valid return value
 
-    >>> {None for i in xrange(10)}
+    >>> {None for i in range(10)}
     {None}
 
 ########### Tests for various scoping corner cases ############
@@ -443,7 +443,7 @@ def test_main(verbose=None):
     if verbose and hasattr(sys, "gettotalrefcount"):
         import gc
         counts = [None] * 5
-        for i in xrange(len(counts)):
+        for i in range(len(counts)):
             test_support.run_doctest(test_genexps, verbose)
             gc.collect()
             counts[i] = sys.gettotalrefcount()
index 977b28a50ba93b798213c5abfcd644638dbd53ba..77a2931485a3cf52cb78cbe4b6d798e03f28249c 100644 (file)
@@ -89,7 +89,7 @@ class SliceTest(unittest.TestCase):
         )
         self.assertEqual(slice(-100, 100, 2).indices(10), (0, 10,  2))
 
-        self.assertEqual(range(10)[::sys.maxint - 1], [0])
+        self.assertEqual(list(range(10))[::sys.maxint - 1], [0])
 
         self.assertRaises(OverflowError, slice(None).indices, 1<<100)
 
index ad3a817ec1c936350972cdf388a8737a55cdccf1..738ffe1aa9f70a247a456cc53923f25201b55fbf 100644 (file)
@@ -75,7 +75,7 @@ class TestBase(unittest.TestCase):
                 return "Stable(%d, %d)" % (self.key, self.index)
 
         for n in sizes:
-            x = range(n)
+            x = list(range(n))
             if verbose:
                 print("Testing size", n)
 
@@ -115,7 +115,7 @@ class TestBase(unittest.TestCase):
                 Complains.maybe_complain = False
                 check("exception during sort left some permutation", x, s)
 
-            s = [Stable(random.randrange(10), i) for i in xrange(n)]
+            s = [Stable(random.randrange(10), i) for i in range(n)]
             augmented = [(e, e.index) for e in s]
             augmented.sort()    # forced stable because ties broken by index
             x = [e for e, i in augmented] # a stable sort of s
@@ -144,10 +144,10 @@ class TestBugs(unittest.TestCase):
     def test_cmpNone(self):
         # Testing None as a comparison function.
 
-        L = range(50)
+        L = list(range(50))
         random.shuffle(L)
         L.sort(None)
-        self.assertEqual(L, range(50))
+        self.assertEqual(L, list(range(50)))
 
     def test_undetected_mutation(self):
         # Python 2.4a1 did not always detect mutation
@@ -182,7 +182,7 @@ class TestDecorateSortUndecorate(unittest.TestCase):
         self.assertRaises(TypeError, data.sort, None, lambda x,y: 0)
 
     def test_stability(self):
-        data = [(random.randrange(100), i) for i in xrange(200)]
+        data = [(random.randrange(100), i) for i in range(200)]
         copy = data[:]
         data.sort(key=lambda (x,y): x)  # sort on the random first field
         copy.sort()                     # sort using both fields
@@ -204,13 +204,13 @@ class TestDecorateSortUndecorate(unittest.TestCase):
 
     def test_key_with_exception(self):
         # Verify that the wrapper has been removed
-        data = range(-2,2)
+        data = list(range(-2, 2))
         dup = data[:]
         self.assertRaises(ZeroDivisionError, data.sort, None, lambda x: 1/x)
         self.assertEqual(data, dup)
 
     def test_key_with_mutation(self):
-        data = range(10)
+        data = list(range(10))
         def k(x):
             del data[:]
             data[:] = range(20)
@@ -218,7 +218,7 @@ class TestDecorateSortUndecorate(unittest.TestCase):
         self.assertRaises(ValueError, data.sort, key=k)
 
     def test_key_with_mutating_del(self):
-        data = range(10)
+        data = list(range(10))
         class SortKiller(object):
             def __init__(self, x):
                 pass
@@ -230,7 +230,7 @@ class TestDecorateSortUndecorate(unittest.TestCase):
         self.assertRaises(ValueError, data.sort, key=SortKiller)
 
     def test_key_with_mutating_del_and_exception(self):
-        data = range(10)
+        data = list(range(10))
         ## dup = data[:]
         class SortKiller(object):
             def __init__(self, x):
@@ -238,7 +238,7 @@ class TestDecorateSortUndecorate(unittest.TestCase):
                     raise RuntimeError
             def __del__(self):
                 del data[:]
-                data[:] = range(20)
+                data[:] = list(range(20))
         self.assertRaises(RuntimeError, data.sort, key=SortKiller)
         ## major honking subtlety: we *can't* do:
         ##
@@ -250,14 +250,14 @@ class TestDecorateSortUndecorate(unittest.TestCase):
         ## date (this cost some brain cells to figure out...).
 
     def test_reverse(self):
-        data = range(100)
+        data = list(range(100))
         random.shuffle(data)
         data.sort(reverse=True)
-        self.assertEqual(data, range(99,-1,-1))
+        self.assertEqual(data, list(range(99,-1,-1)))
         self.assertRaises(TypeError, data.sort, "wrong type")
 
     def test_reverse_stability(self):
-        data = [(random.randrange(100), i) for i in xrange(200)]
+        data = [(random.randrange(100), i) for i in range(200)]
         copy1 = data[:]
         copy2 = data[:]
         data.sort(cmp=lambda x,y: cmp(x[0],y[0]), reverse=True)
@@ -281,7 +281,7 @@ def test_main(verbose=None):
     if verbose and hasattr(sys, "gettotalrefcount"):
         import gc
         counts = [None] * 5
-        for i in xrange(len(counts)):
+        for i in range(len(counts)):
             test_support.run_unittest(*test_classes)
             gc.collect()
             counts[i] = sys.gettotalrefcount()
index c3df2226d344d79b79f7254cac36bb6be5c9b556..29c555facf94b137f39c7c695c2f790de39a8f2e 100644 (file)
@@ -557,18 +557,18 @@ def test_unpack_from():
         vereq(s.unpack_from(data), ('abcd',))
         vereq(s.unpack_from(data, 2), ('cd01',))
         vereq(s.unpack_from(data, 4), ('0123',))
-        for i in xrange(6):
+        for i in range(6):
             vereq(s.unpack_from(data, i), (data[i:i+4],))
-        for i in xrange(6, len(test_string) + 1):
+        for i in range(6, len(test_string) + 1):
             simple_err(s.unpack_from, data, i)
     for cls in (str, buffer):
         data = cls(test_string)
         vereq(struct.unpack_from(fmt, data), ('abcd',))
         vereq(struct.unpack_from(fmt, data, 2), ('cd01',))
         vereq(struct.unpack_from(fmt, data, 4), ('0123',))
-        for i in xrange(6):
+        for i in range(6):
             vereq(struct.unpack_from(fmt, data, i), (data[i:i+4],))
-        for i in xrange(6, len(test_string) + 1):
+        for i in range(6, len(test_string) + 1):
             simple_err(struct.unpack_from, fmt, data, i)
 
 def test_pack_into():
index eb6d58104fcc3c61b64bcfb10f54d07ad0f75f45..12ebef95880dd8c78f28d16908c3d942e29b9eb3 100644 (file)
@@ -13,17 +13,17 @@ class StructSeqTest(unittest.TestCase):
 
         # Check that slicing works the same way; at one point, slicing t[i:j] with
         # 0 < i < j could produce NULLs in the result.
-        for i in xrange(-len(t), len(t)):
+        for i in range(-len(t), len(t)):
             self.assertEqual(t[i:], astuple[i:])
-            for j in xrange(-len(t), len(t)):
+            for j in range(-len(t), len(t)):
                 self.assertEqual(t[i:j], astuple[i:j])
 
-        for j in xrange(-len(t), len(t)):
+        for j in range(-len(t), len(t)):
             self.assertEqual(t[:j], astuple[:j])
 
         self.assertRaises(IndexError, t.__getitem__, -len(t)-1)
         self.assertRaises(IndexError, t.__getitem__, len(t))
-        for i in xrange(-len(t), len(t)-1):
+        for i in range(-len(t), len(t)-1):
             self.assertEqual(t[i], astuple[i])
 
     def test_repr(self):
@@ -33,13 +33,13 @@ class StructSeqTest(unittest.TestCase):
     def test_concat(self):
         t1 = time.gmtime()
         t2 = t1 + tuple(t1)
-        for i in xrange(len(t1)):
+        for i in range(len(t1)):
             self.assertEqual(t2[i], t2[i+len(t1)])
 
     def test_repeat(self):
         t1 = time.gmtime()
         t2 = 3 * t1
-        for i in xrange(len(t1)):
+        for i in range(len(t1)):
             self.assertEqual(t2[i], t2[i+len(t1)])
             self.assertEqual(t2[i], t2[i+2*len(t1)])
 
index 20f22ed07c1320e18651db791f0ae07fc21c83ab..f8b5bdf685ae067c01110224a5a43ee88f51d07e 100644 (file)
@@ -111,7 +111,7 @@ class test__RandomNameSequence(TC):
 
         dict = {}
         r = self.r
-        for i in xrange(TEST_FILES):
+        for i in range(TEST_FILES):
             s = next(r)
             self.nameCheck(s, '', '', '')
             self.failIf(s in dict)
@@ -245,7 +245,7 @@ class test__mkstemp_inner(TC):
 
     def test_basic_many(self):
         # _mkstemp_inner can create many files (stochastic)
-        extant = range(TEST_FILES)
+        extant = list(range(TEST_FILES))
         for i in extant:
             extant[i] = self.do_create(pre="aa")
 
@@ -457,7 +457,7 @@ class test_mkdtemp(TC):
 
     def test_basic_many(self):
         # mkdtemp can create many directories (stochastic)
-        extant = range(TEST_FILES)
+        extant = list(range(TEST_FILES))
         try:
             for i in extant:
                 extant[i] = self.do_create(pre="aa")
@@ -541,7 +541,7 @@ class test_mktemp(TC):
 
     def test_many(self):
         # mktemp can choose many usable file names (stochastic)
-        extant = range(TEST_FILES)
+        extant = list(range(TEST_FILES))
         for i in extant:
             extant[i] = self.do_create(pre="aa")
 
index b1778ddb5f4ea86f683c6452762017ed2bda23a8..05e6e9e3968b1a5f5d6d5d0bea0dfdf0788d76c3 100644 (file)
@@ -285,7 +285,7 @@ class RaisingTraceFuncTestCase(unittest.TestCase):
         handled OK."""
         self.raiseOnEvent = event
         try:
-            for i in xrange(sys.getrecursionlimit() + 1):
+            for i in range(sys.getrecursionlimit() + 1):
                 sys.settrace(self.trace)
                 try:
                     self.f()
index 96eb6e76eb8074e7d2e7894b80a9e381b6c1d081..00dcd393d71d894d62625569383b5aa1acae71b7 100644 (file)
@@ -39,7 +39,7 @@ class TupleTest(seq_tests.CommonTest):
         def f():
             for i in range(1000):
                 yield i
-        self.assertEqual(list(tuple(f())), range(1000))
+        self.assertEqual(list(tuple(f())), list(range(1000)))
 
     def test_hash(self):
         # See SF bug 942952:  Weakness in tuple hash
@@ -58,7 +58,7 @@ class TupleTest(seq_tests.CommonTest):
         #      is sorely suspect.
 
         N=50
-        base = range(N)
+        base = list(range(N))
         xp = [(i, j) for i in base for j in base]
         inps = base + [(i, j) for i in base for j in xp] + \
                      [(i, j) for i in xp for j in base] + xp + list(zip(base))
index 485e124947ca9e24c3827354372d5890cf6bd35e..d743656d97b17e36c7c4e904bbd6a2d136c64d7d 100644 (file)
@@ -61,7 +61,7 @@ class UnicodeNamesTest(unittest.TestCase):
     def test_ascii_letters(self):
         import unicodedata
 
-        for char in "".join(map(chr, xrange(ord("a"), ord("z")))):
+        for char in "".join(map(chr, range(ord("a"), ord("z")))):
             name = "LATIN SMALL LETTER %s" % char.upper()
             code = unicodedata.lookup(name)
             self.assertEqual(unicodedata.name(code), name)
@@ -95,7 +95,7 @@ class UnicodeNamesTest(unittest.TestCase):
     def test_bmp_characters(self):
         import unicodedata
         count = 0
-        for code in xrange(0x10000):
+        for code in range(0x10000):
             char = chr(code)
             name = unicodedata.name(char, None)
             if name is not None:
index 8f842f3601be25659a06824696941feaeb508544..055f3a4bb60d67e28338f1c355b0851e0c0cd614 100644 (file)
@@ -90,7 +90,7 @@ class UnicodeTest(
                 "\\xe2\\xe3\\xe4\\xe5\\xe6\\xe7\\xe8\\xe9\\xea\\xeb\\xec\\xed\\xee\\xef"
                 "\\xf0\\xf1\\xf2\\xf3\\xf4\\xf5\\xf6\\xf7\\xf8\\xf9\\xfa\\xfb\\xfc\\xfd"
                 "\\xfe\\xff'")
-            testrepr = repr(''.join(map(chr, xrange(256))))
+            testrepr = repr(''.join(map(chr, range(256))))
             self.assertEqual(testrepr, latin1repr)
             # Test repr works on wide unicode escapes without overflow.
             self.assertEqual(repr("\U00010000" * 39 + "\uffff" * 4096),
@@ -592,7 +592,7 @@ class UnicodeTest(
         self.assertEqual('hello'.encode('latin-1'), b'hello')
 
         # Roundtrip safety for BMP (just the first 1024 chars)
-        for c in xrange(1024):
+        for c in range(1024):
             u = chr(c)
             for encoding in ('utf-7', 'utf-8', 'utf-16', 'utf-16-le',
                              'utf-16-be', 'raw_unicode_escape',
@@ -600,13 +600,13 @@ class UnicodeTest(
                 self.assertEqual(str(u.encode(encoding),encoding), u)
 
         # Roundtrip safety for BMP (just the first 256 chars)
-        for c in xrange(256):
+        for c in range(256):
             u = chr(c)
             for encoding in ('latin-1',):
                 self.assertEqual(str(u.encode(encoding),encoding), u)
 
         # Roundtrip safety for BMP (just the first 128 chars)
-        for c in xrange(128):
+        for c in range(128):
             u = chr(c)
             for encoding in ('ascii',):
                 self.assertEqual(str(u.encode(encoding),encoding), u)
@@ -622,13 +622,14 @@ class UnicodeTest(
         # This excludes surrogates: in the full range, there would be
         # a surrogate pair (\udbff\udc00), which gets converted back
         # to a non-BMP character (\U0010fc00)
-        u = ''.join(map(chr, range(0,0xd800)+range(0xe000,0x10000)))
+        u = u''.join(map(chr, list(range(0,0xd800)) +
+                              list(range(0xe000,0x10000))))
         for encoding in ('utf-8',):
             self.assertEqual(str(u.encode(encoding),encoding), u)
 
     def test_codecs_charmap(self):
         # 0-127
-        s = bytes(xrange(128))
+        s = bytes(range(128))
         for encoding in (
             'cp037', 'cp1026',
             'cp437', 'cp500', 'cp737', 'cp775', 'cp850',
@@ -656,7 +657,7 @@ class UnicodeTest(
             self.assertEqual(str(s, encoding).encode(encoding), s)
 
         # 128-255
-        s = bytes(xrange(128, 256))
+        s = bytes(range(128, 256))
         for encoding in (
             'cp037', 'cp1026',
             'cp437', 'cp500', 'cp737', 'cp775', 'cp850',
index dc4be19157fad2ff68357d1c21204cd9b1129954..03ff05872690ba24c0f2702fbcbfa283c2e9e312 100644 (file)
@@ -193,7 +193,7 @@ class UnicodeMiscTest(UnicodeDatabaseTest):
         # i.e. if a character has a decimal value,
         # its numeric value should be the same.
         count = 0
-        for i in xrange(0x10000):
+        for i in range(0x10000):
             c = chr(i)
             dec = self.db.decimal(c, -1)
             if dec != -1:
@@ -206,7 +206,7 @@ class UnicodeMiscTest(UnicodeDatabaseTest):
         # i.e. if a character has a digit value,
         # its numeric value should be the same.
         count = 0
-        for i in xrange(0x10000):
+        for i in range(0x10000):
             c = chr(i)
             dec = self.db.digit(c, -1)
             if dec != -1:
index 8c724638e71ad2da03140f57428699f97578c935..039ed650cc5f51ec518d19321895ca8fd25e315f 100644 (file)
@@ -118,7 +118,7 @@ class UserDictTest(mapping_tests.TestHashMappingProtocol):
             self.assertEqual(u0.get(i), d0.get(i))
 
         # Test "in" iteration.
-        for i in xrange(20):
+        for i in range(20):
             u2[i] = str(i)
         ikeys = []
         for k in u2:
index e9fbd2de138ffa308b313c02ce25015521c06de6..fc9508f8ccc7b04c8bd23da85de741269fbea4fd 100644 (file)
@@ -14,7 +14,7 @@ class UserListTest(list_tests.CommonTest):
         for i in range(-3, 6):
             self.assertEqual(u[:i], l[:i])
             self.assertEqual(u[i:], l[i:])
-            for j in xrange(-3, 6):
+            for j in range(-3, 6):
                 self.assertEqual(u[i:j], l[i:j])
 
     def test_add_specials(self):
index 283806f0ea74d70f4ac4f820966bfc18f657b19e..5768a684606a79424919422ba7f3378c1c0f500f 100644 (file)
@@ -3,7 +3,7 @@ import os
 import unittest
 from test import test_support
 
-import warning_tests
+from test import warning_tests
 
 class TestModule(unittest.TestCase):
     def setUp(self):
index 19d4459a55b9432aa668e1a8b1040099b6e0b697..ae963f834200bb1071ec2756f132d6398bd2c9d4 100644 (file)
@@ -19,7 +19,7 @@ class BeepTest(unittest.TestCase):
         winsound.Beep(32767, 75)
 
     def test_increasingfrequency(self):
-        for i in xrange(100, 2000, 100):
+        for i in range(100, 2000, 100):
             winsound.Beep(i, 75)
 
 class MessageBeepTest(unittest.TestCase):
index 97f0cc9e4ccd2b0882ea3f484a68176b3ecf0e93..d0fb1e5df87549f57b6e65032430af99431915c9 100644 (file)
@@ -44,7 +44,7 @@ class XDRTest(unittest.TestCase):
         self.assertAlmostEqual(up.unpack_float(), 1.9)
         self.assertAlmostEqual(up.unpack_double(), 1.9)
         self.assertEqual(up.unpack_string(), s)
-        self.assertEqual(up.unpack_list(up.unpack_uint), range(5))
+        self.assertEqual(up.unpack_list(up.unpack_uint), list(range(5)))
         self.assertEqual(up.unpack_array(up.unpack_string), a)
         up.done()
         self.assertRaises(EOFError, up.unpack_uint)
index 52252505921038f0baebd71a85dceebb0377bfff..1e7f9dec65d8ac0cc1622f12f80d3f6365a2b76d 100644 (file)
@@ -9,56 +9,52 @@ warnings.filterwarnings("ignore", "integer argument expected",
 
 class XrangeTest(unittest.TestCase):
     def test_xrange(self):
-        self.assertEqual(list(xrange(3)), [0, 1, 2])
-        self.assertEqual(list(xrange(1, 5)), [1, 2, 3, 4])
-        self.assertEqual(list(xrange(0)), [])
-        self.assertEqual(list(xrange(-3)), [])
-        self.assertEqual(list(xrange(1, 10, 3)), [1, 4, 7])
-        self.assertEqual(list(xrange(5, -5, -3)), [5, 2, -1, -4])
+        self.assertEqual(list(range(3)), [0, 1, 2])
+        self.assertEqual(list(range(1, 5)), [1, 2, 3, 4])
+        self.assertEqual(list(range(0)), [])
+        self.assertEqual(list(range(-3)), [])
+        self.assertEqual(list(range(1, 10, 3)), [1, 4, 7])
+        self.assertEqual(list(range(5, -5, -3)), [5, 2, -1, -4])
 
         a = 10
         b = 100
         c = 50
 
-        self.assertEqual(list(xrange(a, a+2)), [a, a+1])
-        self.assertEqual(list(xrange(a+2, a, -1)), [a+2, a+1])
-        self.assertEqual(list(xrange(a+4, a, -2)), [a+4, a+2])
+        self.assertEqual(list(range(a, a+2)), [a, a+1])
+        self.assertEqual(list(range(a+2, a, -1)), [a+2, a+1])
+        self.assertEqual(list(range(a+4, a, -2)), [a+4, a+2])
 
-        seq = list(xrange(a, b, c))
+        seq = list(range(a, b, c))
         self.assert_(a in seq)
         self.assert_(b not in seq)
         self.assertEqual(len(seq), 2)
 
-        seq = list(xrange(b, a, -c))
+        seq = list(range(b, a, -c))
         self.assert_(b in seq)
         self.assert_(a not in seq)
         self.assertEqual(len(seq), 2)
 
-        seq = list(xrange(-a, -b, -c))
+        seq = list(range(-a, -b, -c))
         self.assert_(-a in seq)
         self.assert_(-b not in seq)
         self.assertEqual(len(seq), 2)
 
-        self.assertRaises(TypeError, xrange)
-        self.assertRaises(TypeError, xrange, 1, 2, 3, 4)
-        self.assertRaises(ValueError, xrange, 1, 2, 0)
+        self.assertRaises(TypeError, range)
+        self.assertRaises(TypeError, range, 1, 2, 3, 4)
+        self.assertRaises(ValueError, range, 1, 2, 0)
 
-        self.assertRaises(TypeError, xrange, 0.0, 2, 1)
-        self.assertRaises(TypeError, xrange, 1, 2.0, 1)
-        self.assertRaises(TypeError, xrange, 1, 2, 1.0)
-        self.assertRaises(TypeError, xrange, 1e100, 1e101, 1e101)
+        self.assertRaises(TypeError, range, 0.0, 2, 1)
+        self.assertRaises(TypeError, range, 1, 2.0, 1)
+        self.assertRaises(TypeError, range, 1, 2, 1.0)
+        self.assertRaises(TypeError, range, 1e100, 1e101, 1e101)
 
-        self.assertRaises(TypeError, xrange, 0, "spam")
-        self.assertRaises(TypeError, xrange, 0, 42, "spam")
+        self.assertRaises(TypeError, range, 0, "spam")
+        self.assertRaises(TypeError, range, 0, 42, "spam")
 
-        self.assertEqual(len(xrange(0, sys.maxint, sys.maxint-1)), 2)
+        self.assertEqual(len(range(0, sys.maxint, sys.maxint-1)), 2)
 
-        self.assertRaises(OverflowError, xrange, -sys.maxint, sys.maxint)
-        self.assertRaises(OverflowError, xrange, 0, 2*sys.maxint)
-
-        r = xrange(-sys.maxint, sys.maxint, 2)
+        r = range(-sys.maxint, sys.maxint, 2)
         self.assertEqual(len(r), sys.maxint)
-        self.assertRaises(OverflowError, xrange, -sys.maxint-1, sys.maxint, 2)
 
 def test_main():
     test.test_support.run_unittest(XrangeTest)
index a6500da17954dbae2806174be9de58853936f12f..172e230cac43493b0306599c5afc72043237fda9 100644 (file)
@@ -19,7 +19,7 @@ FIXEDTEST_SIZE = 10
 class TestsWithSourceFile(unittest.TestCase):
     def setUp(self):
         self.line_gen = ("Zipfile test line %d. random float: %f" % (i, random())
-                          for i in xrange(FIXEDTEST_SIZE))
+                          for i in range(FIXEDTEST_SIZE))
         self.data = '\n'.join(self.line_gen) + '\n'
 
         # Make a source file with some lines
@@ -562,7 +562,7 @@ class DecryptionTests(unittest.TestCase):
 class TestsWithRandomBinaryFiles(unittest.TestCase):
     def setUp(self):
         datacount = randint(16, 64)*1024 + randint(1, 1024)
-        self.data = ''.join((struct.pack('<f', random()*randint(-1000, 1000)) for i in xrange(datacount)))
+        self.data = ''.join((struct.pack('<f', random()*randint(-1000, 1000)) for i in range(datacount)))
 
         # Make a source file with some lines
         fp = open(TESTFN, "wb")
@@ -706,7 +706,7 @@ class TestsWithMultipleOpens(unittest.TestCase):
 
 class UniversalNewlineTests(unittest.TestCase):
     def setUp(self):
-        self.line_gen = ["Test of zipfile line %d." % i for i in xrange(FIXEDTEST_SIZE)]
+        self.line_gen = ["Test of zipfile line %d." % i for i in range(FIXEDTEST_SIZE)]
         self.seps = ('\r', '\r\n', '\n')
         self.arcdata, self.arcfiles = {}, {}
         for n, s in enumerate(self.seps):
index 445e23d52d2ef4e7e2b39f143b75652b1c2e110c..dedce4af6fe807a60008d2c446353c814fde0fd7 100644 (file)
@@ -33,9 +33,7 @@ _PRINT_WORKING_MSG_INTERVAL = 5 * 60
 class TestsWithSourceFile(unittest.TestCase):
     def setUp(self):
         # Create test data.
-        # xrange() is important here -- don't want to create immortal space
-        # for a million ints.
-        line_gen = ("Test of zipfile line %d." % i for i in xrange(1000000))
+        line_gen = ("Test of zipfile line %d." % i for i in range(1000000))
         self.data = '\n'.join(line_gen)
 
         # And write it to a file.
index c210bd22aa10e306bf4a8207f404fadf4c1abc9f..5b96d0e62f9ec5e1c7a452717a7e332bdf31580d 100644 (file)
@@ -14,7 +14,7 @@ def test_scaled_msg(scale, name):
 
     localCF = creatorFunc
     start = time.time()
-    for f in xrange(iterations):
+    for f in range(iterations):
         x = localCF(longStr).digest()
     end = time.time()
 
@@ -22,7 +22,7 @@ def test_scaled_msg(scale, name):
 
 def test_create():
     start = time.time()
-    for f in xrange(20000):
+    for f in range(20000):
         d = creatorFunc()
     end = time.time()
 
@@ -30,7 +30,7 @@ def test_create():
 
 def test_zero():
     start = time.time()
-    for f in xrange(20000):
+    for f in range(20000):
         x = creatorFunc().digest()
     end = time.time()
 
index de158f625d56275e53e1346ece3ee882cda53264..3c1c9390d7e228099ff0d41282408c92a1806830 100644 (file)
@@ -63,7 +63,6 @@ BuiltinMethodType = type([].append)     # Same as BuiltinFunctionType
 
 ModuleType = type(sys)
 FileType = file
-XRangeType = xrange
 
 try:
     raise TypeError
index fe1c74feccb49d57756fdb56dc1002c4cee515f4..cc5ee0701190b12f7fda612b949e2186eca54abb 100644 (file)
@@ -1151,7 +1151,7 @@ _hextochr.update(('%02X' % i, chr(i)) for i in range(256))
 def unquote(s):
     """unquote('abc%20def') -> 'abc def'."""
     res = s.split('%')
-    for i in xrange(1, len(res)):
+    for i in range(1, len(res)):
         item = res[i]
         try:
             res[i] = _hextochr[item[:2]] + item[2:]
index 7dc18402f1febbb85e8cc05a5fb65298822325c1..729cbc7c590c68ae5f3c109de210b8c4cbfcf978 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -16,11 +16,9 @@ TO DO
 
 - Weed really old/weird stuff from the library.
 
-- Unify range() and xrange().
-
 - Use io.py instead of C stdio everywhere.
 
-- Make strings all Unicode.
+- Make strings all Unicode (see branches/py3k-struni).
 
 - Get rid of various compatibility-related flags (e.g. division flags).
 
@@ -28,6 +26,9 @@ TO DO
 Core and Builtins
 -----------------
 
+- range() now returns an iterator rather than a list.  Floats are not allowed.
+  xrange() is no longer defined.
+
 - Merged from (2.6) trunk at r54987.
 
 - Patch #1660500: hide iteration variable in list comps, add set comps
@@ -171,7 +172,7 @@ Extension Modules
 Library
 -------
 
-- Remove functions in string module that are also string methods.
+- Remove functions in string and strop modules that are also string methods.
 
 - Remove obsolete modules: xmllib, stringold.
 
index c48bee0164e7a6050a05b74dff7bd4a558a332a3..f38935bbf137fe85a86f56d5476f4fd5d6db3da5 100644 (file)
 
 #include "Python.h"
 
+/* Support objects whose length is > PY_SSIZE_T_MAX.
+
+   This could be sped up for small PyLongs if they fit in an Py_ssize_t.
+   This only matters on Win64.  Though we could use PY_LONG_LONG which
+   would presumably help perf.
+*/
+
 typedef struct {
-       PyObject_HEAD
-       long    start;
-       long    step;
-       long    len;
+    PyObject_HEAD
+    PyObject *start;
+    PyObject *stop;
+    PyObject *step;
 } rangeobject;
 
-/* Return number of items in range/xrange (lo, hi, step).  step > 0
- * required.  Return a value < 0 if & only if the true value is too
- * large to fit in a signed long.
- */
-static long
-get_len_of_range(long lo, long hi, long step)
+/* Helper function for validating step.  Always returns a new reference or
+   NULL on error. 
+*/
+static PyObject *
+validate_step(PyObject *step)
 {
-       /* -------------------------------------------------------------
-       If lo >= hi, the range is empty.
-       Else if n values are in the range, the last one is
-       lo + (n-1)*step, which must be <= hi-1.  Rearranging,
-       n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
-       the proper value.  Since lo < hi in this case, hi-lo-1 >= 0, so
-       the RHS is non-negative and so truncation is the same as the
-       floor.  Letting M be the largest positive long, the worst case
-       for the RHS numerator is hi=M, lo=-M-1, and then
-       hi-lo-1 = M-(-M-1)-1 = 2*M.  Therefore unsigned long has enough
-       precision to compute the RHS exactly.
-       ---------------------------------------------------------------*/
-       long n = 0;
-       if (lo < hi) {
-               unsigned long uhi = (unsigned long)hi;
-               unsigned long ulo = (unsigned long)lo;
-               unsigned long diff = uhi - ulo - 1;
-               n = (long)(diff / (unsigned long)step + 1);
-       }
-       return n;
+    /* No step specified, use a step of 1. */
+    if (!step)
+        return PyInt_FromLong(1);
+
+    step = PyNumber_Index(step);
+    if (step) {
+        Py_ssize_t istep = PyNumber_AsSsize_t(step, NULL);
+        if (istep == -1 && PyErr_Occurred()) {
+            /* Ignore OverflowError, we know the value isn't 0. */
+            PyErr_Clear();
+        }
+        else if (istep == 0) {
+            PyErr_SetString(PyExc_ValueError,
+                            "range() arg 3 must not be zero");
+            Py_CLEAR(step);
+        }
+    }
+
+    return step;
 }
 
+/* XXX(nnorwitz): should we error check if the user passes any empty ranges?
+   range(-10)
+   range(0, -5)
+   range(0, 5, -1)
+*/
 static PyObject *
 range_new(PyTypeObject *type, PyObject *args, PyObject *kw)
 {
-       rangeobject *obj;
-       long ilow = 0, ihigh = 0, istep = 1;
-       long n;
-
-       if (!_PyArg_NoKeywords("xrange()", kw))
-               return NULL;
-
-       if (PyTuple_Size(args) <= 1) {
-               if (!PyArg_ParseTuple(args,
-                               "l;xrange() requires 1-3 int arguments",
-                               &ihigh))
-                       return NULL;
-       }
-       else {
-               if (!PyArg_ParseTuple(args,
-                               "ll|l;xrange() requires 1-3 int arguments",
-                               &ilow, &ihigh, &istep))
-                       return NULL;
-       }
-       if (istep == 0) {
-               PyErr_SetString(PyExc_ValueError, "xrange() arg 3 must not be zero");
-               return NULL;
-       }
-       if (istep > 0)
-               n = get_len_of_range(ilow, ihigh, istep);
-       else
-               n = get_len_of_range(ihigh, ilow, -istep);
-       if (n < 0) {
-               PyErr_SetString(PyExc_OverflowError,
-                               "xrange() result has too many items");
-               return NULL;
-       }
-
-       obj = PyObject_New(rangeobject, &PyRange_Type);
-       if (obj == NULL)
-               return NULL;
-       obj->start = ilow;
-       obj->len   = n;
-       obj->step  = istep;
-       return (PyObject *) obj;
+    rangeobject *obj = NULL;
+    PyObject *start = NULL, *stop = NULL, *step = NULL;
+
+    if (!_PyArg_NoKeywords("range()", kw))
+        return NULL;
+
+    if (PyTuple_Size(args) <= 1) {
+        if (!PyArg_UnpackTuple(args, "range", 1, 1, &stop))
+            goto Fail;
+        stop = PyNumber_Index(stop);
+        if (!stop)
+            goto Fail;
+        start = PyInt_FromLong(0);
+        step = PyInt_FromLong(1);
+        if (!start || !step)
+            goto Fail;
+    }
+    else {
+        if (!PyArg_UnpackTuple(args, "range", 2, 3,
+                               &start, &stop, &step))
+            goto Fail;
+
+        /* Convert borrowed refs to owned refs */
+        start = PyNumber_Index(start);
+        stop = PyNumber_Index(stop);
+        step = validate_step(step);
+        if (!start || !stop || !step)
+            goto Fail;
+    }
+
+    obj = PyObject_New(rangeobject, &PyRange_Type);
+    if (obj == NULL)
+        goto Fail;
+    obj->start = start;
+    obj->stop = stop;
+    obj->step = step;
+    return (PyObject *) obj;
+
+Fail:
+    Py_XDECREF(start);
+    Py_XDECREF(stop);
+    Py_XDECREF(step);
+    return NULL;
 }
 
 PyDoc_STRVAR(range_doc,
-"xrange([start,] stop[, step]) -> xrange object\n\
+"range([start,] stop[, step]) -> range object\n\
 \n\
-Like range(), but instead of returning a list, returns an object that\n\
-generates the numbers in the range on demand.  For looping, this is \n\
-slightly faster than range() and more memory efficient.");
+Returns an iterator that generates the numbers in the range on demand.");
 
-static PyObject *
-range_item(rangeobject *r, Py_ssize_t i)
+static void
+range_dealloc(rangeobject *r)
 {
-       if (i < 0 || i >= r->len) {
-               PyErr_SetString(PyExc_IndexError,
-                               "xrange object index out of range");
-               return NULL;
-       }
-       return PyInt_FromSsize_t(r->start + (i % r->len) * r->step);
+    Py_DECREF(r->start);
+    Py_DECREF(r->stop);
+    Py_DECREF(r->step);
+}
+
+/* Return number of items in range (lo, hi, step), when arguments are
+ * PyInt or PyLong objects.  step > 0 required.  Return a value < 0 if
+ * & only if the true value is too large to fit in a signed long.
+ * Arguments MUST return 1 with either PyInt_Check() or
+ * PyLong_Check().  Return -1 when there is an error.
+ */
+static PyObject*
+range_length_obj(rangeobject *r)
+{
+    /* -------------------------------------------------------------
+    Algorithm is equal to that of get_len_of_range(), but it operates
+    on PyObjects (which are assumed to be PyLong or PyInt objects).
+    ---------------------------------------------------------------*/
+    int cmp_result, cmp_call;
+    PyObject *lo, *hi;
+    PyObject *step = NULL;
+    PyObject *diff = NULL;
+    PyObject *one = NULL;
+    PyObject *tmp1 = NULL, *tmp2 = NULL, *result;
+                /* holds sub-expression evaluations */
+
+    PyObject *zero = PyLong_FromLong(0);
+    if (zero == NULL)
+        return NULL;
+    cmp_call = PyObject_Cmp(r->step, zero, &cmp_result);
+    Py_DECREF(zero);
+    if (cmp_call == -1)
+        return NULL;
+
+    assert(cmp_result != 0);
+    if (cmp_result > 0) {
+        lo = r->start;
+        hi = r->stop;
+        step = r->step;
+        Py_INCREF(step);
+    } else {
+        lo = r->stop;
+        hi = r->start;
+        step = PyNumber_Negative(r->step);
+        if (!step)
+            return NULL;
+    }
+
+    /* if (lo >= hi), return length of 0. */
+    if (PyObject_Compare(lo, hi) >= 0) {
+        Py_XDECREF(step);
+        return PyLong_FromLong(0);
+    }
+
+    if ((one = PyLong_FromLong(1L)) == NULL)
+        goto Fail;
+
+    if ((tmp1 = PyNumber_Subtract(hi, lo)) == NULL)
+        goto Fail;
+
+    if ((diff = PyNumber_Subtract(tmp1, one)) == NULL)
+        goto Fail;
+
+    if ((tmp2 = PyNumber_FloorDivide(diff, step)) == NULL)
+        goto Fail;
+
+    if ((result = PyNumber_Add(tmp2, one)) == NULL)
+        goto Fail;
+
+    Py_DECREF(tmp2);
+    Py_DECREF(diff);
+    Py_DECREF(step);
+    Py_DECREF(tmp1);
+    Py_DECREF(one);
+    return result;
+
+  Fail:
+    Py_XDECREF(tmp2);
+    Py_XDECREF(diff);
+    Py_XDECREF(step);
+    Py_XDECREF(tmp1);
+    Py_XDECREF(one);
+    return NULL;
 }
 
 static Py_ssize_t
 range_length(rangeobject *r)
 {
-       return (Py_ssize_t)(r->len);
+    PyObject *len = range_length_obj(r);
+    Py_ssize_t result = -1;
+    if (len) {
+        result = PyLong_AsSsize_t(len);
+        Py_DECREF(len);
+    }
+    return result;
+}
+
+/* range(...)[x] is necessary for:  seq[:] = range(...) */
+
+static PyObject *
+range_item(rangeobject *r, Py_ssize_t i)
+{
+    Py_ssize_t len = range_length(r);
+    PyObject *rem, *incr, *result;
+
+    /* XXX(nnorwitz): should negative indices be supported? */
+    /* XXX(nnorwitz): should support range[x] where x > PY_SSIZE_T_MAX? */
+    if (i < 0 || i >= len) {
+        if (!PyErr_Occurred())
+            PyErr_SetString(PyExc_IndexError,
+                            "xrange object index out of range");
+            return NULL;
+        }
+
+    /* XXX(nnorwitz): optimize for short ints. */
+    rem = PyLong_FromSsize_t(i % len);
+    if (!rem)
+        return NULL;
+    incr = PyNumber_Multiply(rem, r->step);
+    Py_DECREF(rem);
+    if (!incr)
+        return NULL;
+    result = PyNumber_Add(r->start, incr);
+    Py_DECREF(incr);
+    return result;
 }
 
 static PyObject *
 range_repr(rangeobject *r)
 {
-       PyObject *rtn;
-
-       if (r->start == 0 && r->step == 1)
-               rtn = PyString_FromFormat("xrange(%ld)",
-                                         r->start + r->len * r->step);
-
-       else if (r->step == 1)
-               rtn = PyString_FromFormat("xrange(%ld, %ld)",
-                                         r->start,
-                                         r->start + r->len * r->step);
-
-       else
-               rtn = PyString_FromFormat("xrange(%ld, %ld, %ld)",
-                                         r->start,
-                                         r->start + r->len * r->step,
-                                         r->step);
-       return rtn;
+    PyObject *start_str = NULL, *stop_str = NULL, *step_str = NULL;
+    PyObject *result = NULL;
+    Py_ssize_t istart, istep;
+
+    /* We always need the stop value. */
+    stop_str = PyObject_Str(r->stop);
+    if (!stop_str)
+        return NULL;
+
+    /* XXX(nnorwitz): should we use PyObject_Repr instead of str? */
+
+    /* Check for special case values for printing.  We don't always
+       need the start or step values.  We don't care about errors
+       (it means overflow), so clear the errors. */
+    istart = PyNumber_AsSsize_t(r->start, NULL);
+    if (istart != 0 || (istart == -1 && PyErr_Occurred())) {
+        PyErr_Clear();
+        start_str = PyObject_Str(r->start);
+    }
+
+    istep = PyNumber_AsSsize_t(r->step, NULL);
+    if (istep != 1 || (istep == -1 && PyErr_Occurred())) {
+        PyErr_Clear();
+        step_str = PyObject_Str(r->step);
+    }
+
+    if (istart == 0 && istep == 1)
+        result = PyString_FromFormat("range(%s)",
+                                     PyString_AS_STRING(stop_str));
+    else if (istep == 1) {
+        if (start_str)
+            result = PyString_FromFormat("range(%s, %s)",
+                                         PyString_AS_STRING(start_str),
+                                         PyString_AS_STRING(stop_str));
+    }
+    else if (start_str && step_str)
+        result = PyString_FromFormat("range(%s, %s, %s)",
+                                     PyString_AS_STRING(start_str),
+                                     PyString_AS_STRING(stop_str),
+                                     PyString_AS_STRING(step_str));
+    /* else result is NULL and an error should already be set. */
+
+    Py_XDECREF(start_str);
+    Py_XDECREF(stop_str);
+    Py_XDECREF(step_str);
+    return result;
 }
 
 static PySequenceMethods range_as_sequence = {
-       (lenfunc)range_length,  /* sq_length */
-       0,                      /* sq_concat */
-       0,                      /* sq_repeat */
-       (ssizeargfunc)range_item, /* sq_item */
-       0,                      /* sq_slice */
+    (lenfunc)range_length,     /* sq_length */
+    0,                 /* sq_concat */
+    0,                 /* sq_repeat */
+    (ssizeargfunc)range_item, /* sq_item */
+    0,                 /* sq_slice */
 };
 
 static PyObject * range_iter(PyObject *seq);
@@ -144,17 +297,18 @@ PyDoc_STRVAR(reverse_doc,
 "Returns a reverse iterator.");
 
 static PyMethodDef range_methods[] = {
-       {"__reversed__",        (PyCFunction)range_reverse, METH_NOARGS, reverse_doc},
-       {NULL,          NULL}           /* sentinel */
+    {"__reversed__",   (PyCFunction)range_reverse, METH_NOARGS,
+       reverse_doc},
+    {NULL,             NULL}           /* sentinel */
 };
 
 PyTypeObject PyRange_Type = {
        PyObject_HEAD_INIT(&PyType_Type)
        0,                      /* Number of items for varobject */
-       "xrange",               /* Name of this type */
+       "range",                /* Name of this type */
        sizeof(rangeobject),    /* Basic object size */
        0,                      /* Item size for varobject */
-       (destructor)PyObject_Del, /* tp_dealloc */
+       (destructor)range_dealloc, /* tp_dealloc */
        0,                      /* tp_print */
        0,                      /* tp_getattr */
        0,                      /* tp_setattr */
@@ -192,6 +346,11 @@ PyTypeObject PyRange_Type = {
 
 /*********************** Xrange Iterator **************************/
 
+/* There are 2 types of iterators, one for C longs, the other for
+   Python longs (ie, PyObjects).  This should make iteration fast
+   in the normal case, but possible for any numeric value.
+*/
+
 typedef struct {
        PyObject_HEAD
        long    index;
@@ -203,25 +362,42 @@ typedef struct {
 static PyObject *
 rangeiter_next(rangeiterobject *r)
 {
-       if (r->index < r->len)
-               return PyInt_FromLong(r->start + (r->index++) * r->step);
-       return NULL;
+    if (r->index < r->len)
+        return PyInt_FromLong(r->start + (r->index++) * r->step);
+    return NULL;
 }
 
 static PyObject *
 rangeiter_len(rangeiterobject *r)
 {
-       return PyInt_FromLong(r->len - r->index);
+    return PyInt_FromLong(r->len - r->index);
 }
 
-PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
+typedef struct {
+    PyObject_HEAD
+    PyObject *index;
+    PyObject *start;
+    PyObject *step;
+    PyObject *len;
+} longrangeiterobject;
+
+static PyObject *
+longrangeiter_len(longrangeiterobject *r, PyObject *no_args)
+{
+    return PyNumber_Subtract(r->len, r->index);
+}
+static PyObject *rangeiter_new(PyTypeObject *, PyObject *args, PyObject *kw);
+
+PyDoc_STRVAR(length_hint_doc,
+             "Private method returning an estimate of len(list(it)).");
 
 static PyMethodDef rangeiter_methods[] = {
-       {"__length_hint__", (PyCFunction)rangeiter_len, METH_NOARGS, length_hint_doc},
-       {NULL,          NULL}           /* sentinel */
+    {"__length_hint__", (PyCFunction)rangeiter_len, METH_NOARGS,
+       length_hint_doc},
+    {NULL,             NULL}           /* sentinel */
 };
 
-static PyTypeObject Pyrangeiter_Type = {
+PyTypeObject Pyrangeiter_Type = {
        PyObject_HEAD_INIT(&PyType_Type)
        0,                                      /* ob_size */
        "rangeiterator",                        /* tp_name */
@@ -252,50 +428,279 @@ static PyTypeObject Pyrangeiter_Type = {
        PyObject_SelfIter,                      /* tp_iter */
        (iternextfunc)rangeiter_next,           /* tp_iternext */
        rangeiter_methods,                      /* tp_methods */
+       0,                                      /* tp_members */
+       0,                                      /* tp_getset */
+       0,                                      /* tp_base */
+       0,                                      /* tp_dict */
+       0,                                      /* tp_descr_get */
+       0,                                      /* tp_descr_set */
+       0,                                      /* tp_dictoffset */
+       0,                                      /* tp_init */
+       0,                                      /* tp_alloc */
+       rangeiter_new,                          /* tp_new */
+};
+
+/* Return number of items in range/xrange (lo, hi, step).  step > 0
+ * required.  Return a value < 0 if & only if the true value is too
+ * large to fit in a signed long.
+ */
+static long
+get_len_of_range(long lo, long hi, long step)
+{
+    /* -------------------------------------------------------------
+    If lo >= hi, the range is empty.
+    Else if n values are in the range, the last one is
+    lo + (n-1)*step, which must be <= hi-1.  Rearranging,
+    n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
+    the proper value.  Since lo < hi in this case, hi-lo-1 >= 0, so
+    the RHS is non-negative and so truncation is the same as the
+    floor.  Letting M be the largest positive long, the worst case
+    for the RHS numerator is hi=M, lo=-M-1, and then
+    hi-lo-1 = M-(-M-1)-1 = 2*M.  Therefore unsigned long has enough
+    precision to compute the RHS exactly.
+    ---------------------------------------------------------------*/
+    long n = 0;
+    if (lo < hi) {
+        unsigned long uhi = (unsigned long)hi;
+        unsigned long ulo = (unsigned long)lo;
+        unsigned long diff = uhi - ulo - 1;
+        n = (long)(diff / (unsigned long)step + 1);
+    }
+    return n;
+}
+
+static PyObject *
+int_range_iter(long start, long stop, long step)
+{
+    rangeiterobject *it = PyObject_New(rangeiterobject, &Pyrangeiter_Type);
+    if (it == NULL)
+        return NULL;
+    it->start = start;
+    it->step = step;
+    if (step > 0)
+        it->len = get_len_of_range(start, stop, step);
+    else
+        it->len = get_len_of_range(stop, start, -step);
+    it->index = 0;
+    return (PyObject *)it;
+}
+
+static PyObject *
+rangeiter_new(PyTypeObject *type, PyObject *args, PyObject *kw)
+{
+    long start, stop, step;
+
+    if (!_PyArg_NoKeywords("rangeiter()", kw))
+        return NULL;
+
+    if (!PyArg_ParseTuple(args, "lll;rangeiter() requires 3 int arguments",
+                          &start, &stop, &step))
+        return NULL;
+
+    return int_range_iter(start, stop, step);
+}
+
+static PyMethodDef longrangeiter_methods[] = {
+    {"__length_hint__", (PyCFunction)longrangeiter_len, METH_NOARGS,
+       length_hint_doc},
+    {NULL,             NULL}           /* sentinel */
+};
+
+static void
+longrangeiter_dealloc(longrangeiterobject *r)
+{
+    Py_XDECREF(r->index);
+    Py_DECREF(r->start);
+    Py_DECREF(r->step);
+    Py_DECREF(r->len);
+}
+
+static PyObject *
+longrangeiter_next(longrangeiterobject *r)
+{
+    PyObject *one, *product, *new_index, *result;
+    if (PyObject_RichCompareBool(r->index, r->len, Py_LT) != 1)
+        return NULL;
+
+    one = PyLong_FromLong(1);
+    if (!one)
+        return NULL;
+
+    product = PyNumber_Multiply(r->index, r->step);
+    if (!product) {
+        Py_DECREF(one);
+        return NULL;
+    }
+
+    new_index = PyNumber_Add(r->index, one);
+    Py_DECREF(one);
+    if (!new_index) {
+        Py_DECREF(product);
+        return NULL;
+    }
+
+    result = PyNumber_Add(r->start, product);
+    Py_DECREF(product);
+    if (result) {
+        Py_DECREF(r->index);
+        r->index = new_index;
+    }
+
+    return result;
+}
+
+static PyTypeObject Pylongrangeiter_Type = {
+       PyObject_HEAD_INIT(&PyType_Type)
+       0,                                      /* ob_size */
+       "rangeiterator",                        /* tp_name */
+       sizeof(longrangeiterobject),            /* tp_basicsize */
+       0,                                      /* tp_itemsize */
+       /* methods */
+       (destructor)longrangeiter_dealloc,      /* tp_dealloc */
+       0,                                      /* tp_print */
+       0,                                      /* tp_getattr */
+       0,                                      /* tp_setattr */
+       0,                                      /* tp_compare */
+       0,                                      /* tp_repr */
+       0,                                      /* tp_as_number */
+       0,                                      /* tp_as_sequence */
+       0,                                      /* tp_as_mapping */
+       0,                                      /* tp_hash */
+       0,                                      /* tp_call */
+       0,                                      /* tp_str */
+       PyObject_GenericGetAttr,                /* tp_getattro */
+       0,                                      /* tp_setattro */
+       0,                                      /* tp_as_buffer */
+       Py_TPFLAGS_DEFAULT,                     /* tp_flags */
+       0,                                      /* tp_doc */
+       0,                                      /* tp_traverse */
+       0,                                      /* tp_clear */
+       0,                                      /* tp_richcompare */
+       0,                                      /* tp_weaklistoffset */
+       PyObject_SelfIter,                      /* tp_iter */
+       (iternextfunc)longrangeiter_next,       /* tp_iternext */
+       longrangeiter_methods,                  /* tp_methods */
        0,
 };
 
 static PyObject *
 range_iter(PyObject *seq)
 {
-       rangeiterobject *it;
-
-       if (!PyRange_Check(seq)) {
-               PyErr_BadInternalCall();
-               return NULL;
-       }
-       it = PyObject_New(rangeiterobject, &Pyrangeiter_Type);
-       if (it == NULL)
-               return NULL;
-       it->index = 0;
-       it->start = ((rangeobject *)seq)->start;
-       it->step = ((rangeobject *)seq)->step;
-       it->len = ((rangeobject *)seq)->len;
-       return (PyObject *)it;
+    rangeobject *r = (rangeobject *)seq;
+    longrangeiterobject *it;
+    PyObject *tmp, *len;
+
+    assert(PyRange_Check(seq));
+    if (_PyLong_FitsInLong(r->start) &&
+        _PyLong_FitsInLong(r->stop) &&
+        _PyLong_FitsInLong(r->step))
+        return int_range_iter(PyLong_AsLong(r->start),
+                      PyLong_AsLong(r->stop),
+                      PyLong_AsLong(r->step));
+
+    it = PyObject_New(longrangeiterobject, &Pylongrangeiter_Type);
+    if (it == NULL)
+        return NULL;
+    it->start = r->start;
+    /* Calculate length: (r->stop - r->start) / r->step */
+    tmp = PyNumber_Subtract(r->stop, r->start);
+    if (!tmp)
+        goto create_failure;
+    len = PyNumber_FloorDivide(tmp, r->step);
+    Py_DECREF(tmp);
+    if (!len)
+        goto create_failure;
+    it->len = len;
+    it->step = r->step;
+    it->index = PyLong_FromLong(0);
+    if (!it->index)
+        goto create_failure;
+
+    Py_INCREF(it->start);
+    Py_INCREF(it->step);
+    Py_INCREF(it->len);
+    return (PyObject *)it;
+
+create_failure:
+    PyObject_Del(it);
+    return NULL;
 }
 
 static PyObject *
 range_reverse(PyObject *seq)
 {
-       rangeiterobject *it;
-       long start, step, len;
-
-       if (!PyRange_Check(seq)) {
-               PyErr_BadInternalCall();
-               return NULL;
-       }
-       it = PyObject_New(rangeiterobject, &Pyrangeiter_Type);
-       if (it == NULL)
-               return NULL;
-
-       start = ((rangeobject *)seq)->start;
-       step = ((rangeobject *)seq)->step;
-       len = ((rangeobject *)seq)->len;
-
-       it->index = 0;
-       it->start = start + (len-1) * step;
-       it->step = -step;
-       it->len = len;
-
-       return (PyObject *)it;
+    rangeobject *range = (rangeobject*) seq;
+    longrangeiterobject *it;
+    PyObject *one, *sum, *diff, *len = NULL, *product;
+
+    /* XXX(nnorwitz): do the calc for the new start/stop first,
+        then if they fit, call the proper iter()?
+    */
+    assert(PyRange_Check(seq));
+    if (_PyLong_FitsInLong(range->start) &&
+        _PyLong_FitsInLong(range->stop) &&
+        _PyLong_FitsInLong(range->step)) {
+        long start = PyLong_AsLong(range->start);
+        long step = PyLong_AsLong(range->step);
+        long stop = PyLong_AsLong(range->stop);
+        /* XXX(nnorwitz): need to check for overflow and simplify. */
+        long len = get_len_of_range(start, stop, step);
+        long new_start = start + (len - 1) * step;
+        long new_stop = start;
+        if (step > 0)
+            new_stop -= 1;
+        else
+            new_stop += 1;
+        return int_range_iter(new_start, new_stop, -step);
+    }
+
+    it = PyObject_New(longrangeiterobject, &Pylongrangeiter_Type);
+    if (it == NULL)
+        return NULL;
+
+    /* start + (len - 1) * step */
+    len = range_length_obj(range);
+    if (!len)
+        goto create_failure;
+
+    one = PyLong_FromLong(1);
+    if (!one)
+        goto create_failure;
+
+    diff = PyNumber_Subtract(len, one);
+    Py_DECREF(one);
+    if (!diff)
+        goto create_failure;
+
+    product = PyNumber_Multiply(len, range->step);
+    if (!product)
+        goto create_failure;
+
+    sum = PyNumber_Add(range->start, product);
+    Py_DECREF(product);
+    it->start = sum;
+    if (!it->start)
+        goto create_failure;
+    it->step = PyNumber_Negative(range->step);
+    if (!it->step) {
+        Py_DECREF(it->start);
+        PyObject_Del(it);
+        return NULL;
+    }
+
+    /* Steal reference to len. */
+    it->len = len;
+
+    it->index = PyLong_FromLong(0);
+    if (!it->index) {
+        Py_DECREF(it);
+        return NULL;
+    }
+
+    return (PyObject *)it;
+
+create_failure:
+    Py_XDECREF(len);
+    PyObject_Del(it);
+    return NULL;
 }
index 08dc848968a8ca5170abc3d3ad34ab09532995cb..b1afd0fab1ac928e0fb9fffb48accfae2a82e5aa 100644 (file)
@@ -13,10 +13,15 @@ Changes for Python: Add support for module versions
 #__metaclass__ = type
 
 import os
+import sys
 import traceback
 
 import spark
 
+def output(string):
+    sys.stdout.write(string + "\n")
+
+
 class Token:
     # spark seems to dispatch in the parser based on a token's
     # type attribute
@@ -45,7 +50,7 @@ class String(Token):
         self.value = value
         self.lineno = lineno
 
-class ASDLSyntaxError:
+class ASDLSyntaxError(Exception):
 
     def __init__(self, lineno, token=None, msg=None):
         self.lineno = lineno
@@ -128,7 +133,7 @@ class ASDLParser(spark.GenericParser, object):
         "version ::= Id String"
         if version.value != "version":
             raise ASDLSyntaxError(version.lineno,
-                                msg="expected 'version', found %" % version)
+                                  msg="expected 'version', found %" % version)
         return V
 
     def p_definition_0(self, (definition,)):
@@ -306,9 +311,9 @@ class VisitorBase(object):
             return
         try:
             meth(object, *args)
-        except Exception, err:
-            print "Error visiting", repr(object)
-            print err
+        except Exception:
+            output("Error visiting", repr(object))
+            output(sys.exc_info()[1])
             traceback.print_exc()
             # XXX hack
             if hasattr(self, 'file'):
@@ -353,8 +358,8 @@ class Check(VisitorBase):
         if conflict is None:
             self.cons[key] = name
         else:
-            print "Redefinition of constructor %s" % key
-            print "Defined in %s and %s" % (conflict, name)
+            output("Redefinition of constructor %s" % key)
+            output("Defined in %s and %s" % (conflict, name))
             self.errors += 1
         for f in cons.fields:
             self.visit(f, key)
@@ -376,7 +381,7 @@ def check(mod):
         if t not in mod.types and not t in builtin_types:
             v.errors += 1
             uses = ", ".join(v.types[t])
-            print "Undefined type %s, used in %s" % (t, uses)
+            output("Undefined type %s, used in %s" % (t, uses))
 
     return not v.errors
 
@@ -388,10 +393,10 @@ def parse(file):
     tokens = scanner.tokenize(buf)
     try:
         return parser.parse(tokens)
-    except ASDLSyntaxError, err:
-        print err
+    except ASDLSyntaxError:
+        output(sys.exc_info()[1])
         lines = buf.split("\n")
-        print lines[err.lineno - 1] # lines starts at 0, files at 1
+        output(lines[err.lineno - 1]) # lines starts at 0, files at 1
 
 if __name__ == "__main__":
     import glob
@@ -404,12 +409,12 @@ if __name__ == "__main__":
         files = glob.glob(testdir + "/*.asdl")
 
     for file in files:
-        print file
+        output(file)
         mod = parse(file)
-        print "module", mod.name
-        print len(mod.dfns), "definitions"
+        output("module", mod.name)
+        output(len(mod.dfns), "definitions")
         if not check(mod):
-            print "Check failed"
+            output("Check failed")
         else:
             for dfn in mod.dfns:
-                print dfn.type
+                output(dfn.type)
index 325a2b6d2653c0902af48b3950eb926973422e9c..8c33e9dc5b1934576ae9e14581ac612c29ec7c02 100755 (executable)
@@ -718,7 +718,7 @@ class ChainOfVisitors:
             v.visit(object)
             v.emit("", 0)
 
-common_msg = "/* File automatically generated by %s. */\n"
+common_msg = "/* File automatically generated by %s. */\n\n"
 
 c_file_msg = """
 /*
@@ -728,6 +728,7 @@ c_file_msg = """
    The __version__ number is set to the revision number of the commit
    containing the grammar change.
 */
+
 """
 
 def main(srcfile):
@@ -741,25 +742,25 @@ def main(srcfile):
     if INC_DIR:
         p = "%s/%s-ast.h" % (INC_DIR, mod.name)
         f = open(p, "wb")
-        print >> f, auto_gen_msg
-        print >> f, '#include "asdl.h"\n'
+        f.write(auto_gen_msg)
+        f.write('#include "asdl.h"\n\n')
         c = ChainOfVisitors(TypeDefVisitor(f),
                             StructVisitor(f),
                             PrototypeVisitor(f),
                             )
         c.visit(mod)
-        print >>f, "PyObject* PyAST_mod2obj(mod_ty t);"
+        f.write("PyObject* PyAST_mod2obj(mod_ty t);\n")
         f.close()
 
     if SRC_DIR:
         p = os.path.join(SRC_DIR, str(mod.name) + "-ast.c")
         f = open(p, "wb")
-        print >> f, auto_gen_msg
-        print >> f, c_file_msg % parse_version(mod)
-        print >> f, '#include "Python.h"'
-        print >> f, '#include "%s-ast.h"' % mod.name
-        print >> f
-        print >>f, "static PyTypeObject* AST_type;"
+        f.write(auto_gen_msg)
+        f.write(c_file_msg % parse_version(mod))
+        f.write('#include "Python.h"\n')
+        f.write('#include "%s-ast.h"\n' % mod.name)
+        f.write('\n')
+        f.write("static PyTypeObject* AST_type;\n")
         v = ChainOfVisitors(
             PyTypesDeclareVisitor(f),
             PyTypesVisitor(f),
@@ -779,7 +780,7 @@ if __name__ == "__main__":
     SRC_DIR = ''
     opts, args = getopt.getopt(sys.argv[1:], "h:c:")
     if len(opts) != 1:
-        print "Must specify exactly one output file"
+        sys.stdout.write("Must specify exactly one output file\n")
         sys.exit(1)
     for o, v in opts:
         if o == '-h':
@@ -787,6 +788,6 @@ if __name__ == "__main__":
         if o == '-c':
             SRC_DIR = v
     if len(args) != 1:
-        print "Must specify single input file"
+        sys.stdout.write("Must specify single input file\n")
         sys.exit(1)
     main(args[0])
index 0b3292f5c7f22e70902c926040ecc9589ba8a404..7035077d53581a86cf8f812b88148ed6a4eebdaa 100644 (file)
@@ -23,7 +23,18 @@ __version__ = 'SPARK-0.7 (pre-alpha-5)'
 
 import re
 import sys
-import string
+
+# Compatability with older pythons.
+def output(string='', end='\n'):
+    sys.stdout.write(string + end)
+
+try:
+    sorted
+except NameError:
+    def sorted(seq):
+        seq2 = seq[:]
+        seq2.sort()
+        return seq2
 
 def _namelist(instance):
     namelist, namedict, classlist = [], {}, [instance.__class__]
@@ -57,10 +68,10 @@ class GenericScanner:
                 rv.append(self.makeRE(name))
 
         rv.append(self.makeRE('t_default'))
-        return string.join(rv, '|')
+        return '|'.join(rv)
 
     def error(self, s, pos):
-        print "Lexical error at position %s" % pos
+        output("Lexical error at position %s" % pos)
         raise SystemExit
 
     def tokenize(self, s):
@@ -79,7 +90,7 @@ class GenericScanner:
 
     def t_default(self, s):
         r'( . | \n )+'
-        print "Specification error: unmatched input"
+        output("Specification error: unmatched input")
         raise SystemExit
 
 #
@@ -172,7 +183,7 @@ class GenericParser:
 
     def addRule(self, doc, func, _preprocess=1):
         fn = func
-        rules = string.split(doc)
+        rules = doc.split()
 
         index = []
         for i in range(len(rules)):
@@ -296,7 +307,7 @@ class GenericParser:
         return None
 
     def error(self, token):
-        print "Syntax error at or near `%s' token" % token
+        output("Syntax error at or near `%s' token" % token)
         raise SystemExit
 
     def parse(self, tokens):
@@ -313,7 +324,7 @@ class GenericParser:
             self.states = { 0: self.makeState0() }
             self.makeState(0, self._BOF)
 
-        for i in xrange(len(tokens)):
+        for i in range(len(tokens)):
             sets.append([])
 
             if sets[i] == []:
@@ -419,8 +430,7 @@ class GenericParser:
         #  need to know the entire set of predicted nonterminals
         #  to do this without accidentally duplicating states.
         #
-        core = predicted.keys()
-        core.sort()
+        core = sorted(predicted.keys())
         tcore = tuple(core)
         if tcore in self.cores:
             self.edges[(k, None)] = self.cores[tcore]
@@ -605,7 +615,7 @@ class GenericParser:
             rule = self.ambiguity(self.newrules[nt])
         else:
             rule = self.newrules[nt][0]
-        #print rule
+        #output(rule)
 
         rhs = rule[1]
         attr = [None] * len(rhs)
@@ -624,7 +634,7 @@ class GenericParser:
         rule = choices[0]
         if len(choices) > 1:
             rule = self.ambiguity(choices)
-        #print rule
+        #output(rule)
 
         rhs = rule[1]
         attr = [None] * len(rhs)
@@ -826,15 +836,15 @@ class GenericASTMatcher(GenericParser):
 
 def _dump(tokens, sets, states):
     for i in range(len(sets)):
-        print 'set', i
+        output('set %d' % i)
         for item in sets[i]:
-            print '\t', item
+            output('\t', item)
             for (lhs, rhs), pos in states[item[0]].items:
-                print '\t\t', lhs, '::=',
-                print string.join(rhs[:pos]),
-                print '.',
-                print string.join(rhs[pos:])
+                output('\t\t', lhs, '::=', end='')
+                output(' '.join(rhs[:pos]), end='')
+                output('.', end='')
+                output(' '.join(rhs[pos:]))
         if i < len(tokens):
-            print
-            print 'token', str(tokens[i])
-            print
+            output()
+            output('token %s' % str(tokens[i]))
+            output()
index 093bb8114ff2f15daceffb41ffab464154f51078..46fbf777f4f14feb84629d6cb6f5181cbf16343d 100644 (file)
@@ -1593,302 +1593,6 @@ sep:  string inserted between values, default a space.\n\
 end:  string appended after the last value, default a newline.");
 
 
-/* Return number of items in range (lo, hi, step), when arguments are
- * PyInt or PyLong objects.  step > 0 required.  Return a value < 0 if
- * & only if the true value is too large to fit in a signed long.
- * Arguments MUST return 1 with either PyInt_Check() or
- * PyLong_Check().  Return -1 when there is an error.
- */
-static long
-get_len_of_range_longs(PyObject *lo, PyObject *hi, PyObject *step)
-{
-       /* -------------------------------------------------------------
-       Algorithm is equal to that of get_len_of_range(), but it operates
-       on PyObjects (which are assumed to be PyLong or PyInt objects).
-       ---------------------------------------------------------------*/
-       long n;
-       PyObject *diff = NULL;
-       PyObject *one = NULL;
-       PyObject *tmp1 = NULL, *tmp2 = NULL, *tmp3 = NULL;
-               /* holds sub-expression evaluations */
-
-       /* If (lo >= hi), return length of 0 (or error). */
-       n = PyObject_RichCompareBool(lo, hi, Py_LT);
-       if (n <= 0)
-               return n;
-
-       if ((one = PyLong_FromLong(1L)) == NULL)
-               goto Fail;
-
-       if ((tmp1 = PyNumber_Subtract(hi, lo)) == NULL)
-               goto Fail;
-
-       if ((diff = PyNumber_Subtract(tmp1, one)) == NULL)
-               goto Fail;
-
-       if ((tmp2 = PyNumber_FloorDivide(diff, step)) == NULL)
-               goto Fail;
-
-       if ((tmp3 = PyNumber_Add(tmp2, one)) == NULL)
-               goto Fail;
-
-       n = PyLong_AsLong(tmp3);
-       if (PyErr_Occurred()) {  /* Check for Overflow */
-               PyErr_Clear();
-               goto Fail;
-       }
-
-       Py_DECREF(tmp3);
-       Py_DECREF(tmp2);
-       Py_DECREF(diff);
-       Py_DECREF(tmp1);
-       Py_DECREF(one);
-       return n;
-
-  Fail:
-       Py_XDECREF(tmp3);
-       Py_XDECREF(tmp2);
-       Py_XDECREF(diff);
-       Py_XDECREF(tmp1);
-       Py_XDECREF(one);
-       return -1;
-}
-
-/* An extension of builtin_range() that handles the case when PyLong
- * arguments are given. */
-static PyObject *
-handle_range_longs(PyObject *self, PyObject *args)
-{
-       PyObject *ilow;
-       PyObject *ihigh = NULL;
-       PyObject *istep = NULL;
-
-       PyObject *curnum = NULL;
-       PyObject *v = NULL;
-       long bign;
-       int i, n;
-       int step_pos;
-
-       PyObject *zero = PyLong_FromLong(0);
-
-       if (zero == NULL)
-               return NULL;
-
-       if (!PyArg_UnpackTuple(args, "range", 1, 3, &ilow, &ihigh, &istep)) {
-               Py_DECREF(zero);
-               return NULL;
-       }
-
-       /* Figure out which way we were called, supply defaults, and be
-        * sure to incref everything so that the decrefs at the end
-        * are correct.
-        */
-       assert(ilow != NULL);
-       if (ihigh == NULL) {
-               /* only 1 arg -- it's the upper limit */
-               ihigh = ilow;
-               ilow = NULL;
-       }
-       assert(ihigh != NULL);
-       Py_INCREF(ihigh);
-
-       /* ihigh correct now; do ilow */
-       if (ilow == NULL)
-               ilow = zero;
-       Py_INCREF(ilow);
-
-       /* ilow and ihigh correct now; do istep */
-       if (istep == NULL) {
-               istep = PyLong_FromLong(1L);
-               if (istep == NULL)
-                       goto Fail;
-       }
-       else {
-               Py_INCREF(istep);
-       }
-
-       if (!PyInt_Check(ilow) && !PyLong_Check(ilow)) {
-               PyErr_Format(PyExc_TypeError,
-                            "range() integer start argument expected, got %s.",
-                            ilow->ob_type->tp_name);
-               goto Fail;
-       }
-
-       if (!PyInt_Check(ihigh) && !PyLong_Check(ihigh)) {
-               PyErr_Format(PyExc_TypeError,
-                            "range() integer end argument expected, got %s.",
-                            ihigh->ob_type->tp_name);
-               goto Fail;
-       }
-
-       if (!PyInt_Check(istep) && !PyLong_Check(istep)) {
-               PyErr_Format(PyExc_TypeError,
-                            "range() integer step argument expected, got %s.",
-                            istep->ob_type->tp_name);
-               goto Fail;
-       }
-
-       step_pos = PyObject_RichCompareBool(istep, zero, Py_GT);
-       if (step_pos < 0)
-               goto Fail;
-       if (step_pos)
-               bign = get_len_of_range_longs(ilow, ihigh, istep);
-       else {
-               int step_zero = PyObject_RichCompareBool(istep, zero, Py_EQ);
-               PyObject *neg_istep;
-               if (step_zero < 0)
-                       goto Fail;
-               if (step_zero) {
-                       PyErr_SetString(PyExc_ValueError,
-                               "range() step argument must not be zero");
-                       goto Fail;
-               }
-               neg_istep = PyNumber_Negative(istep);
-               if (neg_istep == NULL)
-                       goto Fail;
-               bign = get_len_of_range_longs(ihigh, ilow, neg_istep);
-               Py_DECREF(neg_istep);
-       }
-
-       n = (int)bign;
-       if (bign < 0 || (long)n != bign) {
-               PyErr_SetString(PyExc_OverflowError,
-                               "range() result has too many items");
-               goto Fail;
-       }
-
-       v = PyList_New(n);
-       if (v == NULL)
-               goto Fail;
-
-       curnum = ilow;
-       Py_INCREF(curnum);
-
-       for (i = 0; i < n; i++) {
-               PyObject *w = PyNumber_Long(curnum);
-               PyObject *tmp_num;
-               if (w == NULL)
-                       goto Fail;
-
-               PyList_SET_ITEM(v, i, w);
-
-               tmp_num = PyNumber_Add(curnum, istep);
-               if (tmp_num == NULL)
-                       goto Fail;
-
-               Py_DECREF(curnum);
-               curnum = tmp_num;
-       }
-       Py_DECREF(ilow);
-       Py_DECREF(ihigh);
-       Py_DECREF(istep);
-       Py_DECREF(zero);
-       Py_DECREF(curnum);
-       return v;
-
-  Fail:
-       Py_DECREF(ilow);
-       Py_DECREF(ihigh);
-       Py_XDECREF(istep);
-       Py_DECREF(zero);
-       Py_XDECREF(curnum);
-       Py_XDECREF(v);
-       return NULL;
-}
-
-/* Return number of items in range/xrange (lo, hi, step).  step > 0
- * required.  Return a value < 0 if & only if the true value is too
- * large to fit in a signed long.
- */
-static long
-get_len_of_range(long lo, long hi, long step)
-{
-       /* -------------------------------------------------------------
-       If lo >= hi, the range is empty.
-       Else if n values are in the range, the last one is
-       lo + (n-1)*step, which must be <= hi-1.  Rearranging,
-       n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
-       the proper value.  Since lo < hi in this case, hi-lo-1 >= 0, so
-       the RHS is non-negative and so truncation is the same as the
-       floor.  Letting M be the largest positive long, the worst case
-       for the RHS numerator is hi=M, lo=-M-1, and then
-       hi-lo-1 = M-(-M-1)-1 = 2*M.  Therefore unsigned long has enough
-       precision to compute the RHS exactly.
-       ---------------------------------------------------------------*/
-       long n = 0;
-       if (lo < hi) {
-               unsigned long uhi = (unsigned long)hi;
-               unsigned long ulo = (unsigned long)lo;
-               unsigned long diff = uhi - ulo - 1;
-               n = (long)(diff / (unsigned long)step + 1);
-       }
-       return n;
-}
-
-static PyObject *
-builtin_range(PyObject *self, PyObject *args)
-{
-       long ilow = 0, ihigh = 0, istep = 1;
-       long bign;
-       int i, n;
-
-       PyObject *v;
-
-       if (PyTuple_Size(args) <= 1) {
-               if (!PyArg_ParseTuple(args,
-                               "l;range() requires 1-3 int arguments",
-                               &ihigh)) {
-                       PyErr_Clear();
-                       return handle_range_longs(self, args);
-               }
-       }
-       else {
-               if (!PyArg_ParseTuple(args,
-                               "ll|l;range() requires 1-3 int arguments",
-                               &ilow, &ihigh, &istep)) {
-                       PyErr_Clear();
-                       return handle_range_longs(self, args);
-               }
-       }
-       if (istep == 0) {
-               PyErr_SetString(PyExc_ValueError,
-                               "range() step argument must not be zero");
-               return NULL;
-       }
-       if (istep > 0)
-               bign = get_len_of_range(ilow, ihigh, istep);
-       else
-               bign = get_len_of_range(ihigh, ilow, -istep);
-       n = (int)bign;
-       if (bign < 0 || (long)n != bign) {
-               PyErr_SetString(PyExc_OverflowError,
-                               "range() result has too many items");
-               return NULL;
-       }
-       v = PyList_New(n);
-       if (v == NULL)
-               return NULL;
-       for (i = 0; i < n; i++) {
-               PyObject *w = PyInt_FromLong(ilow);
-               if (w == NULL) {
-                       Py_DECREF(v);
-                       return NULL;
-               }
-               PyList_SET_ITEM(v, i, w);
-               ilow += istep;
-       }
-       return v;
-}
-
-PyDoc_STRVAR(range_doc,
-"range([start,] stop[, step]) -> list of integers\n\
-\n\
-Return a list containing an arithmetic progression of integers.\n\
-range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\n\
-When step is given, it specifies the increment (or decrement).\n\
-For example, range(4) returns [0, 1, 2, 3].  The end point is omitted!\n\
-These are exactly the valid indices for a list of 4 elements.");
-
 static PyObject *
 builtin_input(PyObject *self, PyObject *args)
 {
@@ -2277,7 +1981,6 @@ static PyMethodDef builtin_methods[] = {
        {"ord",         builtin_ord,        METH_O, ord_doc},
        {"pow",         builtin_pow,        METH_VARARGS, pow_doc},
        {"print",       (PyCFunction)builtin_print,      METH_VARARGS | METH_KEYWORDS, print_doc},
-       {"range",       builtin_range,      METH_VARARGS, range_doc},
        {"reload",      builtin_reload,     METH_O, reload_doc},
        {"repr",        builtin_repr,       METH_O, repr_doc},
        {"round",       (PyCFunction)builtin_round,      METH_VARARGS | METH_KEYWORDS, round_doc},
@@ -2344,6 +2047,7 @@ _PyBuiltin_Init(void)
        SETBUILTIN("int",               &PyLong_Type);
        SETBUILTIN("list",              &PyList_Type);
        SETBUILTIN("object",            &PyBaseObject_Type);
+       SETBUILTIN("range",             &PyRange_Type);
        SETBUILTIN("reversed",          &PyReversed_Type);
        SETBUILTIN("set",               &PySet_Type);
        SETBUILTIN("slice",             &PySlice_Type);
@@ -2353,7 +2057,6 @@ _PyBuiltin_Init(void)
        SETBUILTIN("super",             &PySuper_Type);
        SETBUILTIN("tuple",             &PyTuple_Type);
        SETBUILTIN("type",              &PyType_Type);
-       SETBUILTIN("xrange",            &PyRange_Type);
        SETBUILTIN("unicode",           &PyUnicode_Type);
        debug = PyBool_FromLong(Py_OptimizeFlag == 0);
        if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
index 6923b4b496e5a2ef66eea0fc27cc18700dac2d66..6ef2f205f228ecd45f5be6b6858b504b3a64629c 100644 (file)
@@ -8,7 +8,7 @@ class SimpleIntegerArithmetic(Test):
 
     def test(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             a = 2
             b = 3
@@ -152,7 +152,7 @@ class SimpleIntegerArithmetic(Test):
 
     def calibrate(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 class SimpleFloatArithmetic(Test):
@@ -163,7 +163,7 @@ class SimpleFloatArithmetic(Test):
 
     def test(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             a = 2.1
             b = 3.3332
@@ -307,7 +307,7 @@ class SimpleFloatArithmetic(Test):
 
     def calibrate(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 class SimpleIntFloatArithmetic(Test):
@@ -318,7 +318,7 @@ class SimpleIntFloatArithmetic(Test):
 
     def test(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             a = 2
             b = 3
@@ -462,7 +462,7 @@ class SimpleIntFloatArithmetic(Test):
 
     def calibrate(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 
@@ -474,7 +474,7 @@ class SimpleLongArithmetic(Test):
 
     def test(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             a = 2220001L
             b = 100001L
@@ -618,7 +618,7 @@ class SimpleLongArithmetic(Test):
 
     def calibrate(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 class SimpleComplexArithmetic(Test):
@@ -629,7 +629,7 @@ class SimpleComplexArithmetic(Test):
 
     def test(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             a = 2 + 3j
             b = 2.5 + 4.5j
@@ -773,5 +773,5 @@ class SimpleComplexArithmetic(Test):
 
     def calibrate(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
index 72ccd0eaae7739e3ec319511cfbe1182243baabd..cfe07152639b565f3f1f97f47663ded6788c6e96 100644 (file)
@@ -24,7 +24,7 @@ class PythonFunctionCalls(Test):
             return d,e,f
 
         # do calls
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             f()
             f1(i)
@@ -104,7 +104,7 @@ class PythonFunctionCalls(Test):
             return d,e,f
 
         # do calls
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 ###
@@ -124,7 +124,7 @@ class BuiltinFunctionCalls(Test):
         f3 = range
 
         # do calls
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             f0()
             f0()
@@ -225,7 +225,7 @@ class BuiltinFunctionCalls(Test):
         f3 = range
 
         # do calls
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 ###
@@ -261,7 +261,7 @@ class PythonMethodCalls(Test):
 
         o = c()
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             o.f()
             o.f()
@@ -367,7 +367,7 @@ class PythonMethodCalls(Test):
 
         o = c
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 ###
@@ -388,7 +388,7 @@ class Recursion(Test):
                 return f(x-1)
             return 1
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             f(10)
             f(10)
             f(10)
@@ -405,7 +405,7 @@ class Recursion(Test):
                 return f(x-1)
             return 1
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 
index 51054619651df43563486d7466e4debb14227c1d..7273b87192ee24a7ca2b8d076f082472f6d74de6 100644 (file)
@@ -9,7 +9,7 @@ class IfThenElse(Test):
     def test(self):
 
         a,b,c = 1,2,3
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             if a == 1:
                 if b == 2:
@@ -464,7 +464,7 @@ class IfThenElse(Test):
     def calibrate(self):
 
         a,b,c = 1,2,3
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 class NestedForLoops(Test):
@@ -478,7 +478,7 @@ class NestedForLoops(Test):
         l1 = range(1000)
         l2 = range(10)
         l3 = range(5)
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             for i in l1:
                 for j in l2:
                     for k in l3:
@@ -489,7 +489,7 @@ class NestedForLoops(Test):
         l1 = range(1000)
         l2 = range(10)
         l3 = range(5)
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 class ForLoops(Test):
@@ -501,7 +501,7 @@ class ForLoops(Test):
     def test(self):
 
         l1 = range(100)
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             for i in l1:
                 pass
             for i in l1:
@@ -560,5 +560,5 @@ class ForLoops(Test):
     def calibrate(self):
 
         l1 = range(1000)
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
index cb039b04e1f2a2b017a06d998f9840eb97c91836..575758bfc2d12d7b8c7f523277ec54d5b2daf195 100644 (file)
@@ -8,7 +8,7 @@ class DictCreation(Test):
 
     def test(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             d1 = {}
             d2 = {}
@@ -72,7 +72,7 @@ class DictCreation(Test):
 
     def calibrate(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 class DictWithStringKeys(Test):
@@ -85,7 +85,7 @@ class DictWithStringKeys(Test):
 
         d = {}
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             d['abc'] = 1
             d['def'] = 2
@@ -161,7 +161,7 @@ class DictWithStringKeys(Test):
 
         d = {}
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 class DictWithFloatKeys(Test):
@@ -174,7 +174,7 @@ class DictWithFloatKeys(Test):
 
         d = {}
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             d[1.234] = 1
             d[2.345] = 2
@@ -250,7 +250,7 @@ class DictWithFloatKeys(Test):
 
         d = {}
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 class DictWithIntegerKeys(Test):
@@ -263,7 +263,7 @@ class DictWithIntegerKeys(Test):
 
         d = {}
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             d[1] = 1
             d[2] = 2
@@ -339,7 +339,7 @@ class DictWithIntegerKeys(Test):
 
         d = {}
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 class SimpleDictManipulation(Test):
@@ -353,7 +353,7 @@ class SimpleDictManipulation(Test):
         d = {}
         has_key = lambda key: key in d
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             d[0] = 3
             d[1] = 4
@@ -500,5 +500,5 @@ class SimpleDictManipulation(Test):
         d = {}
         has_key = lambda key: key in d
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
index ab0fa0a22fc8bd9a0b143bd06fc7873b2e516078..c321b2ef47065fc26a2dae5f50d5f3944f1148f5 100644 (file)
@@ -10,7 +10,7 @@ class TryRaiseExcept(Test):
 
         error = ValueError
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             try:
                 raise error
             except:
@@ -48,7 +48,7 @@ class TryRaiseExcept(Test):
 
         error = ValueError
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 
@@ -60,7 +60,7 @@ class TryExcept(Test):
 
     def test(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             try:
                 pass
             except:
@@ -687,7 +687,7 @@ class TryExcept(Test):
 
     def calibrate(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 ### Test to make Fredrik happy...
index afc728b94ffcea6614a738e5be11f0e6ae6096b7..399ba17f2a91d45ee7b7c724004b3fedf54e11bf 100644 (file)
@@ -12,7 +12,7 @@ class SecondImport(Test):
 
     def test(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             import os
             import os
             import os
@@ -45,7 +45,7 @@ class SecondImport(Test):
 
     def calibrate(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 
@@ -57,7 +57,7 @@ class SecondPackageImport(Test):
 
     def test(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             import package
             import package
             import package
@@ -90,7 +90,7 @@ class SecondPackageImport(Test):
 
     def calibrate(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 class SecondSubmoduleImport(Test):
@@ -101,7 +101,7 @@ class SecondSubmoduleImport(Test):
 
     def test(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             import package.submodule
             import package.submodule
             import package.submodule
@@ -134,5 +134,5 @@ class SecondSubmoduleImport(Test):
 
     def calibrate(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
index 1dfc82f326b791e55931ae721c9a0a62a71a64db..0a09b7bd7608be445330c03f07b127b62e428236 100644 (file)
@@ -26,7 +26,7 @@ class CreateInstances(Test):
                 self.e = b
                 self.f = c
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             o = c()
             o1 = c()
             o2 = c()
@@ -62,5 +62,5 @@ class CreateInstances(Test):
                 self.e = b
                 self.f = c
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
index 67760db35034907a42bf1c3ac5b10405f6924e9d..aedd35270943dcbc36f13d052afc17b3e6e37a9f 100644 (file)
@@ -11,7 +11,7 @@ class SimpleListManipulation(Test):
         l = []
         append = l.append
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             append(2)
             append(3)
@@ -127,7 +127,7 @@ class SimpleListManipulation(Test):
         l = []
         append = l.append
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 class ListSlicing(Test):
@@ -141,7 +141,7 @@ class ListSlicing(Test):
         n = range(100)
         r = range(25)
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             l = n[:]
 
@@ -160,7 +160,7 @@ class ListSlicing(Test):
         n = range(100)
         r = range(25)
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             for j in r:
                 pass
 
@@ -172,7 +172,7 @@ class SmallLists(Test):
 
     def test(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             l = []
 
@@ -291,5 +291,5 @@ class SmallLists(Test):
 
     def calibrate(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
index e454a002b50b6cbc4a041fc9f3a7933e9e57f6b7..5bf9e7622dc3ba0349225a86ae06909c4b62c563 100644 (file)
@@ -11,7 +11,7 @@ class SpecialClassAttribute(Test):
         class c:
             pass
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             c.__a = 2
             c.__b = 3
@@ -178,7 +178,7 @@ class SpecialClassAttribute(Test):
         class c:
             pass
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 class NormalClassAttribute(Test):
@@ -192,7 +192,7 @@ class NormalClassAttribute(Test):
         class c:
             pass
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             c.a = 2
             c.b = 3
@@ -364,7 +364,7 @@ class NormalClassAttribute(Test):
         class c:
             pass
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 class SpecialInstanceAttribute(Test):
@@ -379,7 +379,7 @@ class SpecialInstanceAttribute(Test):
             pass
         o = c()
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             o.__a__ = 2
             o.__b__ = 3
@@ -552,7 +552,7 @@ class SpecialInstanceAttribute(Test):
             pass
         o = c()
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 class NormalInstanceAttribute(Test):
@@ -567,7 +567,7 @@ class NormalInstanceAttribute(Test):
             pass
         o = c()
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             o.a = 2
             o.b = 3
@@ -740,7 +740,7 @@ class NormalInstanceAttribute(Test):
             pass
         o = c()
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 class BuiltinMethodLookup(Test):
@@ -754,7 +754,7 @@ class BuiltinMethodLookup(Test):
         l = []
         d = {}
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             l.append
             l.append
@@ -941,5 +941,5 @@ class BuiltinMethodLookup(Test):
         l = []
         d = {}
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
index 258beba617f1d1569d4a77df85f7778a25c0679f..9506da484c9c5f48ef79044c1ddaf296246ef93e 100644 (file)
@@ -35,7 +35,7 @@ class CreateNewInstances(Test):
                 self.e = b
                 self.f = c
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             o = c()
             o1 = c()
             o2 = c()
@@ -71,5 +71,5 @@ class CreateNewInstances(Test):
                 self.e = b
                 self.f = c
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
index 10c8940a2101e35807c2280c4250a84fee68ebda..b0a11f4ce5f58256fdca360d13f280351d89f433 100644 (file)
@@ -8,7 +8,7 @@ class CompareIntegers(Test):
 
     def test(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             2 < 3
             2 > 3
@@ -192,7 +192,7 @@ class CompareIntegers(Test):
 
     def calibrate(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 
@@ -204,7 +204,7 @@ class CompareFloats(Test):
 
     def test(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             2.1 < 3.31
             2.1 > 3.31
@@ -388,7 +388,7 @@ class CompareFloats(Test):
 
     def calibrate(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 
@@ -400,7 +400,7 @@ class CompareFloatsIntegers(Test):
 
     def test(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             2.1 < 4
             2.1 > 4
@@ -584,7 +584,7 @@ class CompareFloatsIntegers(Test):
 
     def calibrate(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 
@@ -596,7 +596,7 @@ class CompareLongs(Test):
 
     def test(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             1234567890L < 3456789012345L
             1234567890L > 3456789012345L
@@ -780,5 +780,5 @@ class CompareLongs(Test):
 
     def calibrate(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
index dc49df1dae1dd76cc572f5ac3bae089fbb9e3683..2668d6bf4512ec654f8e298f316d9ed4aa572af8 100644 (file)
@@ -14,7 +14,7 @@ class ConcatStrings(Test):
         s = join(map(str,range(100)))
         t = join(map(str,range(1,101)))
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             t + s
             t + s
             t + s
@@ -80,7 +80,7 @@ class ConcatStrings(Test):
         s = join(map(str,range(100)))
         t = join(map(str,range(1,101)))
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 
@@ -96,7 +96,7 @@ class CompareStrings(Test):
         s = join(map(str,range(10)))
         t = join(map(str,range(10))) + "abc"
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             t < s
             t > s
             t == s
@@ -162,7 +162,7 @@ class CompareStrings(Test):
         s = join(map(str,range(10)))
         t = join(map(str,range(10))) + "abc"
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 
@@ -178,7 +178,7 @@ class CompareInternedStrings(Test):
         s = sys.intern(join(map(str,range(10))))
         t = s
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             t == s
             t == s
             t >= s
@@ -244,7 +244,7 @@ class CompareInternedStrings(Test):
         s = sys.intern(join(map(str,range(10))))
         t = s
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 
@@ -256,7 +256,7 @@ class CreateStringsWithConcat(Test):
 
     def test(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             s = 'om'
             s = s + 'xbx'
             s = s + 'xcx'
@@ -319,7 +319,7 @@ class CreateStringsWithConcat(Test):
 
     def calibrate(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 
@@ -333,7 +333,7 @@ class StringSlicing(Test):
 
         s = join(map(str,range(100)))
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             s[50:]
             s[:25]
@@ -379,7 +379,7 @@ class StringSlicing(Test):
 
         s = join(map(str,range(100)))
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 ### String methods
@@ -399,7 +399,7 @@ if hasattr('', 'lower'):
             u = join(map(chr,range(100)),'')
             v = join(map(chr,range(256)),'')
 
-            for i in xrange(self.rounds):
+            for i in range(self.rounds):
 
                 s.lower()
                 s.lower()
@@ -456,7 +456,7 @@ if hasattr('', 'lower'):
             u = join(map(chr,range(100)),'')
             v = join(map(chr,range(256)),'')
 
-            for i in xrange(self.rounds):
+            for i in range(self.rounds):
                 pass
 
     class StringPredicates(Test):
@@ -470,7 +470,7 @@ if hasattr('', 'lower'):
             data = ('abc', '123', '   ', '\xe4\xf6\xfc', '\xdf'*10)
             len_data = len(data)
 
-            for i in xrange(self.rounds):
+            for i in range(self.rounds):
                 s = data[i % len_data]
 
                 s.isalnum()
@@ -559,5 +559,5 @@ if hasattr('', 'lower'):
             data = ('abc', '123', '   ', '\xe4\xf6\xfc', '\xdf'*10)
             len_data = len(data)
 
-            for i in xrange(self.rounds):
+            for i in range(self.rounds):
                 s = data[i % len_data]
index 8e4698959707bf9bc4e00b1ab8c3d04dbc6799b5..d93802c187aba902d059a44c1b433a53e1b0928c 100644 (file)
@@ -11,7 +11,7 @@ class TupleSlicing(Test):
         r = range(25)
         t = tuple(range(100))
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             for j in r:
 
@@ -260,7 +260,7 @@ class TupleSlicing(Test):
         r = range(25)
         t = tuple(range(100))
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             for j in r:
                 pass
 
@@ -272,7 +272,7 @@ class SmallTuples(Test):
 
     def test(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             t = (1,2,3,4,5,6)
 
@@ -356,5 +356,5 @@ class SmallTuples(Test):
 
     def calibrate(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
index 153a91e66d7384ab76b5bb871df9790afaffe9c3..21e24c09b735274e853a48ca1e64b74d6f4b6714 100644 (file)
@@ -18,7 +18,7 @@ class ConcatUnicode(Test):
         s = unicode(join(map(str,range(100))))
         t = unicode(join(map(str,range(1,101))))
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             t + s
             t + s
             t + s
@@ -84,7 +84,7 @@ class ConcatUnicode(Test):
         s = unicode(join(map(str,range(100))))
         t = unicode(join(map(str,range(1,101))))
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 
@@ -100,7 +100,7 @@ class CompareUnicode(Test):
         s = unicode(join(map(str,range(10))))
         t = unicode(join(map(str,range(10))) + "abc")
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             t < s
             t > s
             t == s
@@ -166,7 +166,7 @@ class CompareUnicode(Test):
         s = unicode(join(map(str,range(10))))
         t = unicode(join(map(str,range(10))) + "abc")
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 
@@ -178,7 +178,7 @@ class CreateUnicodeWithConcat(Test):
 
     def test(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             s = u'om'
             s = s + u'xbx'
             s = s + u'xcx'
@@ -241,7 +241,7 @@ class CreateUnicodeWithConcat(Test):
 
     def calibrate(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 
@@ -255,7 +255,7 @@ class UnicodeSlicing(Test):
 
         s = unicode(join(map(str,range(100))))
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             s[50:]
             s[:25]
@@ -301,7 +301,7 @@ class UnicodeSlicing(Test):
 
         s = unicode(join(map(str,range(100))))
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 ### String methods
@@ -319,7 +319,7 @@ class UnicodeMappings(Test):
         u = join(map(unichr,range(500)),'')
         v = join(map(unichr,range(1000)),'')
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             s.lower()
             s.lower()
@@ -376,7 +376,7 @@ class UnicodeMappings(Test):
         u = join(map(unichr,range(500)),'')
         v = join(map(unichr,range(1000)),'')
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 class UnicodePredicates(Test):
@@ -390,7 +390,7 @@ class UnicodePredicates(Test):
         data = (u'abc', u'123', u'   ', u'\u1234\u2345\u3456', u'\uFFFF'*10)
         len_data = len(data)
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             s = data[i % len_data]
 
             s.isalnum()
@@ -448,7 +448,7 @@ class UnicodePredicates(Test):
         data = (u'abc', u'123', u'   ', u'\u1234\u2345\u3456', u'\uFFFF'*10)
         len_data = len(data)
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             s = data[i % len_data]
 
 try:
@@ -475,7 +475,7 @@ else:
             mirrored = unicodedata.mirrored
             combining = unicodedata.combining
 
-            for i in xrange(self.rounds):
+            for i in range(self.rounds):
 
                 c = data[i % len_data]
 
@@ -537,6 +537,6 @@ else:
             mirrored = unicodedata.mirrored
             combining = unicodedata.combining
 
-            for i in xrange(self.rounds):
+            for i in range(self.rounds):
 
                 c = data[i % len_data]
index bf07e36dd2834676b9aee5c1d1f6d58f8a6de3f8..5478c288a21260d34b4fe360f2e98783c892d731 100644 (file)
@@ -181,7 +181,7 @@ def processtime():
 
 def some_workload():
     x = 0L
-    for i in xrange(10000000L):
+    for i in range(10000000L):
         x = x + 1L
 
 def test_workload():
index dade0717d2686eef7560fde38be0372ae0e1e92e..13a5f9b70b9a5f7b74c3671f45526ec1c36c90f0 100644 (file)
@@ -193,7 +193,7 @@ class Reindenter:
                     want = have2want.get(have, -1)
                     if want < 0:
                         # Then it probably belongs to the next real stmt.
-                        for j in xrange(i+1, len(stats)-1):
+                        for j in range(i+1, len(stats)-1):
                             jline, jlevel = stats[j]
                             if jlevel >= 0:
                                 if have == getlspace(lines[jline]):
@@ -203,7 +203,7 @@ class Reindenter:
                                            # comment like this one,
                         # in which case we should shift it like its base
                         # line got shifted.
-                        for j in xrange(i-1, -1, -1):
+                        for j in range(i-1, -1, -1):
                             jline, jlevel = stats[j]
                             if jlevel >= 0:
                                 want = have + getlspace(after[jline-1]) - \
index 9de69048eb6105ff6430c1869ee810d01cb94904..2a85e8405c5bd046ae0a7b1f0af827908bec0e22 100644 (file)
@@ -935,7 +935,7 @@ def splitbins(t, trace=0):
     if __debug__:
         # exhaustively verify that the decomposition is correct
         mask = ~((~0) << shift) # i.e., low-bit mask of shift bits
-        for i in xrange(len(t)):
+        for i in range(len(t)):
             assert t[i] == t2[(t1[i >> shift] << shift) + (i & mask)]
     return best
 
index 2525f9e5e66c1dff0d2ec5de9b3b41e06e7fcd30..5be44c95e6625e14b7a68354953769e441d469a4 100644 (file)
@@ -37,7 +37,7 @@ def compact_set(l):
         tuple.append((prev,prev+span+1))
     else:
         single.append(prev)
-    tuple = " + ".join(["range(%d,%d)" % t for t in tuple])
+    tuple = " + ".join(["list(range(%d,%d))" % t for t in tuple])
     if not single:
         return "set(%s)" % tuple
     if not tuple: