From f0dbceb1812c5df14215b380323eee0b61e8348e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=87a=C4=9F=C4=B1l=20Ulu=C5=9Fahin?= Date: Tue, 18 Sep 2018 20:23:59 +0100 Subject: [PATCH 1/4] First attempt to port the repo from python2 to python3 --- .../benchmarks/bm_call_method.py | 2 +- .../benchmarks/bm_call_simple.py | 2 +- grumpy-runtime-src/benchmarks/call.py | 12 +- .../benchmarks/comprehension.py | 12 +- grumpy-runtime-src/benchmarks/concurrent.py | 6 +- grumpy-runtime-src/benchmarks/dict.py | 14 +- grumpy-runtime-src/benchmarks/generator.py | 4 +- grumpy-runtime-src/benchmarks/list.py | 8 +- grumpy-runtime-src/benchmarks/loop.py | 6 +- grumpy-runtime-src/benchmarks/tuple.py | 6 +- grumpy-runtime-src/lib/cStringIO.py | 326 +++++++++++++++++- grumpy-runtime-src/lib/itertools.py | 22 +- grumpy-runtime-src/lib/itertools_test.py | 32 +- grumpy-runtime-src/lib/os/path_test.py | 14 +- grumpy-runtime-src/lib/sys_test.py | 2 +- grumpy-runtime-src/lib/tempfile_test.py | 2 +- grumpy-runtime-src/lib/weetest.py | 10 +- grumpy-runtime-src/lib/weetest_test.py | 2 +- grumpy-runtime-src/testing/builtin_test.py | 98 +++--- .../testing/comprehension_test.py | 2 +- grumpy-runtime-src/testing/generator_test.py | 6 +- grumpy-runtime-src/testing/global_test.py | 2 +- grumpy-runtime-src/testing/import_test.py | 2 +- grumpy-runtime-src/testing/list_test.py | 2 +- grumpy-runtime-src/testing/op_test.py | 4 +- grumpy-runtime-src/testing/pow_test.py | 24 +- grumpy-runtime-src/testing/str_test.py | 22 +- .../third_party/pypy/_collections.py | 8 +- grumpy-runtime-src/third_party/pypy/_csv.py | 14 +- .../third_party/pypy/_functools.py | 2 +- .../third_party/pypy/_sha256.py | 6 +- .../third_party/pypy/_sha512.py | 6 +- grumpy-runtime-src/third_party/pypy/_sre.py | 36 +- .../third_party/pypy/binascii.py | 114 +++--- .../third_party/pypy/datetime.py | 20 +- .../third_party/stdlib/StringIO.py | 32 +- .../third_party/stdlib/UserDict.py | 46 +-- .../third_party/stdlib/UserString.py | 32 +- .../third_party/stdlib/_abcoll.py | 32 +- grumpy-runtime-src/third_party/stdlib/abc.py | 8 +- .../third_party/stdlib/argparse.py | 6 +- .../third_party/stdlib/base64.py | 18 +- .../third_party/stdlib/collections.py | 30 +- .../third_party/stdlib/contextlib.py | 8 +- .../third_party/stdlib/copy_reg.py | 6 +- grumpy-runtime-src/third_party/stdlib/csv.py | 50 +-- .../third_party/stdlib/difflib.py | 33 +- .../third_party/stdlib/fpformat.py | 6 +- .../third_party/stdlib/genericpath.py | 2 +- .../third_party/stdlib/getopt.py | 2 +- grumpy-runtime-src/third_party/stdlib/glob.py | 6 +- .../third_party/stdlib/heapq.py | 22 +- .../third_party/stdlib/linecache.py | 2 +- .../third_party/stdlib/mimetools.py | 10 +- .../third_party/stdlib/optparse.py | 56 +-- .../third_party/stdlib/pprint.py | 8 +- .../third_party/stdlib/quopri.py | 18 +- .../third_party/stdlib/random.py | 26 +- grumpy-runtime-src/third_party/stdlib/re.py | 14 +- .../third_party/stdlib/re_tests.py | 2 +- grumpy-runtime-src/third_party/stdlib/repr.py | 12 +- .../third_party/stdlib/rfc822.py | 40 +-- .../third_party/stdlib/sched.py | 2 +- .../third_party/stdlib/sre_compile.py | 24 +- .../third_party/stdlib/sre_parse.py | 150 ++++---- .../third_party/stdlib/string.py | 15 +- .../third_party/stdlib/textwrap.py | 6 +- .../third_party/stdlib/threading.py | 46 +-- .../third_party/stdlib/traceback.py | 2 +- .../third_party/stdlib/types.py | 2 +- .../third_party/stdlib/unittest_case.py | 26 +- .../third_party/stdlib/unittest_loader.py | 6 +- .../third_party/stdlib/unittest_result.py | 2 +- .../third_party/stdlib/unittest_runner.py | 6 +- .../third_party/stdlib/unittest_suite.py | 6 +- .../third_party/stdlib/unittest_util.py | 10 +- .../third_party/stdlib/urlparse.py | 18 +- grumpy-runtime-src/third_party/stdlib/uu.py | 22 +- .../third_party/stdlib/warnings.py | 14 +- grumpy-tools-src/grumpy_tools/benchcmp.py | 6 +- grumpy-tools-src/grumpy_tools/cli.py | 2 +- .../grumpy_tools/compiler/util.py | 8 +- grumpy-tools-src/grumpy_tools/coverparse.py | 6 +- grumpy-tools-src/grumpy_tools/diffrange.py | 6 +- grumpy-tools-src/grumpy_tools/genmake.py | 2 +- grumpy-tools-src/grumpy_tools/grumpc.py | 4 +- grumpy-tools-src/grumpy_tools/grumprun.py | 2 +- grumpy-tools-src/grumpy_tools/pydeps.py | 4 +- .../tests/dummymodule/__init__.py | 2 +- .../dummymodule/dummysubmodule1/__init__.py | 4 +- .../tests/import_havingpkgmain.py | 2 +- 91 files changed, 1047 insertions(+), 735 deletions(-) mode change 120000 => 100644 grumpy-runtime-src/lib/cStringIO.py diff --git a/grumpy-runtime-src/benchmarks/bm_call_method.py b/grumpy-runtime-src/benchmarks/bm_call_method.py index 5216f533..b7d4d3e9 100644 --- a/grumpy-runtime-src/benchmarks/bm_call_method.py +++ b/grumpy-runtime-src/benchmarks/bm_call_method.py @@ -110,7 +110,7 @@ def qux(self): def BenchmarkCallMethod(b): f = Foo() - for _ in xrange(b.N): + for _ in range(b.N): # 20 calls f.foo(1, 2, 3, 4) f.foo(1, 2, 3, 4) diff --git a/grumpy-runtime-src/benchmarks/bm_call_simple.py b/grumpy-runtime-src/benchmarks/bm_call_simple.py index d1ee4f6d..1a68f9e8 100644 --- a/grumpy-runtime-src/benchmarks/bm_call_simple.py +++ b/grumpy-runtime-src/benchmarks/bm_call_simple.py @@ -111,7 +111,7 @@ def qux(): def BenchmarkCallSimple(b): - for _ in xrange(b.N): + for _ in range(b.N): # 20 calls foo(1, 2, 3, 4) foo(1, 2, 3, 4) diff --git a/grumpy-runtime-src/benchmarks/call.py b/grumpy-runtime-src/benchmarks/call.py index 2a7d383a..eb128e67 100644 --- a/grumpy-runtime-src/benchmarks/call.py +++ b/grumpy-runtime-src/benchmarks/call.py @@ -22,42 +22,42 @@ def BenchmarkCallNoArgs(b): def Foo(): pass - for _ in xrange(b.N): + for _ in range(b.N): Foo() def BenchmarkCallPositionalArgs(b): def Foo(a, b, c): pass - for _ in xrange(b.N): + for _ in range(b.N): Foo(1, 2, 3) def BenchmarkCallKeywords(b): def Foo(a, b, c): pass - for _ in xrange(b.N): + for _ in range(b.N): Foo(a=1, b=2, c=3) def BenchmarkCallDefaults(b): def Foo(a=1, b=2, c=3): pass - for _ in xrange(b.N): + for _ in range(b.N): Foo() def BenchmarkCallVarArgs(b): def Foo(*args): pass - for _ in xrange(b.N): + for _ in range(b.N): Foo(1, 2, 3) def BenchmarkCallKwargs(b): def Foo(**kwargs): pass - for _ in xrange(b.N): + for _ in range(b.N): Foo(a=1, b=2, c=3) diff --git a/grumpy-runtime-src/benchmarks/comprehension.py b/grumpy-runtime-src/benchmarks/comprehension.py index 79469db1..7eee77f5 100644 --- a/grumpy-runtime-src/benchmarks/comprehension.py +++ b/grumpy-runtime-src/benchmarks/comprehension.py @@ -21,23 +21,23 @@ def BenchmarkGeneratorExpCreate(b): l = [] - for _ in xrange(b.N): + for _ in range(b.N): (x for x in l) # pylint: disable=pointless-statement def BenchmarkGeneratorExpIterate(b): - for _ in (x for x in xrange(b.N)): + for _ in (x for x in range(b.N)): pass def BenchmarkListCompCreate(b): - for _ in xrange(b.N): - [x for x in xrange(1000)] # pylint: disable=expression-not-assigned + for _ in range(b.N): + [x for x in range(1000)] # pylint: disable=expression-not-assigned def BenchmarkDictCompCreate(b): - for _ in xrange(b.N): - {x: x for x in xrange(1000)} # pylint: disable=expression-not-assigned + for _ in range(b.N): + {x: x for x in range(1000)} # pylint: disable=expression-not-assigned if __name__ == '__main__': diff --git a/grumpy-runtime-src/benchmarks/concurrent.py b/grumpy-runtime-src/benchmarks/concurrent.py index ce48a553..36e203d0 100644 --- a/grumpy-runtime-src/benchmarks/concurrent.py +++ b/grumpy-runtime-src/benchmarks/concurrent.py @@ -41,10 +41,10 @@ def Benchmark(b): # pylint: disable=missing-docstring e = threading.Event() def Target(): e.wait() - for _ in xrange(b.N / p): + for _ in range(b.N / p): work_func(*args) threads = [] - for _ in xrange(p): + for _ in range(p): t = threading.Thread(target=Target) t.start() threads.append(t) @@ -56,7 +56,7 @@ def Target(): def _RegisterBenchmarks(): - for p in xrange(1, 13): + for p in range(1, 13): for work_func, arg in _WORKLOADS: name = 'Benchmark' + work_func.__name__ if p > 1: diff --git a/grumpy-runtime-src/benchmarks/dict.py b/grumpy-runtime-src/benchmarks/dict.py index ae08b8b3..7f8b944d 100644 --- a/grumpy-runtime-src/benchmarks/dict.py +++ b/grumpy-runtime-src/benchmarks/dict.py @@ -20,43 +20,43 @@ def BenchmarkDictCreate(b): - for _ in xrange(b.N): + for _ in range(b.N): d = {'one': 1, 'two': 2, 'three': 3} def BenchmarkDictCreateFunc(b): - for _ in xrange(b.N): + for _ in range(b.N): d = dict(one=1, two=2, three=3) def BenchmarkDictGetItem(b): d = {42: 123} - for _ in xrange(b.N): + for _ in range(b.N): d[42] def BenchmarkDictStringOnlyGetItem(b): d = {'foo': 123} - for _ in xrange(b.N): + for _ in range(b.N): d['foo'] def BenchmarkDictSetItem(b): d = {} - for _ in xrange(b.N): + for _ in range(b.N): d[42] = 123 def BenchmarkDictStringOnlySetItem(b): d = {} - for _ in xrange(b.N): + for _ in range(b.N): d['foo'] = 123 def BenchmarkHashStrCached(b): """Hashes the same value repeatedly to exercise any hash caching logic.""" h = hash # Prevent builtins lookup each iteration. - for _ in xrange(b.N): + for _ in range(b.N): h('foobarfoobarfoobar') diff --git a/grumpy-runtime-src/benchmarks/generator.py b/grumpy-runtime-src/benchmarks/generator.py index d49e838c..13d2d77f 100644 --- a/grumpy-runtime-src/benchmarks/generator.py +++ b/grumpy-runtime-src/benchmarks/generator.py @@ -19,7 +19,7 @@ def BenchmarkGeneratorIterate(b): def Gen(n): - for i in xrange(n): + for i in range(n): yield i for _ in Gen(b.N): pass @@ -28,7 +28,7 @@ def Gen(n): def BenchmarkGeneratorCreate(b): def Gen(): yield 1 - for _ in xrange(b.N): + for _ in range(b.N): Gen() diff --git a/grumpy-runtime-src/benchmarks/list.py b/grumpy-runtime-src/benchmarks/list.py index 2c4a5b9c..9562377a 100644 --- a/grumpy-runtime-src/benchmarks/list.py +++ b/grumpy-runtime-src/benchmarks/list.py @@ -21,19 +21,19 @@ def BenchmarkListGetItem(b): l = [1, 3, 9] - for _ in xrange(b.N): + for _ in range(b.N): l[2] def BenchmarkListContains3(b): l = [1, 3, 9] - for _ in xrange(b.N): + for _ in range(b.N): 9 in l def BenchmarkListContains10(b): - l = range(10) - for _ in xrange(b.N): + l = list(range(10)) + for _ in range(b.N): 9 in l diff --git a/grumpy-runtime-src/benchmarks/loop.py b/grumpy-runtime-src/benchmarks/loop.py index 7bd91240..e3e5869f 100644 --- a/grumpy-runtime-src/benchmarks/loop.py +++ b/grumpy-runtime-src/benchmarks/loop.py @@ -18,7 +18,7 @@ def BenchmarkForXRange(b): - for _ in xrange(b.N): + for _ in range(b.N): pass @@ -29,10 +29,10 @@ def BenchmarkWhileCounter(b): def BenchmarkWhileXRange(b): - i = iter(xrange(b.N)) + i = iter(range(b.N)) try: while True: - i.next() + next(i) except StopIteration: pass diff --git a/grumpy-runtime-src/benchmarks/tuple.py b/grumpy-runtime-src/benchmarks/tuple.py index b6a44945..0da93bd6 100644 --- a/grumpy-runtime-src/benchmarks/tuple.py +++ b/grumpy-runtime-src/benchmarks/tuple.py @@ -21,19 +21,19 @@ def BenchmarkTupleGetItem(b): l = (1, 3, 9) - for _ in xrange(b.N): + for _ in range(b.N): l[2] def BenchmarkTupleContains3(b): t = (1, 3, 9) - for _ in xrange(b.N): + for _ in range(b.N): 9 in t def BenchmarkTupleContains10(b): t = tuple(range(10)) - for _ in xrange(b.N): + for _ in range(b.N): 9 in t diff --git a/grumpy-runtime-src/lib/cStringIO.py b/grumpy-runtime-src/lib/cStringIO.py deleted file mode 120000 index 7b1e326c..00000000 --- a/grumpy-runtime-src/lib/cStringIO.py +++ /dev/null @@ -1 +0,0 @@ -../third_party/stdlib/StringIO.py \ No newline at end of file diff --git a/grumpy-runtime-src/lib/cStringIO.py b/grumpy-runtime-src/lib/cStringIO.py new file mode 100644 index 00000000..72dcb200 --- /dev/null +++ b/grumpy-runtime-src/lib/cStringIO.py @@ -0,0 +1,325 @@ +r"""File-like objects that read from or write to a string buffer. + +This implements (nearly) all stdio methods. + +f = StringIO() # ready for writing +f = StringIO(buf) # ready for reading +f.close() # explicitly release resources held +flag = f.isatty() # always false +pos = f.tell() # get current position +f.seek(pos) # set current position +f.seek(pos, mode) # mode 0: absolute; 1: relative; 2: relative to EOF +buf = f.read() # read until EOF +buf = f.read(n) # read up to n bytes +buf = f.readline() # read until end of line ('\n') or EOF +list = f.readlines()# list of f.readline() results until EOF +f.truncate([size]) # truncate file at to at most size (default: current pos) +f.write(buf) # write at current position +f.writelines(list) # for line in list: f.write(line) +f.getvalue() # return whole file's contents as a string + +Notes: +- Using a real file is often faster (but less convenient). +- There's also a much faster implementation in C, called cStringIO, but + it's not subclassable. +- fileno() is left unimplemented so that code which uses it triggers + an exception early. +- Seeking far beyond EOF and then writing will insert real null + bytes that occupy space in the buffer. +- There's a simple test set (see end of this file). +""" +try: + import errno + EINVAL = errno.EINVAL +except ImportError: + EINVAL = 22 + +__all__ = ["StringIO"] + +def _complain_ifclosed(closed): + if closed: + raise ValueError("I/O operation on closed file") + +class StringIO(object): + """class StringIO([buffer]) + + When a StringIO object is created, it can be initialized to an existing + string by passing the string to the constructor. If no string is given, + the StringIO will start empty. + + The StringIO object can accept either Unicode or 8-bit strings, but + mixing the two may take some care. If both are used, 8-bit strings that + cannot be interpreted as 7-bit ASCII (that use the 8th bit) will cause + a UnicodeError to be raised when getvalue() is called. + """ + def __init__(self, buf = ''): + # Force self.buf to be a string or unicode + if not isinstance(buf, str): + buf = str(buf) + self.buf = buf + self.len = len(buf) + self.buflist = [] + self.pos = 0 + self.closed = False + self.softspace = 0 + + def __iter__(self): + return self + + def __next__(self): + """A file object is its own iterator, for example iter(f) returns f + (unless f is closed). When a file is used as an iterator, typically + in a for loop (for example, for line in f: print line), the next() + method is called repeatedly. This method returns the next input line, + or raises StopIteration when EOF is hit. + """ + _complain_ifclosed(self.closed) + r = self.readline() + if not r: + raise StopIteration + return r + + def close(self): + """Free the memory buffer. + """ + if not self.closed: + self.closed = True + del self.buf, self.pos + + def isatty(self): + """Returns False because StringIO objects are not connected to a + tty-like device. + """ + _complain_ifclosed(self.closed) + return False + + def seek(self, pos, mode = 0): + """Set the file's current position. + + The mode argument is optional and defaults to 0 (absolute file + positioning); other values are 1 (seek relative to the current + position) and 2 (seek relative to the file's end). + + There is no return value. + """ + _complain_ifclosed(self.closed) + if self.buflist: + self.buf += ''.join(self.buflist) + self.buflist = [] + if mode == 1: + pos += self.pos + elif mode == 2: + pos += self.len + self.pos = max(0, pos) + + def tell(self): + """Return the file's current position.""" + _complain_ifclosed(self.closed) + return self.pos + + def read(self, n = -1): + """Read at most size bytes from the file + (less if the read hits EOF before obtaining size bytes). + + If the size argument is negative or omitted, read all data until EOF + is reached. The bytes are returned as a string object. An empty + string is returned when EOF is encountered immediately. + """ + _complain_ifclosed(self.closed) + if self.buflist: + self.buf += ''.join(self.buflist) + self.buflist = [] + if n is None or n < 0: + newpos = self.len + else: + newpos = min(self.pos+n, self.len) + r = self.buf[self.pos:newpos] + self.pos = newpos + return r + + def readline(self, length=None): + r"""Read one entire line from the file. + + A trailing newline character is kept in the string (but may be absent + when a file ends with an incomplete line). If the size argument is + present and non-negative, it is a maximum byte count (including the + trailing newline) and an incomplete line may be returned. + + An empty string is returned only when EOF is encountered immediately. + + Note: Unlike stdio's fgets(), the returned string contains null + characters ('\0') if they occurred in the input. + """ + _complain_ifclosed(self.closed) + if self.buflist: + self.buf += ''.join(self.buflist) + self.buflist = [] + i = self.buf.find('\n', self.pos) + if i < 0: + newpos = self.len + else: + newpos = i+1 + if length is not None and length >= 0: + if self.pos + length < newpos: + newpos = self.pos + length + r = self.buf[self.pos:newpos] + self.pos = newpos + return r + + def readlines(self, sizehint = 0): + """Read until EOF using readline() and return a list containing the + lines thus read. + + If the optional sizehint argument is present, instead of reading up + to EOF, whole lines totalling approximately sizehint bytes (or more + to accommodate a final whole line). + """ + total = 0 + lines = [] + line = self.readline() + while line: + lines.append(line) + total += len(line) + if 0 < sizehint <= total: + break + line = self.readline() + return lines + + def truncate(self, size=None): + """Truncate the file's size. + + If the optional size argument is present, the file is truncated to + (at most) that size. The size defaults to the current position. + The current file position is not changed unless the position + is beyond the new file size. + + If the specified size exceeds the file's current size, the + file remains unchanged. + """ + _complain_ifclosed(self.closed) + if size is None: + size = self.pos + elif size < 0: + raise IOError(EINVAL, "Negative size not allowed") + elif size < self.pos: + self.pos = size + self.buf = self.getvalue()[:size] + self.len = size + + def write(self, s): + """Write a string to the file. + + There is no return value. + """ + _complain_ifclosed(self.closed) + if not s: return + # Force s to be a string or unicode + if not isinstance(s, str): + s = str(s) + spos = self.pos + slen = self.len + if spos == slen: + self.buflist.append(s) + self.len = self.pos = spos + len(s) + return + if spos > slen: + self.buflist.append('\0'*(spos - slen)) + slen = spos + newpos = spos + len(s) + if spos < slen: + if self.buflist: + self.buf += ''.join(self.buflist) + self.buflist = [self.buf[:spos], s, self.buf[newpos:]] + self.buf = '' + if newpos > slen: + slen = newpos + else: + self.buflist.append(s) + slen = newpos + self.len = slen + self.pos = newpos + + def writelines(self, iterable): + """Write a sequence of strings to the file. The sequence can be any + iterable object producing strings, typically a list of strings. There + is no return value. + + (The name is intended to match readlines(); writelines() does not add + line separators.) + """ + write = self.write + for line in iterable: + write(line) + + def flush(self): + """Flush the internal buffer + """ + _complain_ifclosed(self.closed) + + def getvalue(self): + """ + Retrieve the entire contents of the "file" at any time before + the StringIO object's close() method is called. + + The StringIO object can accept either Unicode or 8-bit strings, + but mixing the two may take some care. If both are used, 8-bit + strings that cannot be interpreted as 7-bit ASCII (that use the + 8th bit) will cause a UnicodeError to be raised when getvalue() + is called. + """ + _complain_ifclosed(self.closed) + if self.buflist: + self.buf += ''.join(self.buflist) + self.buflist = [] + return self.buf + + +# A little test suite + +def test(): + import sys + if sys.argv[1:]: + file = sys.argv[1] + else: + file = '/etc/passwd' + lines = open(file, 'r').readlines() + text = open(file, 'r').read() + f = StringIO() + for line in lines[:-2]: + f.write(line) + f.writelines(lines[-2:]) + if f.getvalue() != text: + raise RuntimeError('write failed') + length = f.tell() + print('File length =', length) + f.seek(len(lines[0])) + f.write(lines[1]) + f.seek(0) + print('First line =', repr(f.readline())) + print('Position =', f.tell()) + line = f.readline() + print('Second line =', repr(line)) + f.seek(-len(line), 1) + line2 = f.read(len(line)) + if line != line2: + raise RuntimeError('bad result after seek back') + f.seek(len(line2), 1) + list = f.readlines() + line = list[-1] + f.seek(f.tell() - len(line)) + line2 = f.read() + if line != line2: + raise RuntimeError('bad result after seek back from EOF') + print('Read', len(list), 'more lines') + print('File length =', f.tell()) + if f.tell() != length: + raise RuntimeError('bad length') + f.truncate(length/2) + f.seek(0, 2) + print('Truncated length =', f.tell()) + if f.tell() != length/2: + raise RuntimeError('truncate did not adjust length') + f.close() + +if __name__ == '__main__': + test() diff --git a/grumpy-runtime-src/lib/itertools.py b/grumpy-runtime-src/lib/itertools.py index 80ef4dea..f715901d 100644 --- a/grumpy-runtime-src/lib/itertools.py +++ b/grumpy-runtime-src/lib/itertools.py @@ -36,7 +36,7 @@ def __init__(self, *iterables): def __iter__(self): return self - def next(self): + def __next__(self): flag = True while flag: try: @@ -48,7 +48,7 @@ def next(self): def compress(data, selectors): - return (d for d,s in izip(data, selectors) if s) + return (d for d,s in zip(data, selectors) if s) def count(start=0, step=1): @@ -91,7 +91,7 @@ def __init__(self, iterable, key=None): def __iter__(self): return self - def next(self): + def __next__(self): while self.currkey == self.tgtkey: self.currvalue = next(self.it) # Exit on StopIteration self.currkey = self.keyfunc(self.currvalue) @@ -122,7 +122,7 @@ def ifilterfalse(predicate, iterable): def imap(function, *iterables): - iterables = map(iter, iterables) + iterables = list(map(iter, iterables)) while True: args = [next(it) for it in iterables] if function is None: @@ -133,7 +133,7 @@ def imap(function, *iterables): 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.maxsize, s.step or 1)) nexti = next(it) for i, element in enumerate(iterable): if i == nexti: @@ -142,7 +142,7 @@ def islice(iterable, *args): def izip(*iterables): - iterators = map(iter, iterables) + iterators = list(map(iter, iterables)) while iterators: yield tuple(map(next, iterators)) @@ -172,7 +172,7 @@ def sentinel(): def product(*args, **kwds): # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111 - pools = map(tuple, args) * kwds.get('repeat', 1) + pools = list(map(tuple, args)) * kwds.get('repeat', 1) result = [[]] for pool in pools: result = [x+[y] for x in result for y in pool] @@ -184,7 +184,7 @@ def permutations(iterable, r=None): pool = tuple(iterable) n = len(pool) r = n if r is None else r - for indices in product(range(n), repeat=r): + for indices in product(list(range(n)), repeat=r): if len(set(indices)) == r: yield tuple(pool[i] for i in indices) @@ -192,7 +192,7 @@ def permutations(iterable, r=None): def combinations(iterable, r): pool = tuple(iterable) n = len(pool) - for indices in permutations(range(n), r): + for indices in permutations(list(range(n)), r): if sorted(indices) == list(indices): yield tuple(pool[i] for i in indices) @@ -200,7 +200,7 @@ def combinations(iterable, r): def combinations_with_replacement(iterable, r): pool = tuple(iterable) n = len(pool) - for indices in product(range(n), repeat=r): + for indices in product(list(range(n)), repeat=r): if sorted(indices) == list(indices): yield tuple(pool[i] for i in indices) @@ -210,7 +210,7 @@ def repeat(object, times=None): while True: yield object else: - for i in xrange(times): + for i in range(times): yield object diff --git a/grumpy-runtime-src/lib/itertools_test.py b/grumpy-runtime-src/lib/itertools_test.py index 6300195b..27655f33 100644 --- a/grumpy-runtime-src/lib/itertools_test.py +++ b/grumpy-runtime-src/lib/itertools_test.py @@ -37,7 +37,7 @@ def TestCycle(): def TestDropwhile(): - r = range(10) + r = list(range(10)) cases = [ ((lambda x: x < 5, r), (5, 6, 7, 8, 9)), ((lambda x: True, r), ()), @@ -49,7 +49,7 @@ def TestDropwhile(): def TestChain(): - r = range(10) + r = list(range(10)) cases = [ ([r], tuple(r)), ([r, r], tuple(r) + tuple(r)), @@ -61,7 +61,7 @@ def TestChain(): def TestFromIterable(): - r = range(10) + r = list(range(10)) cases = [ ([r], tuple(r)), ([r, r], tuple(r) + tuple(r)), @@ -73,7 +73,7 @@ def TestFromIterable(): def TestIFilter(): - r = range(10) + r = list(range(10)) cases = [ ((lambda x: x < 5, r), (0, 1, 2, 3, 4)), ((lambda x: False, r), ()), @@ -81,12 +81,12 @@ def TestIFilter(): ((None, r), (1, 2, 3, 4, 5, 6, 7, 8, 9)) ] for args, want in cases: - got = tuple(itertools.ifilter(*args)) + got = tuple(filter(*args)) assert got == want, 'tuple(ifilter%s) == %s, want %s' % (args, got, want) def TestIFilterFalse(): - r = range(10) + r = list(range(10)) cases = [ ((lambda x: x < 5, r), (5, 6, 7, 8, 9)), ((lambda x: False, r), tuple(r)), @@ -94,12 +94,12 @@ def TestIFilterFalse(): ((None, r), (0,)) ] for args, want in cases: - got = tuple(itertools.ifilterfalse(*args)) + got = tuple(itertools.filterfalse(*args)) assert got == want, 'tuple(ifilterfalse%s) == %s, want %s' % (args, got, want) def TestISlice(): - r = range(10) + r = list(range(10)) cases = [ ((r, 5), (0, 1, 2, 3, 4)), ((r, 25, 30), ()), @@ -112,12 +112,12 @@ def TestISlice(): def TestIZipLongest(): cases = [ - (('abc', range(6)), (('a', 0), ('b', 1), ('c', 2), (None, 3), (None, 4), (None, 5))), - ((range(6), 'abc'), ((0, 'a'), (1, 'b'), (2, 'c'), (3, None), (4, None), (5, None))), - (([1, None, 3], 'ab', range(1)), ((1, 'a', 0), (None, 'b', None), (3, None, None))), + (('abc', list(range(6))), (('a', 0), ('b', 1), ('c', 2), (None, 3), (None, 4), (None, 5))), + ((list(range(6)), 'abc'), ((0, 'a'), (1, 'b'), (2, 'c'), (3, None), (4, None), (5, None))), + (([1, None, 3], 'ab', list(range(1))), ((1, 'a', 0), (None, 'b', None), (3, None, None))), ] for args, want in cases: - got = tuple(itertools.izip_longest(*args)) + got = tuple(itertools.zip_longest(*args)) assert got == want, 'tuple(izip_longest%s) == %s, want %s' % (args, got, want) @@ -136,10 +136,10 @@ def TestPermutations(): cases = [ (('AB',), (('A', 'B'), ('B', 'A'))), (('ABC', 2), (('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B'))), - ((range(3),), ((0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0))), + ((list(range(3)),), ((0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0))), (([],), ((),)), (([], 0), ((),)), - ((range(3), 4), ()), + ((list(range(3)), 4), ()), ] for args, want in cases: got = tuple(itertools.permutations(*args)) @@ -148,7 +148,7 @@ def TestPermutations(): def TestCombinations(): cases = [ - ((range(4), 3), ((0, 1, 2), (0, 1, 3), (0, 2, 3), (1, 2, 3))), + ((list(range(4)), 3), ((0, 1, 2), (0, 1, 3), (0, 2, 3), (1, 2, 3))), ] for args, want in cases: got = tuple(itertools.combinations(*args)) @@ -178,7 +178,7 @@ def TestGroupBy(): def TestTakewhile(): - r = range(10) + r = list(range(10)) cases = [ ((lambda x: x % 2 == 0, r), (0,)), ((lambda x: True, r), tuple(r)), diff --git a/grumpy-runtime-src/lib/os/path_test.py b/grumpy-runtime-src/lib/os/path_test.py index c191dce4..37df4764 100644 --- a/grumpy-runtime-src/lib/os/path_test.py +++ b/grumpy-runtime-src/lib/os/path_test.py @@ -29,9 +29,9 @@ def _AssertEqual(a, b): def TestAbspath(): _AssertEqual(path.abspath('/a/b/c'), '/a/b/c') - _AssertEqual(path.abspath(u'/a/b/c'), u'/a/b/c') + _AssertEqual(path.abspath('/a/b/c'), '/a/b/c') + _AssertEqual(path.abspath('/a/b/c/'), '/a/b/c') _AssertEqual(path.abspath('/a/b/c/'), '/a/b/c') - _AssertEqual(path.abspath(u'/a/b/c/'), u'/a/b/c') _AssertEqual(path.abspath('a/b/c'), path.normpath(os.getcwd() + '/a/b/c')) @@ -108,11 +108,11 @@ def TestNormPath(): _AssertEqual(path.normpath('abc/../123'), '123') _AssertEqual(path.normpath('../abc/123'), '../abc/123') _AssertEqual(path.normpath('x/y/./z'), 'x/y/z') - _AssertEqual(path.normpath(u'abc/'), u'abc') - _AssertEqual(path.normpath(u'/a//b'), u'/a/b') - _AssertEqual(path.normpath(u'abc/../123'), u'123') - _AssertEqual(path.normpath(u'../abc/123'), u'../abc/123') - _AssertEqual(path.normpath(u'x/y/./z'), u'x/y/z') + _AssertEqual(path.normpath('abc/'), 'abc') + _AssertEqual(path.normpath('/a//b'), '/a/b') + _AssertEqual(path.normpath('abc/../123'), '123') + _AssertEqual(path.normpath('../abc/123'), '../abc/123') + _AssertEqual(path.normpath('x/y/./z'), 'x/y/z') def TestSplit(): diff --git a/grumpy-runtime-src/lib/sys_test.py b/grumpy-runtime-src/lib/sys_test.py index 20a8db34..59b3eb1c 100644 --- a/grumpy-runtime-src/lib/sys_test.py +++ b/grumpy-runtime-src/lib/sys_test.py @@ -25,7 +25,7 @@ def TestArgv(): def TestMaxInt(): - assert sys.maxint > 2000000000 + assert sys.maxsize > 2000000000 def TestSysModules(): diff --git a/grumpy-runtime-src/lib/tempfile_test.py b/grumpy-runtime-src/lib/tempfile_test.py index 266e7bab..4034278d 100644 --- a/grumpy-runtime-src/lib/tempfile_test.py +++ b/grumpy-runtime-src/lib/tempfile_test.py @@ -50,7 +50,7 @@ def TestMkdTempOSError(): except OSError: pass else: - raise AssertionError, 'Should not be able to touch 0o500 paths' + raise AssertionError('Should not be able to touch 0o500 paths') os.rmdir(tempdir) diff --git a/grumpy-runtime-src/lib/weetest.py b/grumpy-runtime-src/lib/weetest.py index 53bdce93..b53d6054 100644 --- a/grumpy-runtime-src/lib/weetest.py +++ b/grumpy-runtime-src/lib/weetest.py @@ -96,19 +96,19 @@ def _RunOneBenchmark(name, test_func): """Runs a single benchmark and returns a _TestResult.""" b = _Benchmark(test_func, 1) result = _TestResult(name) - print name, + print(name, end=' ') start_time = time.time() try: b.Run() except Exception as e: # pylint: disable=broad-except result.status = 'error' - print 'ERROR' + print('ERROR') traceback.print_exc() else: result.status = 'passed' ops_per_sec = b.N / b.duration result.properties['ops_per_sec'] = ops_per_sec - print 'PASSED', ops_per_sec + print('PASSED', ops_per_sec) finally: result.duration = time.time() - start_time return result @@ -122,11 +122,11 @@ def _RunOneTest(name, test_func): test_func() except AssertionError as e: result.status = 'failed' - print name, 'FAILED' + print(name, 'FAILED') traceback.print_exc() except Exception as e: # pylint: disable=broad-except result.status = 'error' - print name, 'ERROR' + print(name, 'ERROR') traceback.print_exc() else: result.status = 'passed' diff --git a/grumpy-runtime-src/lib/weetest_test.py b/grumpy-runtime-src/lib/weetest_test.py index bb06f738..f87e42a6 100644 --- a/grumpy-runtime-src/lib/weetest_test.py +++ b/grumpy-runtime-src/lib/weetest_test.py @@ -186,6 +186,6 @@ def BenchmarkQux(self, b): if __name__ == '__main__': # Using keys() avoids "dictionary changed size during iteration" error. - for test_name in globals().keys(): + for test_name in list(globals().keys()): if test_name.startswith('Test'): globals()[test_name]() diff --git a/grumpy-runtime-src/testing/builtin_test.py b/grumpy-runtime-src/testing/builtin_test.py index c7932682..f232ced4 100644 --- a/grumpy-runtime-src/testing/builtin_test.py +++ b/grumpy-runtime-src/testing/builtin_test.py @@ -20,9 +20,9 @@ assert abs(-1) == 1 assert isinstance(abs(-1), int) -assert abs(long(2)) == 2 -assert abs(long(-2)) == 2 -assert isinstance(abs(long(-2)), long) +assert abs(int(2)) == 2 +assert abs(int(-2)) == 2 +assert isinstance(abs(int(-2)), int) assert abs(3.4) == 3.4 assert abs(-3.4) == 3.4 @@ -313,51 +313,51 @@ class Foo(object): # Test zip -assert zip('abc', (0, 1, 2)) == [('a', 0), ('b', 1), ('c', 2)] -assert list(zip('abc', range(6))) == zip('abc', range(6)) -assert list(zip('abcdef', range(3))) == zip('abcdef', range(3)) -assert list(zip('abcdef')) == zip('abcdef') -assert list(zip()) == zip() -assert [tuple(list(pair)) for pair in zip('abc', 'def')] == zip('abc', 'def') -assert [pair for pair in zip('abc', 'def')] == zip('abc', 'def') -assert zip({'b': 1, 'a': 2}) == [('a',), ('b',)] -assert zip(range(5)) == [(0,), (1,), (2,), (3,), (4,)] -assert zip(xrange(5)) == [(0,), (1,), (2,), (3,), (4,)] -assert zip([1, 2, 3], [1], [4, 5, 6]) == [(1, 1, 4)] -assert zip([1], [1, 2, 3], [4, 5, 6]) == [(1, 1, 4)] -assert zip([4, 5, 6], [1], [1, 2, 3]) == [(4, 1, 1)] -assert zip([1], [1, 2, 3], [4]) == [(1, 1, 4)] -assert zip([1, 2], [1, 2, 3], [4]) == [(1, 1, 4)] -assert zip([1, 2, 3, 4], [1, 2, 3], [4]) == [(1, 1, 4)] -assert zip([1], [1, 2], [4, 2, 4]) == [(1, 1, 4)] -assert zip([1, 2, 3], [1, 2], [4]) == [(1, 1, 4)] -assert zip([1, 2, 3], [1, 2], [4], []) == [] -assert zip([], [1], [1, 2], [1, 2, 3]) == [] +assert list(zip('abc', (0, 1, 2))) == [('a', 0), ('b', 1), ('c', 2)] +assert list(zip('abc', list(range(6)))) == list(zip('abc', list(range(6)))) +assert list(zip('abcdef', list(range(3)))) == list(zip('abcdef', list(range(3)))) +assert list(zip('abcdef')) == list(zip('abcdef')) +assert list(zip()) == list(zip()) +assert [tuple(list(pair)) for pair in zip('abc', 'def')] == list(zip('abc', 'def')) +assert [pair for pair in zip('abc', 'def')] == list(zip('abc', 'def')) +assert list(zip({'b': 1, 'a': 2})) == [('a',), ('b',)] +assert list(zip(list(range(5)))) == [(0,), (1,), (2,), (3,), (4,)] +assert list(zip(list(range(5)))) == [(0,), (1,), (2,), (3,), (4,)] +assert list(zip([1, 2, 3], [1], [4, 5, 6])) == [(1, 1, 4)] +assert list(zip([1], [1, 2, 3], [4, 5, 6])) == [(1, 1, 4)] +assert list(zip([4, 5, 6], [1], [1, 2, 3])) == [(4, 1, 1)] +assert list(zip([1], [1, 2, 3], [4])) == [(1, 1, 4)] +assert list(zip([1, 2], [1, 2, 3], [4])) == [(1, 1, 4)] +assert list(zip([1, 2, 3, 4], [1, 2, 3], [4])) == [(1, 1, 4)] +assert list(zip([1], [1, 2], [4, 2, 4])) == [(1, 1, 4)] +assert list(zip([1, 2, 3], [1, 2], [4])) == [(1, 1, 4)] +assert list(zip([1, 2, 3], [1, 2], [4], [])) == [] +assert list(zip([], [1], [1, 2], [1, 2, 3])) == [] try: - zip([1, 2, 3], [1, 2], [4], None) + list(zip([1, 2, 3], [1, 2], [4], None)) raise AssertionError except TypeError: pass # Test map -assert map(str, []) == [] -assert map(str, [1, 2, 3]) == ["1", "2", "3"] -assert map(str, (1, 2, 3)) == ["1", "2", "3"] +assert list(map(str, [])) == [] +assert list(map(str, [1, 2, 3])) == ["1", "2", "3"] +assert list(map(str, (1, 2, 3))) == ["1", "2", "3"] # assert map(str, (1.0, 2.0, 3.0)) == ["1", "2", "3"] -assert map(str, range(3)) == ["0", "1", "2"] -assert map(str, xrange(3)) == ["0", "1", "2"] -assert map(int, ["1", "2", "3"]) == [1, 2, 3] -assert map(int, "123") == [1, 2, 3] -assert map(int, {"1": "a", "2": "b"}) == [1, 2] -assert map(int, {1: "a", 2: "b"}) == [1, 2] -assert map(lambda a, b: (str(a), float(b or 0) + 0.1), - [1, 2, 3], [1, 2]) == [('1', 1.1), ('2', 2.1), ('3', 0.1)] -assert map(None, [1, 2, 3]) == [1, 2, 3] +assert list(map(str, list(range(3)))) == ["0", "1", "2"] +assert list(map(str, range(3))) == ["0", "1", "2"] +assert list(map(int, ["1", "2", "3"])) == [1, 2, 3] +assert list(map(int, "123")) == [1, 2, 3] +assert list(map(int, {"1": "a", "2": "b"})) == [1, 2] +assert list(map(int, {1: "a", 2: "b"})) == [1, 2] +assert list(map(lambda a, b: (str(a), float(b or 0) + 0.1), + [1, 2, 3], [1, 2])) == [('1', 1.1), ('2', 2.1), ('3', 0.1)] +assert list([1, 2, 3]) == [1, 2, 3] a = [1, 2, 3] -assert map(None, a) == a -assert map(None, a) is not a -assert map(None, (1, 2, 3)) == [1, 2, 3] +assert list(a) == a +assert list(a) is not a +assert list((1, 2, 3)) == [1, 2, 3] # divmod(v, w) @@ -372,14 +372,14 @@ class Foo(object): assert isinstance(divmod(12, 7)[0], int) assert isinstance(divmod(12, 7)[1], int) -assert divmod(long(7), long(3)) == (2L, 1L) -assert divmod(long(3), long(-7)) == (-1L, -4L) -assert divmod(long(sys.maxsize), long(-sys.maxsize)) == (-1L, 0L) -assert divmod(long(-sys.maxsize), long(1)) == (-sys.maxsize, 0L) -assert divmod(long(-sys.maxsize), long(-1)) == (sys.maxsize, 0L) -assert isinstance(divmod(long(7), long(3)), tuple) -assert isinstance(divmod(long(7), long(3))[0], long) -assert isinstance(divmod(long(7), long(3))[1], long) +assert divmod(int(7), int(3)) == (2, 1) +assert divmod(int(3), int(-7)) == (-1, -4) +assert divmod(int(sys.maxsize), int(-sys.maxsize)) == (-1, 0) +assert divmod(int(-sys.maxsize), int(1)) == (-sys.maxsize, 0) +assert divmod(int(-sys.maxsize), int(-1)) == (sys.maxsize, 0) +assert isinstance(divmod(int(7), int(3)), tuple) +assert isinstance(divmod(int(7), int(3))[0], int) +assert isinstance(divmod(int(7), int(3))[1], int) assert divmod(3.25, 1.0) == (3.0, 0.25) assert divmod(-3.25, 1.0) == (-4.0, 0.75) @@ -400,7 +400,7 @@ class Foo(object): # internal exception state. See: # https://github.com/google/grumpy/issues/305 sys.exc_clear() -zip((1, 3), (2, 4)) +list(zip((1, 3), (2, 4))) assert not any(sys.exc_info()) -map(int, (1, 2, 3)) +list(map(int, (1, 2, 3))) assert not any(sys.exc_info()) diff --git a/grumpy-runtime-src/testing/comprehension_test.py b/grumpy-runtime-src/testing/comprehension_test.py index deff8285..ae85a2e8 100644 --- a/grumpy-runtime-src/testing/comprehension_test.py +++ b/grumpy-runtime-src/testing/comprehension_test.py @@ -20,4 +20,4 @@ assert [c for c in 'abc'] == ['a', 'b', 'c'] assert [i + j for i in range(2) for j in range(2)] == [0, 1, 1, 2] assert [c for c in 'foobar' if c in 'aeiou'] == ['o', 'o', 'a'] -assert {i: str(i) for i in range(2)} == {0: '0', 1: '1'} +assert {i: str(i) for i in list(range(2))} == {0: '0', 1: '1'} diff --git a/grumpy-runtime-src/testing/generator_test.py b/grumpy-runtime-src/testing/generator_test.py index 182249c5..f6db1e73 100644 --- a/grumpy-runtime-src/testing/generator_test.py +++ b/grumpy-runtime-src/testing/generator_test.py @@ -39,17 +39,17 @@ def gen3(): yield 1 # pylint: disable=unreachable g = gen3() try: - g.next() + next(g) except RuntimeError: pass assert list(g) == [] # pylint: disable=g-explicit-bool-comparison def gen4(): - yield g.next() + yield next(g) g = gen4() try: - g.next() + next(g) except ValueError as e: assert 'generator already executing' in str(e), str(e) else: diff --git a/grumpy-runtime-src/testing/global_test.py b/grumpy-runtime-src/testing/global_test.py index 2ed46a4e..16ea7901 100644 --- a/grumpy-runtime-src/testing/global_test.py +++ b/grumpy-runtime-src/testing/global_test.py @@ -45,7 +45,7 @@ def f3(): del x f3() try: - print x + print(x) raise AssertionError except NameError: pass diff --git a/grumpy-runtime-src/testing/import_test.py b/grumpy-runtime-src/testing/import_test.py index 384f772b..1896e7bd 100644 --- a/grumpy-runtime-src/testing/import_test.py +++ b/grumpy-runtime-src/testing/import_test.py @@ -14,4 +14,4 @@ import sys -print sys.maxint +print(sys.maxsize) diff --git a/grumpy-runtime-src/testing/list_test.py b/grumpy-runtime-src/testing/list_test.py index 9ea2a3d8..8707d4d7 100644 --- a/grumpy-runtime-src/testing/list_test.py +++ b/grumpy-runtime-src/testing/list_test.py @@ -84,7 +84,7 @@ assert a == [3, 2, 4, 1] a.extend((6, 7)) assert a == [3, 2, 4, 1, 6, 7] -a.extend(range(3)) +a.extend(list(range(3))) assert a == [3, 2, 4, 1, 6, 7, 0, 1, 2] try: diff --git a/grumpy-runtime-src/testing/op_test.py b/grumpy-runtime-src/testing/op_test.py index 0773b0ad..93f1e4d9 100644 --- a/grumpy-runtime-src/testing/op_test.py +++ b/grumpy-runtime-src/testing/op_test.py @@ -77,7 +77,7 @@ def TestNeg(): x = float('nan') assert math.isnan(-x) - x = long(100) + x = int(100) assert -x == -100 @@ -100,7 +100,7 @@ def TestPos(): x = float('nan') assert math.isnan(+x) - x = long(100) + x = int(100) assert +x == 100 diff --git a/grumpy-runtime-src/testing/pow_test.py b/grumpy-runtime-src/testing/pow_test.py index 13266c84..038b30dd 100644 --- a/grumpy-runtime-src/testing/pow_test.py +++ b/grumpy-runtime-src/testing/pow_test.py @@ -29,20 +29,20 @@ assert 2 ** 1 == 2, "2 ** 1" assert 2 ** 2 == 4, "2 ** 2" -assert 2L ** -2 == 0.25, "2L ** -2" -assert 2L ** -1 == 0.5, "2L ** -1" -assert 2L ** 0 == 1, "2L ** 0" -assert 2L ** 1 == 2, "2L ** 1" -assert 2L ** 2 == 4, "2L ** 2" +assert 2 ** -2 == 0.25, "2L ** -2" +assert 2 ** -1 == 0.5, "2L ** -1" +assert 2 ** 0 == 1, "2L ** 0" +assert 2 ** 1 == 2, "2L ** 1" +assert 2 ** 2 == 4, "2L ** 2" # Test the rpow operator on long -assert 2 ** -2L == 0.25, "2 ** -2L" -assert 2 ** -1L == 0.5, "2 ** -1L" -assert 2 ** 0L == 1, "2 ** 0L" -assert 2 ** 1L == 2, "2 ** 1L" -assert 2 ** 2L == 4, "2 ** 2L" +assert 2 ** -2 == 0.25, "2 ** -2L" +assert 2 ** -1 == 0.5, "2 ** -1L" +assert 2 ** 0 == 1, "2 ** 0L" +assert 2 ** 1 == 2, "2 ** 1L" +assert 2 ** 2 == 4, "2 ** 2L" -for zero in (0, 0L, 0.0): +for zero in (0, 0, 0.0): try: result = zero ** -2 assert "0 ** -2" @@ -61,7 +61,7 @@ assert 2 ** zero == 1 assert (-2.0) ** zero == 1 - assert 3L ** zero == 1 + assert 3 ** zero == 1 assert (-2) ** -2 == 0.25, '(-2) ** -2' assert (-2) ** -1 == -0.5, '(-2) ** -1' diff --git a/grumpy-runtime-src/testing/str_test.py b/grumpy-runtime-src/testing/str_test.py index 92e7236f..5a681504 100644 --- a/grumpy-runtime-src/testing/str_test.py +++ b/grumpy-runtime-src/testing/str_test.py @@ -18,7 +18,7 @@ # Test Add assert "foo" + "bar" == "foobar" -assert "foo" + u"bar" == u"foobar" +assert "foo" + "bar" == "foobar" assert "baz" + "" == "baz" # Test capitalize @@ -62,8 +62,8 @@ assert 'abcdefghiabc'.find('def', 4) == -1 assert 'abc'.find('', 0) == 0 assert 'abc'.find('', 3) == 3 -assert 'abc'.find('c', long(1)) == 2 -assert 'abc'.find('c', 0, long(3)) == 2 +assert 'abc'.find('c', int(1)) == 2 +assert 'abc'.find('c', 0, int(3)) == 2 assert 'abc'.find('', 4) == -1 assert 'rrarrrrrrrrra'.find('a') == 2 assert 'rrarrrrrrrrra'.find('a', 4) == 12 @@ -72,10 +72,10 @@ assert 'rrarrrrrrrrra'.find('a', None, 6) == 2 assert ''.find('') == 0 assert ''.find('', 1, 1) == -1 -assert ''.find('', sys.maxint, 0) == -1 +assert ''.find('', sys.maxsize, 0) == -1 assert ''.find('xx') == -1 assert ''.find('xx', 1, 1) == -1 -assert ''.find('xx', sys.maxint, 0) == -1 +assert ''.find('xx', sys.maxsize, 0) == -1 assert 'ab'.find('xxx', sys.maxsize + 1, 0) == -1 # TODO: Support unicode substring. # assert "foobar".find(u"bar") == 3 @@ -124,7 +124,7 @@ def __index__(self): class LongIndexType(object): def __index__(self): - return 2L + return 2 class IntIntType(object): def __int__(self): @@ -132,10 +132,10 @@ def __int__(self): class LongIntType(object): def __int__(self): - return 2L + return 2 assert "bar"[1] == "a" -assert "bar"[long(1)] == "a" +assert "bar"[int(1)] == "a" assert "baz"[-1] == "z" assert "baz"[IntIndexType()] == "z" assert "baz"[LongIndexType()] == "z" @@ -173,7 +173,7 @@ def __int__(self): # Test Mod assert "%s" % 42 == "42" assert "%f" % 3.14 == "3.140000" -assert "abc %d" % 123L == "abc 123" +assert "abc %d" % 123 == "abc 123" assert "%d" % 3.14 == "3" assert "%%" % tuple() == "%" assert "%r" % "abc" == "'abc'" @@ -303,14 +303,14 @@ def __int__(self): return 3 class AL(object): def __int__(self): - return 3L + return 3 class B(object): def __index__(self): return 3 class BL(object): def __index__(self): - return 3L + return 3 assert 'aaaaa'.replace('a', 'b', A()) == 'bbbaa' assert 'aaaaa'.replace('a', 'b', AL()) == 'bbbaa' diff --git a/grumpy-runtime-src/third_party/pypy/_collections.py b/grumpy-runtime-src/third_party/pypy/_collections.py index 2660c6ee..0d6fc362 100644 --- a/grumpy-runtime-src/third_party/pypy/_collections.py +++ b/grumpy-runtime-src/third_party/pypy/_collections.py @@ -14,8 +14,8 @@ # def _thread_ident(): # return -1 -import thread -_thread_ident = thread.get_ident +import _thread +_thread_ident = _thread.get_ident n = 30 LFTLNK = n @@ -378,7 +378,7 @@ def giveup(): raise RuntimeError("deque mutated during iteration") self._gen = itergen(deq.state, giveup) - def next(self): + def __next__(self): res = next(self._gen) self.counter -= 1 return res @@ -433,5 +433,5 @@ def __reduce__(self): This API is used by pickle.py and copy.py. """ - return (type(self), (self.default_factory,), None, None, self.iteritems()) + return (type(self), (self.default_factory,), None, None, iter(self.items())) diff --git a/grumpy-runtime-src/third_party/pypy/_csv.py b/grumpy-runtime-src/third_party/pypy/_csv.py index bf4fa773..7de3a66a 100644 --- a/grumpy-runtime-src/third_party/pypy/_csv.py +++ b/grumpy-runtime-src/third_party/pypy/_csv.py @@ -66,7 +66,7 @@ class excel: 'undefined', 'unregister_dialect', 'writer' ] -QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONNUMERIC, QUOTE_NONE = range(4) +QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONNUMERIC, QUOTE_NONE = list(range(4)) _dialects = {} _field_limit = 128 * 1024 # max parsed field size @@ -90,12 +90,12 @@ def __new__(cls, dialect, **kwargs): (name,)) if dialect is not None: - if isinstance(dialect, basestring): + if isinstance(dialect, str): dialect = get_dialect(dialect) # Can we reuse this instance? if (isinstance(dialect, Dialect) - and all(value is None for value in kwargs.itervalues())): + and all(value is None for value in iter(kwargs.values()))): return dialect self = object.__new__(cls) @@ -176,7 +176,7 @@ def _call_dialect(dialect_inst, kwargs): def register_dialect(name, dialect=None, **kwargs): """Create a mapping from a string name to a dialect class. dialect = csv.register_dialect(name, dialect)""" - if not isinstance(name, basestring): + if not isinstance(name, str): raise TypeError("dialect name must be a string or unicode") dialect = _call_dialect(dialect, kwargs) @@ -212,7 +212,7 @@ class Reader(object): (START_RECORD, START_FIELD, ESCAPED_CHAR, IN_FIELD, IN_QUOTED_FIELD, ESCAPE_IN_QUOTED_FIELD, QUOTE_IN_QUOTED_FIELD, - EAT_CRNL) = range(8) + EAT_CRNL) = list(range(8)) def __init__(self, iterator, dialect=None, **kwargs): self.dialect = _call_dialect(dialect, kwargs) @@ -230,7 +230,7 @@ def _parse_reset(self): def __iter__(self): return self - def next(self): + def __next__(self): self._parse_reset() while True: try: @@ -574,7 +574,7 @@ def field_size_limit(limit=undefined): old_limit = _field_limit if limit is not undefined: - if not isinstance(limit, (int, long)): + if not isinstance(limit, int): raise TypeError("int expected, got %s" % (limit.__class__.__name__,)) _field_limit = limit diff --git a/grumpy-runtime-src/third_party/pypy/_functools.py b/grumpy-runtime-src/third_party/pypy/_functools.py index 2e142d54..e0e2ff29 100644 --- a/grumpy-runtime-src/third_party/pypy/_functools.py +++ b/grumpy-runtime-src/third_party/pypy/_functools.py @@ -63,7 +63,7 @@ def __call__(self, *fargs, **fkeywords): return self._func(*(self._args + fargs), **fkeywords) def __reduce__(self): - d = dict((k, v) for k, v in self.__dict__.iteritems() if k not in + d = dict((k, v) for k, v in iter(self.__dict__.items()) if k not in ('_func', '_args', '_keywords')) if len(d) == 0: d = None diff --git a/grumpy-runtime-src/third_party/pypy/_sha256.py b/grumpy-runtime-src/third_party/pypy/_sha256.py index ff1f6da8..0cfe2d0b 100644 --- a/grumpy-runtime-src/third_party/pypy/_sha256.py +++ b/grumpy-runtime-src/third_party/pypy/_sha256.py @@ -28,10 +28,10 @@ def sha_transform(sha_info): W = [] d = sha_info['data'] - for i in xrange(0,16): + for i in range(0,16): W.append( (d[4*i]<<24) + (d[4*i+1]<<16) + (d[4*i+2]<<8) + d[4*i+3]) - for i in xrange(16,64): + for i in range(16,64): W.append( (Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16]) & 0xffffffff ) ss = sha_info['digest'][:] @@ -134,7 +134,7 @@ def sha224_init(): def getbuf(s): if isinstance(s, str): return s - elif isinstance(s, unicode): + elif isinstance(s, str): return str(s) else: return buffer(s) diff --git a/grumpy-runtime-src/third_party/pypy/_sha512.py b/grumpy-runtime-src/third_party/pypy/_sha512.py index eec167e2..7ac51c59 100644 --- a/grumpy-runtime-src/third_party/pypy/_sha512.py +++ b/grumpy-runtime-src/third_party/pypy/_sha512.py @@ -32,10 +32,10 @@ def sha_transform(sha_info): W = [] d = sha_info['data'] - for i in xrange(0,16): + for i in range(0,16): W.append( (d[8*i]<<56) + (d[8*i+1]<<48) + (d[8*i+2]<<40) + (d[8*i+3]<<32) + (d[8*i+4]<<24) + (d[8*i+5]<<16) + (d[8*i+6]<<8) + d[8*i+7]) - for i in xrange(16,80): + for i in range(16,80): W.append( (Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16]) & 0xffffffffffffffff ) ss = sha_info['digest'][:] @@ -154,7 +154,7 @@ def sha384_init(): def getbuf(s): if isinstance(s, str): return s - elif isinstance(s, unicode): + elif isinstance(s, str): return str(s) else: return buffer(s) diff --git a/grumpy-runtime-src/third_party/pypy/_sre.py b/grumpy-runtime-src/third_party/pypy/_sre.py index 5de71ef9..b6dcd18c 100644 --- a/grumpy-runtime-src/third_party/pypy/_sre.py +++ b/grumpy-runtime-src/third_party/pypy/_sre.py @@ -61,7 +61,7 @@ def __init__(self, pattern, flags, code, groups=0, groupindex={}, indexgroup=[No self._indexgroup = indexgroup # Maps indices to group names self._code = code - def match(self, string, pos=0, endpos=sys.maxint): + def match(self, string, pos=0, endpos=sys.maxsize): """If zero or more characters at the beginning of string match this regular expression, return a corresponding MatchObject instance. Return None if the string does not match the pattern.""" @@ -71,7 +71,7 @@ def match(self, string, pos=0, endpos=sys.maxint): else: return None - def search(self, string, pos=0, endpos=sys.maxint): + def search(self, string, pos=0, endpos=sys.maxsize): """Scan through string looking for a location where this regular expression produces a match, and return a corresponding MatchObject instance. Return None if no position in the string matches the @@ -82,7 +82,7 @@ def search(self, string, pos=0, endpos=sys.maxint): else: return None - def findall(self, string, pos=0, endpos=sys.maxint): + def findall(self, string, pos=0, endpos=sys.maxsize): """Return a list of all non-overlapping matches of pattern in string.""" matchlist = [] state = _State(string, pos, endpos, self.flags) @@ -108,7 +108,7 @@ def _subx(self, template, string, count=0, subn=False): if not callable(template) and "\\" in template: # handle non-literal strings ; hand it over to the template compiler raise NotImplementedError() - state = _State(string, 0, sys.maxint, self.flags) + state = _State(string, 0, sys.maxsize, self.flags) sublist = [] n = last_pos = 0 @@ -123,7 +123,7 @@ def _subx(self, template, string, count=0, subn=False): last_pos == state.string_position and n > 0): # the above ignores empty matches on latest position if callable(filter): - sublist.append(filter(SRE_Match(self, state))) + sublist.append(list(filter(SRE_Match(self, state)))) else: sublist.append(filter) last_pos = state.string_position @@ -155,7 +155,7 @@ def subn(self, repl, string, count=0): def split(self, string, maxsplit=0): """Split string by the occurrences of pattern.""" splitlist = [] - state = _State(string, 0, sys.maxint, self.flags) + state = _State(string, 0, sys.maxsize, self.flags) n = 0 last = state.start while not maxsplit or n < maxsplit: @@ -180,19 +180,19 @@ def split(self, string, maxsplit=0): splitlist.append(string[last:state.end]) return splitlist - def finditer(self, string, pos=0, endpos=sys.maxint): + def finditer(self, string, pos=0, endpos=sys.maxsize): """Return a list of all non-overlapping matches of pattern in string.""" scanner = self.scanner(string, pos, endpos) return iter(scanner.search, None) - def scanner(self, string, start=0, end=sys.maxint): + def scanner(self, string, start=0, end=sys.maxsize): return SRE_Scanner(self, string, start, end) def __copy__(self): - raise TypeError, "cannot copy this pattern object" + raise TypeError("cannot copy this pattern object") def __deepcopy__(self): - raise TypeError, "cannot copy this pattern object" + raise TypeError("cannot copy this pattern object") class SRE_Scanner(object): @@ -310,7 +310,7 @@ def groupdict(self, default=None): The default argument is used for groups that did not participate in the match (defaults to None).""" groupdict = {} - for key, value in self.re.groupindex.items(): + for key, value in list(self.re.groupindex.items()): groupdict[key] = self._get_slice(value, default) return groupdict @@ -328,10 +328,10 @@ def group(self, *args): return tuple(grouplist) def __copy__(): - raise TypeError, "cannot copy this pattern object" + raise TypeError("cannot copy this pattern object") def __deepcopy__(): - raise TypeError, "cannot copy this pattern object" + raise TypeError("cannot copy this pattern object") class _State(object): @@ -567,7 +567,7 @@ def build_dispatch_table(cls, code_dict, method_prefix): if cls.DISPATCH_TABLE is not None: return table = {} - for key, value in code_dict.items(): + for key, value in list(code_dict.items()): if hasattr(cls, "%s%s" % (method_prefix, key)): table[value] = getattr(cls, "%s%s" % (method_prefix, key)) cls.DISPATCH_TABLE = table @@ -601,13 +601,13 @@ def dispatch(self, opcode, context): if id(context) in self.executing_contexts: generator = self.executing_contexts[id(context)] del self.executing_contexts[id(context)] - has_finished = generator.next() + has_finished = next(generator) else: method = self.DISPATCH_TABLE.get(opcode, _OpcodeDispatcher.unknown) has_finished = method(self, context) if hasattr(has_finished, "next"): # avoid using the types module generator = has_finished - has_finished = generator.next() + has_finished = next(generator) if not has_finished: self.executing_contexts[id(context)] = generator return has_finished @@ -1285,7 +1285,7 @@ def _is_loc_word(char): return (not (ord(char) & ~255) and char.isalnum()) or char == '_' def _is_uni_word(char): - return unichr(ord(char)).isalnum() or char == '_' + return chr(ord(char)).isalnum() or char == '_' def _is_linebreak(char): return char == "\n" @@ -1295,4 +1295,4 @@ def _is_linebreak(char): def _log(message): if 0: - print message \ No newline at end of file + print(message) \ No newline at end of file diff --git a/grumpy-runtime-src/third_party/pypy/binascii.py b/grumpy-runtime-src/third_party/pypy/binascii.py index 085fd244..e82afd95 100644 --- a/grumpy-runtime-src/third_party/pypy/binascii.py +++ b/grumpy-runtime-src/third_party/pypy/binascii.py @@ -68,7 +68,7 @@ def triples_gen(s): chr(0x20 + (((B << 2) | ((C >> 6) & 0x3)) & 0x3F)), chr(0x20 + (( C ) & 0x3F))]) for A, B, C in triples_gen(s)] - return chr(ord(' ') + (length & 077)) + ''.join(result) + '\n' + return chr(ord(' ') + (length & 0o77)) + ''.join(result) + '\n' table_a2b_base64 = { @@ -141,7 +141,7 @@ def triples_gen(s): def a2b_base64(s): - if not isinstance(s, (str, unicode)): + if not isinstance(s, str): raise TypeError("expected string or unicode, got %r" % (s,)) s = s.rstrip() # clean out all invalid characters, this also strips the final '=' padding @@ -598,68 +598,68 @@ def rledecode_hqx(s): return ''.join(result) crc_32_tab = [ - 0x00000000L, 0x77073096L, 0xee0e612cL, 0x990951baL, 0x076dc419L, - 0x706af48fL, 0xe963a535L, 0x9e6495a3L, 0x0edb8832L, 0x79dcb8a4L, - 0xe0d5e91eL, 0x97d2d988L, 0x09b64c2bL, 0x7eb17cbdL, 0xe7b82d07L, - 0x90bf1d91L, 0x1db71064L, 0x6ab020f2L, 0xf3b97148L, 0x84be41deL, - 0x1adad47dL, 0x6ddde4ebL, 0xf4d4b551L, 0x83d385c7L, 0x136c9856L, - 0x646ba8c0L, 0xfd62f97aL, 0x8a65c9ecL, 0x14015c4fL, 0x63066cd9L, - 0xfa0f3d63L, 0x8d080df5L, 0x3b6e20c8L, 0x4c69105eL, 0xd56041e4L, - 0xa2677172L, 0x3c03e4d1L, 0x4b04d447L, 0xd20d85fdL, 0xa50ab56bL, - 0x35b5a8faL, 0x42b2986cL, 0xdbbbc9d6L, 0xacbcf940L, 0x32d86ce3L, - 0x45df5c75L, 0xdcd60dcfL, 0xabd13d59L, 0x26d930acL, 0x51de003aL, - 0xc8d75180L, 0xbfd06116L, 0x21b4f4b5L, 0x56b3c423L, 0xcfba9599L, - 0xb8bda50fL, 0x2802b89eL, 0x5f058808L, 0xc60cd9b2L, 0xb10be924L, - 0x2f6f7c87L, 0x58684c11L, 0xc1611dabL, 0xb6662d3dL, 0x76dc4190L, - 0x01db7106L, 0x98d220bcL, 0xefd5102aL, 0x71b18589L, 0x06b6b51fL, - 0x9fbfe4a5L, 0xe8b8d433L, 0x7807c9a2L, 0x0f00f934L, 0x9609a88eL, - 0xe10e9818L, 0x7f6a0dbbL, 0x086d3d2dL, 0x91646c97L, 0xe6635c01L, - 0x6b6b51f4L, 0x1c6c6162L, 0x856530d8L, 0xf262004eL, 0x6c0695edL, - 0x1b01a57bL, 0x8208f4c1L, 0xf50fc457L, 0x65b0d9c6L, 0x12b7e950L, - 0x8bbeb8eaL, 0xfcb9887cL, 0x62dd1ddfL, 0x15da2d49L, 0x8cd37cf3L, - 0xfbd44c65L, 0x4db26158L, 0x3ab551ceL, 0xa3bc0074L, 0xd4bb30e2L, - 0x4adfa541L, 0x3dd895d7L, 0xa4d1c46dL, 0xd3d6f4fbL, 0x4369e96aL, - 0x346ed9fcL, 0xad678846L, 0xda60b8d0L, 0x44042d73L, 0x33031de5L, - 0xaa0a4c5fL, 0xdd0d7cc9L, 0x5005713cL, 0x270241aaL, 0xbe0b1010L, - 0xc90c2086L, 0x5768b525L, 0x206f85b3L, 0xb966d409L, 0xce61e49fL, - 0x5edef90eL, 0x29d9c998L, 0xb0d09822L, 0xc7d7a8b4L, 0x59b33d17L, - 0x2eb40d81L, 0xb7bd5c3bL, 0xc0ba6cadL, 0xedb88320L, 0x9abfb3b6L, - 0x03b6e20cL, 0x74b1d29aL, 0xead54739L, 0x9dd277afL, 0x04db2615L, - 0x73dc1683L, 0xe3630b12L, 0x94643b84L, 0x0d6d6a3eL, 0x7a6a5aa8L, - 0xe40ecf0bL, 0x9309ff9dL, 0x0a00ae27L, 0x7d079eb1L, 0xf00f9344L, - 0x8708a3d2L, 0x1e01f268L, 0x6906c2feL, 0xf762575dL, 0x806567cbL, - 0x196c3671L, 0x6e6b06e7L, 0xfed41b76L, 0x89d32be0L, 0x10da7a5aL, - 0x67dd4accL, 0xf9b9df6fL, 0x8ebeeff9L, 0x17b7be43L, 0x60b08ed5L, - 0xd6d6a3e8L, 0xa1d1937eL, 0x38d8c2c4L, 0x4fdff252L, 0xd1bb67f1L, - 0xa6bc5767L, 0x3fb506ddL, 0x48b2364bL, 0xd80d2bdaL, 0xaf0a1b4cL, - 0x36034af6L, 0x41047a60L, 0xdf60efc3L, 0xa867df55L, 0x316e8eefL, - 0x4669be79L, 0xcb61b38cL, 0xbc66831aL, 0x256fd2a0L, 0x5268e236L, - 0xcc0c7795L, 0xbb0b4703L, 0x220216b9L, 0x5505262fL, 0xc5ba3bbeL, - 0xb2bd0b28L, 0x2bb45a92L, 0x5cb36a04L, 0xc2d7ffa7L, 0xb5d0cf31L, - 0x2cd99e8bL, 0x5bdeae1dL, 0x9b64c2b0L, 0xec63f226L, 0x756aa39cL, - 0x026d930aL, 0x9c0906a9L, 0xeb0e363fL, 0x72076785L, 0x05005713L, - 0x95bf4a82L, 0xe2b87a14L, 0x7bb12baeL, 0x0cb61b38L, 0x92d28e9bL, - 0xe5d5be0dL, 0x7cdcefb7L, 0x0bdbdf21L, 0x86d3d2d4L, 0xf1d4e242L, - 0x68ddb3f8L, 0x1fda836eL, 0x81be16cdL, 0xf6b9265bL, 0x6fb077e1L, - 0x18b74777L, 0x88085ae6L, 0xff0f6a70L, 0x66063bcaL, 0x11010b5cL, - 0x8f659effL, 0xf862ae69L, 0x616bffd3L, 0x166ccf45L, 0xa00ae278L, - 0xd70dd2eeL, 0x4e048354L, 0x3903b3c2L, 0xa7672661L, 0xd06016f7L, - 0x4969474dL, 0x3e6e77dbL, 0xaed16a4aL, 0xd9d65adcL, 0x40df0b66L, - 0x37d83bf0L, 0xa9bcae53L, 0xdebb9ec5L, 0x47b2cf7fL, 0x30b5ffe9L, - 0xbdbdf21cL, 0xcabac28aL, 0x53b39330L, 0x24b4a3a6L, 0xbad03605L, - 0xcdd70693L, 0x54de5729L, 0x23d967bfL, 0xb3667a2eL, 0xc4614ab8L, - 0x5d681b02L, 0x2a6f2b94L, 0xb40bbe37L, 0xc30c8ea1L, 0x5a05df1bL, - 0x2d02ef8dL + 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, + 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, + 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, + 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, + 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, + 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, + 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, + 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, + 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, + 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, + 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, + 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, + 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, + 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, + 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, + 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, + 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, + 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, + 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, + 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, + 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, + 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, + 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, + 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, + 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, + 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, + 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, + 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, + 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, + 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, + 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, + 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, + 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, + 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, + 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, + 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, + 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, + 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, + 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, + 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, + 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, + 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, + 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, + 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, + 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, + 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, + 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, + 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, + 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, + 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, + 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, + 0x2d02ef8d ] def crc32(s, crc=0): result = 0 - crc = ~long(crc) & 0xffffffffL + crc = ~int(crc) & 0xffffffff for c in s: - crc = crc_32_tab[(crc ^ long(ord(c))) & 0xffL] ^ (crc >> 8) + crc = crc_32_tab[(crc ^ int(ord(c))) & 0xff] ^ (crc >> 8) #/* Note: (crc >> 8) MUST zero fill on left - result = crc ^ 0xffffffffL + result = crc ^ 0xffffffff if result > (1 << 31): result = ((result + (1<<31)) % (1<<32)) - (1<<31) diff --git a/grumpy-runtime-src/third_party/pypy/datetime.py b/grumpy-runtime-src/third_party/pypy/datetime.py index fe99e1e3..1411bcdd 100644 --- a/grumpy-runtime-src/third_party/pypy/datetime.py +++ b/grumpy-runtime-src/third_party/pypy/datetime.py @@ -298,8 +298,8 @@ def _check_int_field(value): else: if isinstance(value, int): return int(value) - elif isinstance(value, long): - return int(long(value)) + elif isinstance(value, int): + return int(int(value)) raise TypeError('__int__ method should return an integer') raise TypeError('an integer is required') raise TypeError('integer argument expected, got float') @@ -421,7 +421,7 @@ def _normalize_date(year, month, day, ignore_overflow=False): return year, month, day def _accum(tag, sofar, num, factor, leftover): - if isinstance(num, (int, long)): + if isinstance(num, int): prod = num * factor rsum = sofar + prod return rsum, leftover @@ -431,7 +431,7 @@ def _accum(tag, sofar, num, factor, leftover): rsum = sofar + prod if fracpart == 0.0: return rsum, leftover - assert isinstance(factor, (int, long)) + assert isinstance(factor, int) fracpart, intpart = _math.modf(factor * fracpart) rsum += int(intpart) return rsum, leftover + fracpart @@ -594,7 +594,7 @@ def __abs__(self): return self def __mul__(self, other): - if not isinstance(other, (int, long)): + if not isinstance(other, int): return NotImplemented usec = self._to_microseconds() return timedelta._from_microseconds(usec * other) @@ -602,7 +602,7 @@ def __mul__(self, other): __rmul__ = __mul__ def __div__(self, other): - if not isinstance(other, (int, long)): + if not isinstance(other, int): return NotImplemented usec = self._to_microseconds() # return timedelta._from_microseconds(usec // other) @@ -657,7 +657,7 @@ def __hash__(self): self._hashcode = hash(self._getstate()) return self._hashcode - def __nonzero__(self): + def __bool__(self): return (self._days != 0 or self._seconds != 0 or self._microseconds != 0) @@ -787,7 +787,7 @@ def ctime(self): # return _wrap_strftime(self, format, self.timetuple()) def __format__(self, fmt): - if not isinstance(fmt, (str, unicode)): + if not isinstance(fmt, str): raise ValueError("__format__ expects str or unicode, not %s" % fmt.__class__.__name__) if len(fmt) != 0: @@ -1285,7 +1285,7 @@ def isoformat(self): # return _wrap_strftime(self, format, timetuple) def __format__(self, fmt): - if not isinstance(fmt, (str, unicode)): + if not isinstance(fmt, str): raise ValueError("__format__ expects str or unicode, not %s" % fmt.__class__.__name__) if len(fmt) != 0: @@ -1367,7 +1367,7 @@ def replace(self, hour=None, minute=None, second=None, microsecond=None, return time.__new__(type(self), hour, minute, second, microsecond, tzinfo) - def __nonzero__(self): + def __bool__(self): if self.second or self.microsecond: return True offset = self._utcoffset() or 0 diff --git a/grumpy-runtime-src/third_party/stdlib/StringIO.py b/grumpy-runtime-src/third_party/stdlib/StringIO.py index 8b3ffac7..72dcb200 100644 --- a/grumpy-runtime-src/third_party/stdlib/StringIO.py +++ b/grumpy-runtime-src/third_party/stdlib/StringIO.py @@ -38,7 +38,7 @@ def _complain_ifclosed(closed): if closed: - raise ValueError, "I/O operation on closed file" + raise ValueError("I/O operation on closed file") class StringIO(object): """class StringIO([buffer]) @@ -54,7 +54,7 @@ class StringIO(object): """ def __init__(self, buf = ''): # Force self.buf to be a string or unicode - if not isinstance(buf, basestring): + if not isinstance(buf, str): buf = str(buf) self.buf = buf self.len = len(buf) @@ -66,7 +66,7 @@ def __init__(self, buf = ''): def __iter__(self): return self - def next(self): + def __next__(self): """A file object is its own iterator, for example iter(f) returns f (unless f is closed). When a file is used as an iterator, typically in a for loop (for example, for line in f: print line), the next() @@ -214,7 +214,7 @@ def write(self, s): _complain_ifclosed(self.closed) if not s: return # Force s to be a string or unicode - if not isinstance(s, basestring): + if not isinstance(s, str): s = str(s) spos = self.pos slen = self.len @@ -289,36 +289,36 @@ def test(): f.write(line) f.writelines(lines[-2:]) if f.getvalue() != text: - raise RuntimeError, 'write failed' + raise RuntimeError('write failed') length = f.tell() - print 'File length =', length + print('File length =', length) f.seek(len(lines[0])) f.write(lines[1]) f.seek(0) - print 'First line =', repr(f.readline()) - print 'Position =', f.tell() + print('First line =', repr(f.readline())) + print('Position =', f.tell()) line = f.readline() - print 'Second line =', repr(line) + print('Second line =', repr(line)) f.seek(-len(line), 1) line2 = f.read(len(line)) if line != line2: - raise RuntimeError, 'bad result after seek back' + raise RuntimeError('bad result after seek back') f.seek(len(line2), 1) list = f.readlines() line = list[-1] f.seek(f.tell() - len(line)) line2 = f.read() if line != line2: - raise RuntimeError, 'bad result after seek back from EOF' - print 'Read', len(list), 'more lines' - print 'File length =', f.tell() + raise RuntimeError('bad result after seek back from EOF') + print('Read', len(list), 'more lines') + print('File length =', f.tell()) if f.tell() != length: - raise RuntimeError, 'bad length' + raise RuntimeError('bad length') f.truncate(length/2) f.seek(0, 2) - print 'Truncated length =', f.tell() + print('Truncated length =', f.tell()) if f.tell() != length/2: - raise RuntimeError, 'truncate did not adjust length' + raise RuntimeError('truncate did not adjust length') f.close() if __name__ == '__main__': diff --git a/grumpy-runtime-src/third_party/stdlib/UserDict.py b/grumpy-runtime-src/third_party/stdlib/UserDict.py index 09a8ec9c..b535ab9d 100644 --- a/grumpy-runtime-src/third_party/stdlib/UserDict.py +++ b/grumpy-runtime-src/third_party/stdlib/UserDict.py @@ -53,12 +53,12 @@ def copy(self): self.data = data c.update(self) return c - def keys(self): return self.data.keys() - def items(self): return self.data.items() - def iteritems(self): return self.data.iteritems() - def iterkeys(self): return self.data.iterkeys() - def itervalues(self): return self.data.itervalues() - def values(self): return self.data.values() + def keys(self): return list(self.data.keys()) + def items(self): return list(self.data.items()) + def iteritems(self): return iter(self.data.items()) + def iterkeys(self): return iter(self.data.keys()) + def itervalues(self): return iter(self.data.values()) + def values(self): return list(self.data.values()) def has_key(self, key): return key in self.data def update(*args, **kwargs): if not args: @@ -84,7 +84,7 @@ def update(*args, **kwargs): elif isinstance(dict, type({})) or not hasattr(dict, 'items'): self.data.update(dict) else: - for k, v in dict.items(): + for k, v in list(dict.items()): self[k] = v if len(kwargs): self.data.update(kwargs) @@ -128,7 +128,7 @@ class DictMixin(object): # second level definitions support higher levels def __iter__(self): - for k in self.keys(): + for k in list(self.keys()): yield k def has_key(self, key): try: @@ -137,7 +137,7 @@ def has_key(self, key): return False return True def __contains__(self, key): - return self.has_key(key) + return key in self # third level takes advantage of second level definitions def iteritems(self): @@ -148,14 +148,14 @@ def iterkeys(self): # fourth level uses definitions from lower levels def itervalues(self): - for _, v in self.iteritems(): + for _, v in self.items(): yield v def values(self): - return [v for _, v in self.iteritems()] + return [v for _, v in self.items()] def items(self): - return list(self.iteritems()) + return list(self.items()) def clear(self): - for key in self.keys(): + for key in list(self.keys()): del self[key] def setdefault(self, key, default=None): try: @@ -165,8 +165,8 @@ def setdefault(self, key, default=None): return default def pop(self, key, *args): if len(args) > 1: - raise TypeError, "pop expected at most 2 arguments, got "\ - + repr(1 + len(args)) + raise TypeError("pop expected at most 2 arguments, got "\ + + repr(1 + len(args))) try: value = self[key] except KeyError: @@ -177,9 +177,9 @@ def pop(self, key, *args): return value def popitem(self): try: - k, v = self.iteritems().next() + k, v = next(iter(self.items())) except StopIteration: - raise KeyError, 'container is empty' + raise KeyError('container is empty') del self[k] return (k, v) def update(self, other=None, **kwargs): @@ -187,10 +187,10 @@ def update(self, other=None, **kwargs): if other is None: pass elif hasattr(other, 'iteritems'): # iteritems saves memory and lookups - for k, v in other.iteritems(): + for k, v in other.items(): self[k] = v elif hasattr(other, 'keys'): - for k in other.keys(): + for k in list(other.keys()): self[k] = other[k] else: for k, v in other: @@ -203,12 +203,12 @@ def get(self, key, default=None): except KeyError: return default def __repr__(self): - return repr(dict(self.iteritems())) + return repr(dict(iter(self.items()))) def __cmp__(self, other): if other is None: return 1 if isinstance(other, DictMixin): - other = dict(other.iteritems()) - return cmp(dict(self.iteritems()), other) + other = dict(iter(other.items())) + return cmp(dict(iter(self.items())), other) def __len__(self): - return len(self.keys()) + return len(list(self.keys())) diff --git a/grumpy-runtime-src/third_party/stdlib/UserString.py b/grumpy-runtime-src/third_party/stdlib/UserString.py index 324a3294..8562af4c 100755 --- a/grumpy-runtime-src/third_party/stdlib/UserString.py +++ b/grumpy-runtime-src/third_party/stdlib/UserString.py @@ -12,7 +12,7 @@ class UserString(collections.Sequence): def __init__(self, seq): - if isinstance(seq, basestring): + if isinstance(seq, str): self.data = seq elif isinstance(seq, UserString): self.data = seq.data[:] @@ -21,7 +21,7 @@ def __init__(self, seq): def __str__(self): return str(self.data) def __repr__(self): return repr(self.data) def __int__(self): return int(self.data) - def __long__(self): return long(self.data) + def __long__(self): return int(self.data) def __float__(self): return float(self.data) def __complex__(self): return complex(self.data) def __hash__(self): return hash(self.data) @@ -43,12 +43,12 @@ def __getslice__(self, start, end): def __add__(self, other): if isinstance(other, UserString): return self.__class__(self.data + other.data) - elif isinstance(other, basestring): + elif isinstance(other, str): return self.__class__(self.data + other) else: return self.__class__(self.data + str(other)) def __radd__(self, other): - if isinstance(other, basestring): + if isinstance(other, str): return self.__class__(other + self.data) else: return self.__class__(str(other) + self.data) @@ -62,7 +62,7 @@ def __mod__(self, args): def capitalize(self): return self.__class__(self.data.capitalize()) def center(self, width, *args): return self.__class__(self.data.center(width, *args)) - def count(self, sub, start=0, end=sys.maxint): + def count(self, sub, start=0, end=sys.maxsize): return self.data.count(sub, start, end) def decode(self, encoding=None, errors=None): # XXX improve this? if encoding: @@ -80,13 +80,13 @@ def encode(self, encoding=None, errors=None): # XXX improve this? return self.__class__(self.data.encode(encoding)) else: return self.__class__(self.data.encode()) - def endswith(self, suffix, start=0, end=sys.maxint): + def endswith(self, suffix, start=0, end=sys.maxsize): return self.data.endswith(suffix, start, end) def expandtabs(self, tabsize=8): return self.__class__(self.data.expandtabs(tabsize)) - def find(self, sub, start=0, end=sys.maxint): + def find(self, sub, start=0, end=sys.maxsize): return self.data.find(sub, start, end) - def index(self, sub, start=0, end=sys.maxint): + def index(self, sub, start=0, end=sys.maxsize): return self.data.index(sub, start, end) def isalpha(self): return self.data.isalpha() def isalnum(self): return self.data.isalnum() @@ -106,9 +106,9 @@ def partition(self, sep): return self.data.partition(sep) def replace(self, old, new, maxsplit=-1): return self.__class__(self.data.replace(old, new, maxsplit)) - def rfind(self, sub, start=0, end=sys.maxint): + def rfind(self, sub, start=0, end=sys.maxsize): return self.data.rfind(sub, start, end) - def rindex(self, sub, start=0, end=sys.maxint): + def rindex(self, sub, start=0, end=sys.maxsize): return self.data.rindex(sub, start, end) def rjust(self, width, *args): return self.__class__(self.data.rjust(width, *args)) @@ -120,7 +120,7 @@ def split(self, sep=None, maxsplit=-1): def rsplit(self, sep=None, maxsplit=-1): return self.data.rsplit(sep, maxsplit) def splitlines(self, keepends=0): return self.data.splitlines(keepends) - def startswith(self, prefix, start=0, end=sys.maxint): + def startswith(self, prefix, start=0, end=sys.maxsize): return self.data.startswith(prefix, start, end) def strip(self, chars=None): return self.__class__(self.data.strip(chars)) def swapcase(self): return self.__class__(self.data.swapcase()) @@ -160,7 +160,7 @@ def __setitem__(self, index, sub): if isinstance(index, slice): if isinstance(sub, UserString): sub = sub.data - elif not isinstance(sub, basestring): + elif not isinstance(sub, str): sub = str(sub) start, stop, step = index.indices(len(self.data)) if step == -1: @@ -169,7 +169,7 @@ def __setitem__(self, index, sub): elif step != 1: # XXX(twouters): I guess we should be reimplementing # the extended slice assignment/deletion algorithm here... - raise TypeError, "invalid step in slicing assignment" + raise TypeError("invalid step in slicing assignment") start = min(start, stop) self.data = self.data[:start] + sub + self.data[stop:] else: @@ -184,7 +184,7 @@ def __delitem__(self, index): start, stop = stop+1, start+1 elif step != 1: # XXX(twouters): see same block in __setitem__ - raise TypeError, "invalid step in slicing deletion" + raise TypeError("invalid step in slicing deletion") start = min(start, stop) self.data = self.data[:start] + self.data[stop:] else: @@ -196,7 +196,7 @@ def __setslice__(self, start, end, sub): start = max(start, 0); end = max(end, 0) if isinstance(sub, UserString): self.data = self.data[:start]+sub.data+self.data[end:] - elif isinstance(sub, basestring): + elif isinstance(sub, str): self.data = self.data[:start]+sub+self.data[end:] else: self.data = self.data[:start]+str(sub)+self.data[end:] @@ -208,7 +208,7 @@ def immutable(self): def __iadd__(self, other): if isinstance(other, UserString): self.data += other.data - elif isinstance(other, basestring): + elif isinstance(other, str): self.data += other else: self.data += str(other) diff --git a/grumpy-runtime-src/third_party/stdlib/_abcoll.py b/grumpy-runtime-src/third_party/stdlib/_abcoll.py index 1edb8ee6..6ae52020 100644 --- a/grumpy-runtime-src/third_party/stdlib/_abcoll.py +++ b/grumpy-runtime-src/third_party/stdlib/_abcoll.py @@ -31,9 +31,7 @@ def _hasattr(C, attr): return hasattr(C, attr) -class Hashable(object): - __metaclass__ = ABCMeta - +class Hashable(object, metaclass=ABCMeta): @abstractmethod def __hash__(self): return 0 @@ -54,9 +52,7 @@ def __subclasshook__(cls, C): return NotImplemented -class Iterable(object): - __metaclass__ = ABCMeta - +class Iterable(object, metaclass=ABCMeta): @abstractmethod def __iter__(self): while False: @@ -90,9 +86,7 @@ def __subclasshook__(cls, C): return NotImplemented -class Sized(object): - __metaclass__ = ABCMeta - +class Sized(object, metaclass=ABCMeta): @abstractmethod def __len__(self): return 0 @@ -105,9 +99,7 @@ def __subclasshook__(cls, C): return NotImplemented -class Container(object): - __metaclass__ = ABCMeta - +class Container(object, metaclass=ABCMeta): @abstractmethod def __contains__(self, x): return False @@ -120,9 +112,7 @@ def __subclasshook__(cls, C): return NotImplemented -class Callable(object): - __metaclass__ = ABCMeta - +class Callable(object, metaclass=ABCMeta): @abstractmethod def __call__(self, *args, **kwds): return False @@ -261,7 +251,7 @@ def _hash(self): freedom for __eq__ or __hash__. We match the algorithm used by the built-in frozenset type. """ - MAX = sys.maxint + MAX = sys.maxsize MASK = 2 * MAX + 1 n = len(self) h = 1927868237 * (n + 1) @@ -425,7 +415,7 @@ def values(self): def __eq__(self, other): if not isinstance(other, Mapping): return NotImplemented - return dict(self.items()) == dict(other.items()) + return dict(list(self.items())) == dict(list(other.items())) def __ne__(self, other): return not (self == other) @@ -568,12 +558,12 @@ def update(*args, **kwds): for key in other: self[key] = other[key] elif hasattr(other, "keys"): - for key in other.keys(): + for key in list(other.keys()): self[key] = other[key] else: for key, value in other: self[key] = value - for key, value in kwds.items(): + for key, value in list(kwds.items()): self[key] = value def setdefault(self, key, default=None): @@ -618,7 +608,7 @@ def __contains__(self, value): return False def __reversed__(self): - for i in reversed(range(len(self))): + for i in reversed(list(range(len(self)))): yield self[i] def index(self, value): @@ -635,7 +625,7 @@ def count(self, value): return sum(1 for v in self if v == value) Sequence.register(tuple) -Sequence.register(basestring) +Sequence.register(str) #Sequence.register(buffer) Sequence.register(xrange) diff --git a/grumpy-runtime-src/third_party/stdlib/abc.py b/grumpy-runtime-src/third_party/stdlib/abc.py index e4b3f548..39fb71da 100644 --- a/grumpy-runtime-src/third_party/stdlib/abc.py +++ b/grumpy-runtime-src/third_party/stdlib/abc.py @@ -87,7 +87,7 @@ def __new__(mcls, name, bases, namespace): cls = super(ABCMeta, mcls).__new__(mcls, name, bases, namespace) # Compute set of abstract method names abstracts = set(name - for name, value in namespace.items() + for name, value in list(namespace.items()) if getattr(value, "__isabstractmethod__", False)) for base in bases: for name in getattr(base, "__abstractmethods__", set()): @@ -118,12 +118,12 @@ def register(cls, subclass): def _dump_registry(cls, file=None): """Debug helper to print the ABC registry.""" - print >> file, "Class: %s.%s" % (cls.__module__, cls.__name__) - print >> file, "Inv.counter: %s" % ABCMeta._abc_invalidation_counter + print("Class: %s.%s" % (cls.__module__, cls.__name__), file=file) + print("Inv.counter: %s" % ABCMeta._abc_invalidation_counter, file=file) for name in sorted(cls.__dict__.keys()): if name.startswith("_abc_"): value = getattr(cls, name) - print >> file, "%s: %r" % (name, value) + print("%s: %r" % (name, value), file=file) def __instancecheck__(cls, instance): """Override for isinstance(instance, cls).""" diff --git a/grumpy-runtime-src/third_party/stdlib/argparse.py b/grumpy-runtime-src/third_party/stdlib/argparse.py index 92b4f63a..0acc4876 100644 --- a/grumpy-runtime-src/third_party/stdlib/argparse.py +++ b/grumpy-runtime-src/third_party/stdlib/argparse.py @@ -1154,7 +1154,7 @@ def __call__(self, parser, namespace, values, option_string=None): # namespace for the relevant parts. subnamespace, arg_strings = parser.parse_known_args(arg_strings, None) # for key, value in vars(subnamespace).items(): - for key, value in subnamespace.__dict__.items(): + for key, value in list(subnamespace.__dict__.items()): setattr(namespace, key, value) if arg_strings: @@ -2045,7 +2045,7 @@ def consume_positionals(start_index): # twice (which may fail) if the argument was given, but # only if it was defined already in the namespace if (action.default is not None and - isinstance(action.default, basestring) and + isinstance(action.default, str) and hasattr(namespace, action.dest) and action.default is getattr(namespace, action.dest)): setattr(namespace, action.dest, @@ -2298,7 +2298,7 @@ def _get_values(self, action, arg_strings): value = action.const else: value = action.default - if isinstance(value, basestring): + if isinstance(value, str): value = self._get_value(action, value) self._check_value(action, value) diff --git a/grumpy-runtime-src/third_party/stdlib/base64.py b/grumpy-runtime-src/third_party/stdlib/base64.py index 8996a4f2..3e3caeb3 100755 --- a/grumpy-runtime-src/third_party/stdlib/base64.py +++ b/grumpy-runtime-src/third_party/stdlib/base64.py @@ -33,7 +33,7 @@ def _translate(s, altchars): translation = _translation[:] - for k, v in altchars.items(): + for k, v in list(altchars.items()): translation[ord(k)] = v return s.translate(''.join(translation)) @@ -74,7 +74,7 @@ def b64decode(s, altchars=None): s = s.translate(string.maketrans(altchars[:2], '+/')) try: return binascii.a2b_base64(s) - except binascii.Error, msg: + except binascii.Error as msg: # Transform this exception for consistency raise TypeError(msg) @@ -134,10 +134,10 @@ def urlsafe_b64decode(s): 8: 'I', 17: 'R', 26: '2', } -_b32tab = _b32alphabet.items() +_b32tab = list(_b32alphabet.items()) _b32tab.sort() _b32tab = [v for k, v in _b32tab] -_b32rev = dict([(v, long(k)) for k, v in _b32alphabet.items()]) +_b32rev = dict([(v, int(k)) for k, v in list(_b32alphabet.items())]) def b32encode(s): @@ -336,13 +336,13 @@ def test(): import sys, getopt try: opts, args = getopt.getopt(sys.argv[1:], 'deut') - except getopt.error, msg: + except getopt.error as msg: sys.stdout = sys.stderr - print msg - print """usage: %s [-d|-e|-u|-t] [file|-] + print(msg) + print("""usage: %s [-d|-e|-u|-t] [file|-] -d, -u: decode -e: encode (default) - -t: encode and decode string 'Aladdin:open sesame'"""%sys.argv[0] + -t: encode and decode string 'Aladdin:open sesame'"""%sys.argv[0]) sys.exit(2) func = encode for o, a in opts: @@ -361,7 +361,7 @@ def test1(): s0 = "Aladdin:open sesame" s1 = encodestring(s0) s2 = decodestring(s1) - print s0, repr(s1), s2 + print(s0, repr(s1), s2) if __name__ == '__main__': diff --git a/grumpy-runtime-src/third_party/stdlib/collections.py b/grumpy-runtime-src/third_party/stdlib/collections.py index 7afd8346..eab0e45e 100644 --- a/grumpy-runtime-src/third_party/stdlib/collections.py +++ b/grumpy-runtime-src/third_party/stdlib/collections.py @@ -35,8 +35,8 @@ _imap = itertools.imap #try: -import thread -_get_ident = thread.get_ident +import _thread +_get_ident = _thread.get_ident #except ImportError: # from dummy_thread import get_ident as _get_ident @@ -197,7 +197,7 @@ def __repr__(self, _repr_running={}): try: if not self: return '%s()' % (self.__class__.__name__,) - return '%s(%r)' % (self.__class__.__name__, self.items()) + return '%s(%r)' % (self.__class__.__name__, list(self.items())) finally: del _repr_running[call_key] @@ -501,8 +501,8 @@ def most_common(self, n=None): ''' # Emulate Bag.sortedByCount from Smalltalk if n is None: - return sorted(self.iteritems(), key=_itemgetter(1), reverse=True) - return _heapq.nlargest(n, self.iteritems(), key=_itemgetter(1)) + return sorted(iter(self.items()), key=_itemgetter(1), reverse=True) + return _heapq.nlargest(n, iter(self.items()), key=_itemgetter(1)) def elements(self): '''Iterator over elements repeating each as many times as its count. @@ -524,7 +524,7 @@ def elements(self): ''' # Emulate Bag.do from Smalltalk and Multiset.begin from C++. - return _chain.from_iterable(_starmap(_repeat, self.iteritems())) + return _chain.from_iterable(_starmap(_repeat, iter(self.items()))) # Override dict methods where necessary @@ -567,7 +567,7 @@ def update(*args, **kwds): if isinstance(iterable, Mapping): if self: self_get = self.get - for elem, count in iterable.iteritems(): + for elem, count in iterable.items(): self[elem] = self_get(elem, 0) + count else: super(Counter, self).update(iterable) # fast path when counter is empty @@ -605,7 +605,7 @@ def subtract(*args, **kwds): if iterable is not None: self_get = self.get if isinstance(iterable, Mapping): - for elem, count in iterable.items(): + for elem, count in list(iterable.items()): self[elem] = self_get(elem, 0) - count else: for elem in iterable: @@ -650,11 +650,11 @@ def __add__(self, other): if not isinstance(other, Counter): return NotImplemented result = Counter() - for elem, count in self.items(): + for elem, count in list(self.items()): newcount = count + other[elem] if newcount > 0: result[elem] = newcount - for elem, count in other.items(): + for elem, count in list(other.items()): if elem not in self and count > 0: result[elem] = count return result @@ -669,11 +669,11 @@ def __sub__(self, other): if not isinstance(other, Counter): return NotImplemented result = Counter() - for elem, count in self.items(): + for elem, count in list(self.items()): newcount = count - other[elem] if newcount > 0: result[elem] = newcount - for elem, count in other.items(): + for elem, count in list(other.items()): if elem not in self and count < 0: result[elem] = 0 - count return result @@ -688,12 +688,12 @@ def __or__(self, other): if not isinstance(other, Counter): return NotImplemented result = Counter() - for elem, count in self.items(): + for elem, count in list(self.items()): other_count = other[elem] newcount = other_count if count < other_count else count if newcount > 0: result[elem] = newcount - for elem, count in other.items(): + for elem, count in list(other.items()): if elem not in self and count > 0: result[elem] = count return result @@ -708,7 +708,7 @@ def __and__(self, other): if not isinstance(other, Counter): return NotImplemented result = Counter() - for elem, count in self.items(): + for elem, count in list(self.items()): other_count = other[elem] newcount = count if count < other_count else other_count if newcount > 0: diff --git a/grumpy-runtime-src/third_party/stdlib/contextlib.py b/grumpy-runtime-src/third_party/stdlib/contextlib.py index 42d22d0a..13395de3 100644 --- a/grumpy-runtime-src/third_party/stdlib/contextlib.py +++ b/grumpy-runtime-src/third_party/stdlib/contextlib.py @@ -19,14 +19,14 @@ def __init__(self, gen): def __enter__(self): try: - return self.gen.next() + return next(self.gen) except StopIteration: raise RuntimeError("generator didn't yield") def __exit__(self, t, value, tb): if t is None: try: - self.gen.next() + next(self.gen) except StopIteration: return else: @@ -40,7 +40,7 @@ def __exit__(self, t, value, tb): # self.gen.throw(t, value, traceback) # raise RuntimeError("generator didn't stop after throw()") raise t(value) - except StopIteration, exc: + except StopIteration as exc: # Suppress the exception *unless* it's the same exception that # was passed to throw(). This prevents a StopIteration # raised inside the "with" statement from being suppressed @@ -132,7 +132,7 @@ def nested(*managers): # Don't rely on sys.exc_info() still containing # the right information. Another exception may # have been raised and caught by an exit method - raise exc[0], exc[1], exc[2] + raise exc[0](exc[1]).with_traceback(exc[2]) class closing(object): diff --git a/grumpy-runtime-src/third_party/stdlib/copy_reg.py b/grumpy-runtime-src/third_party/stdlib/copy_reg.py index cd28b5c7..0ddb3d26 100644 --- a/grumpy-runtime-src/third_party/stdlib/copy_reg.py +++ b/grumpy-runtime-src/third_party/stdlib/copy_reg.py @@ -67,7 +67,7 @@ def _reduce_ex(self, proto): state = None else: if base is self.__class__: - raise TypeError, "can't pickle %s objects" % base.__name__ + raise TypeError("can't pickle %s objects" % base.__name__) state = base(self) args = (self.__class__, base, state) try: @@ -119,7 +119,7 @@ class found there. (This assumes classes don't modify their if "__slots__" in c.__dict__: slots = c.__dict__['__slots__'] # if class has a single slot, it can be given as a string - if isinstance(slots, basestring): + if isinstance(slots, str): slots = (slots,) for name in slots: # special descriptors @@ -158,7 +158,7 @@ def add_extension(module, name, code): """Register an extension code.""" code = int(code) if not 1 <= code <= 0x7fffffff: - raise ValueError, "code out of range" + raise ValueError("code out of range") key = (module, name) if (_extension_registry.get(key) == code and _inverted_registry.get(code) == key): diff --git a/grumpy-runtime-src/third_party/stdlib/csv.py b/grumpy-runtime-src/third_party/stdlib/csv.py index d3b2db75..66a7a681 100644 --- a/grumpy-runtime-src/third_party/stdlib/csv.py +++ b/grumpy-runtime-src/third_party/stdlib/csv.py @@ -5,6 +5,7 @@ import re import functools +from functools import reduce reduce = functools.reduce # from functools import reduce @@ -21,7 +22,7 @@ # from _csv import Dialect as _Dialect _Dialect = _csv.Dialect -import StringIO as _StringIO +import io as _StringIO StringIO = _StringIO.StringIO # try: # from cStringIO import StringIO @@ -61,7 +62,7 @@ def __init__(self): def _validate(self): try: _Dialect(self) - except TypeError, e: + except TypeError as e: # We do this for compatibility with py2.3 raise Error(str(e)) @@ -98,7 +99,7 @@ def __iter__(self): def fieldnames(self): if self._fieldnames is None: try: - self._fieldnames = self.reader.next() + self._fieldnames = next(self.reader) except StopIteration: pass self.line_num = self.reader.line_num @@ -113,19 +114,19 @@ def fieldnames(self): def fieldnames(self, value): self._fieldnames = value - def next(self): + def __next__(self): if self.line_num == 0: # Used only for its side effect. self.fieldnames - row = self.reader.next() + row = next(self.reader) self.line_num = self.reader.line_num # unlike the basic reader, we prefer not to return blanks, # because we will typically wind up with a dict full of None # values while row == []: - row = self.reader.next() - d = dict(zip(self.fieldnames, row)) + row = next(self.reader) + d = dict(list(zip(self.fieldnames, row))) lf = len(self.fieldnames) lr = len(row) if lf < lr: @@ -142,14 +143,13 @@ def __init__(self, f, fieldnames, restval="", extrasaction="raise", self.fieldnames = fieldnames # list of keys for the dict self.restval = restval # for writing short dicts if extrasaction.lower() not in ("raise", "ignore"): - raise ValueError, \ - ("extrasaction (%s) must be 'raise' or 'ignore'" % + raise ValueError("extrasaction (%s) must be 'raise' or 'ignore'" % extrasaction) self.extrasaction = extrasaction self.writer = writer(f, dialect, *args, **kwds) def writeheader(self): - header = dict(zip(self.fieldnames, self.fieldnames)) + header = dict(list(zip(self.fieldnames, self.fieldnames))) self.writerow(header) def _dict_to_list(self, rowdict): @@ -198,7 +198,7 @@ def sniff(self, sample, delimiters=None): delimiters) if not delimiter: - raise Error, "Could not determine delimiter" + raise Error("Could not determine delimiter") class dialect(Dialect): _name = "sniffed" @@ -263,11 +263,11 @@ def _guess_quote_and_delimiter(self, data, delimiters): spaces += 1 quotechar = reduce(lambda a, b, quotes = quotes: - (quotes[a] > quotes[b]) and a or b, quotes.keys()) + (quotes[a] > quotes[b]) and a or b, list(quotes.keys())) if delims: delim = reduce(lambda a, b, delims = delims: - (delims[a] > delims[b]) and a or b, delims.keys()) + (delims[a] > delims[b]) and a or b, list(delims.keys())) skipinitialspace = delims[delim] == spaces if delim == '\n': # most likely a file with a single column delim = '' @@ -311,7 +311,7 @@ def _guess_delimiter(self, data, delimiters): additional chunks as necessary. """ - data = filter(None, data.split('\n')) + data = [_f for _f in data.split('\n') if _f] ascii = [chr(c) for c in range(127)] # 7-bit ASCII @@ -333,8 +333,8 @@ def _guess_delimiter(self, data, delimiters): metaFrequency[freq] = metaFrequency.get(freq, 0) + 1 charFrequency[char] = metaFrequency - for char in charFrequency.keys(): - items = charFrequency[char].items() + for char in list(charFrequency.keys()): + items = list(charFrequency[char].items()) if len(items) == 1 and items[0][0] == 0: continue # get the mode of the frequencies @@ -351,7 +351,7 @@ def _guess_delimiter(self, data, delimiters): modes[char] = items[0] # build a list of possible delimiters - modeList = modes.items() + modeList = list(modes.items()) total = float(chunkLength * iteration) # (rows of consistent data) / (number of rows) = 100% consistency = 1.0 @@ -366,7 +366,7 @@ def _guess_delimiter(self, data, delimiters): consistency -= 0.01 if len(delims) == 1: - delim = delims.keys()[0] + delim = list(delims.keys())[0] skipinitialspace = (data[0].count(delim) == data[0].count("%c " % delim)) return (delim, skipinitialspace) @@ -381,14 +381,14 @@ def _guess_delimiter(self, data, delimiters): # if there's more than one, fall back to a 'preferred' list if len(delims) > 1: for d in self.preferred: - if d in delims.keys(): + if d in list(delims.keys()): skipinitialspace = (data[0].count(d) == data[0].count("%c " % d)) return (d, skipinitialspace) # nothing else indicates a preference, pick the character that # dominates(?) - items = [(v,k) for (k,v) in delims.items()] + items = [(v,k) for (k,v) in list(delims.items())] items.sort() delim = items[-1][1] @@ -409,7 +409,7 @@ def has_header(self, sample): rdr = reader(StringIO(sample), self.sniff(sample)) - header = rdr.next() # assume first row is header + header = next(rdr) # assume first row is header columns = len(header) columnTypes = {} @@ -425,9 +425,9 @@ def has_header(self, sample): if len(row) != columns: continue # skip rows that have irregular number of columns - for col in columnTypes.keys(): + for col in list(columnTypes.keys()): - for thisType in [int, long, float, complex]: + for thisType in [int, int, float, complex]: try: thisType(row[col]) break @@ -438,7 +438,7 @@ def has_header(self, sample): thisType = len(row[col]) # treat longs as ints - if thisType == long: + if thisType == int: thisType = int if thisType != columnTypes[col]: @@ -452,7 +452,7 @@ def has_header(self, sample): # finally, compare results against first row and "vote" # on whether it's a header hasHeader = 0 - for col, colType in columnTypes.items(): + for col, colType in list(columnTypes.items()): if type(colType) == type(0): # it's a length if len(header[col]) != colType: hasHeader += 1 diff --git a/grumpy-runtime-src/third_party/stdlib/difflib.py b/grumpy-runtime-src/third_party/stdlib/difflib.py index 7fda38fe..04dff574 100644 --- a/grumpy-runtime-src/third_party/stdlib/difflib.py +++ b/grumpy-runtime-src/third_party/stdlib/difflib.py @@ -34,6 +34,7 @@ # from collections import namedtuple as _namedtuple # from functools import reduce import functools +from functools import reduce reduce = functools.reduce import operator @@ -73,13 +74,13 @@ def __repr__(self): def _asdict(self): 'Return a new OrderedDict which maps field names to their values' - return OrderedDict(zip(self._fields, self)) + return OrderedDict(list(zip(self._fields, self))) def _replace(_self, **kwds): 'Return a new Match object replacing specified fields with new values' - result = _self._make(map(kwds.pop, ('a', 'b', 'size'), _self)) + result = _self._make(list(map(kwds.pop, ('a', 'b', 'size'), _self))) if kwds: - raise ValueError('Got unexpected field names: %r' % kwds.keys()) + raise ValueError('Got unexpected field names: %r' % list(kwds.keys())) return result def __getnewargs__(self): @@ -471,7 +472,7 @@ def find_longest_match(self, alo, ahi, blo, bhi): # 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 @@ -586,7 +587,7 @@ def get_matching_blocks(self): non_adjacent.append((i1, j1, k1)) non_adjacent.append( (la, lb, 0) ) - self.matching_blocks = map(Match._make, non_adjacent) + self.matching_blocks = list(map(Match._make, non_adjacent)) return self.matching_blocks def get_opcodes(self): @@ -978,14 +979,14 @@ def compare(self, a, b): elif tag == 'equal': g = self._dump(' ', a, alo, ahi) else: - raise ValueError, 'unknown tag %r' % (tag,) + raise ValueError('unknown tag %r' % (tag,)) for line in g: yield line 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): @@ -1031,10 +1032,10 @@ def _fancy_replace(self, a, alo, ahi, b, blo, bhi): # 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: @@ -1090,7 +1091,7 @@ def _fancy_replace(self, a, alo, ahi, b, blo, bhi): atags += ' ' * la btags += ' ' * lb else: - raise ValueError, 'unknown tag %r' % (tag,) + raise ValueError('unknown tag %r' % (tag,)) for line in self._qformat(aelt, belt, atags, btags): yield line else: @@ -1544,7 +1545,7 @@ def _line_iterator(): # so we can do some very readable comparisons. while len(lines) < 4: try: - lines.append(diff_lines_iterator.next()) + lines.append(next(diff_lines_iterator)) except StopIteration: lines.append('X') s = ''.join([line[0] for line in lines]) @@ -1631,7 +1632,7 @@ def _line_pair_iterator(): while True: # Collecting lines of text until we have a from/to pair while (len(fromlines)==0 or len(tolines)==0): - from_line, to_line, found_diff =line_iterator.next() + from_line, to_line, found_diff =next(line_iterator) if from_line is not None: fromlines.append((from_line,found_diff)) if to_line is not None: @@ -1646,7 +1647,7 @@ def _line_pair_iterator(): line_pair_iterator = _line_pair_iterator() if context is None: while True: - yield line_pair_iterator.next() + yield next(line_pair_iterator) # Handle case where user wants context differencing. We must do some # storage of lines until we know for sure that they are to be yielded. else: @@ -1659,7 +1660,7 @@ def _line_pair_iterator(): index, contextLines = 0, [None]*(context) found_diff = False while(found_diff is False): - from_line, to_line, found_diff = line_pair_iterator.next() + from_line, to_line, found_diff = next(line_pair_iterator) i = index % context contextLines[i] = (from_line, to_line, found_diff) index += 1 @@ -1679,7 +1680,7 @@ def _line_pair_iterator(): # Now yield the context lines after the change lines_to_write = context-1 while(lines_to_write): - from_line, to_line, found_diff = line_pair_iterator.next() + from_line, to_line, found_diff = next(line_pair_iterator) # If another change within the context, extend the context if found_diff: lines_to_write = context-1 @@ -2119,7 +2120,7 @@ def restore(delta, which): try: tag = {1: "- ", 2: "+ "}[int(which)] except KeyError: - raise ValueError, ('unknown delta choice (must be 1 or 2): %r' + raise ValueError('unknown delta choice (must be 1 or 2): %r' % which) prefixes = (" ", tag) for line in delta: diff --git a/grumpy-runtime-src/third_party/stdlib/fpformat.py b/grumpy-runtime-src/third_party/stdlib/fpformat.py index 71cbb25f..fd4d7114 100644 --- a/grumpy-runtime-src/third_party/stdlib/fpformat.py +++ b/grumpy-runtime-src/third_party/stdlib/fpformat.py @@ -39,7 +39,7 @@ def extract(s): fraction is 0 or more digits expo is an integer""" res = decoder.match(s) - if res is None: raise NotANumber, s + if res is None: raise NotANumber(s) sign, intpart, fraction, exppart = res.group(1,2,3,4) if sign == '+': sign = '' if fraction: fraction = fraction[1:] @@ -139,7 +139,7 @@ def test(): """Interactive test run.""" try: while 1: - x, digs = input('Enter (x, digs): ') - print x, fix(x, digs), sci(x, digs) + x, digs = eval(input('Enter (x, digs): ')) + print(x, fix(x, digs), sci(x, digs)) except (EOFError, KeyboardInterrupt): pass diff --git a/grumpy-runtime-src/third_party/stdlib/genericpath.py b/grumpy-runtime-src/third_party/stdlib/genericpath.py index 2648e545..73d019c9 100644 --- a/grumpy-runtime-src/third_party/stdlib/genericpath.py +++ b/grumpy-runtime-src/third_party/stdlib/genericpath.py @@ -11,7 +11,7 @@ try: - _unicode = unicode + _unicode = str except NameError: # If Python is built without Unicode support, the unicode type # will not exist. Fake one. diff --git a/grumpy-runtime-src/third_party/stdlib/getopt.py b/grumpy-runtime-src/third_party/stdlib/getopt.py index 084aadb5..79575f67 100644 --- a/grumpy-runtime-src/third_party/stdlib/getopt.py +++ b/grumpy-runtime-src/third_party/stdlib/getopt.py @@ -207,4 +207,4 @@ def short_has_arg(opt, shortopts): if __name__ == '__main__': import sys - print getopt(sys.argv[1:], "a:b", ["alpha=", "beta"]) + print(getopt(sys.argv[1:], "a:b", ["alpha=", "beta"])) diff --git a/grumpy-runtime-src/third_party/stdlib/glob.py b/grumpy-runtime-src/third_party/stdlib/glob.py index 97e1b9e2..6efc70d2 100644 --- a/grumpy-runtime-src/third_party/stdlib/glob.py +++ b/grumpy-runtime-src/third_party/stdlib/glob.py @@ -6,7 +6,7 @@ import fnmatch try: - _unicode = unicode + _unicode = str except NameError: # If Python is built without Unicode support, the unicode type # will not exist. Fake one. @@ -71,8 +71,8 @@ def iglob(pathname): def glob1(dirname, pattern): if not dirname: dirname = os.curdir - if isinstance(pattern, _unicode) and not isinstance(dirname, unicode): - dirname = unicode(dirname, sys.getfilesystemencoding() or + if isinstance(pattern, _unicode) and not isinstance(dirname, str): + dirname = str(dirname, sys.getfilesystemencoding() or sys.getdefaultencoding()) try: names = os.listdir(dirname) diff --git a/grumpy-runtime-src/third_party/stdlib/heapq.py b/grumpy-runtime-src/third_party/stdlib/heapq.py index 3c15cbd0..b76ee38b 100644 --- a/grumpy-runtime-src/third_party/stdlib/heapq.py +++ b/grumpy-runtime-src/third_party/stdlib/heapq.py @@ -191,7 +191,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 _heappushpop_max(heap, item): @@ -204,7 +204,7 @@ def _heappushpop_max(heap, item): def _heapify_max(x): """Transform list into a maxheap, in-place, in O(len(x)) time.""" n = len(x) - for i in reversed(range(n//2)): + for i in reversed(list(range(n//2))): _siftup_max(x, i) def nlargest(n, iterable): @@ -379,7 +379,7 @@ def merge(*iterables): h_append = h.append for itnum, it in enumerate(map(iter, iterables)): try: - next = it.next + next = it.__next__ h_append([next(), itnum, next]) except _StopIteration: pass @@ -429,15 +429,15 @@ def nsmallest(n, iterable, key=None): # When key is none, use simpler decoration if key is None: - it = izip(iterable, count()) # decorate + it = zip(iterable, count()) # decorate result = _nsmallest(n, it) - return map(itemgetter(0), result) # undecorate + return list(map(itemgetter(0), result)) # undecorate # General case, slowest method in1, in2 = tee(iterable) - it = izip(imap(key, in1), count(), in2) # decorate + it = zip(map(key, in1), count(), in2) # decorate result = _nsmallest(n, it) - return map(itemgetter(2), result) # undecorate + return list(map(itemgetter(2), result)) # undecorate _nlargest = nlargest def nlargest(n, iterable, key=None): @@ -467,15 +467,15 @@ def nlargest(n, iterable, key=None): # When key is none, use simpler decoration if key is None: - it = izip(iterable, count(0,-1)) # decorate + it = zip(iterable, count(0,-1)) # decorate result = _nlargest(n, it) - return map(itemgetter(0), result) # undecorate + return list(map(itemgetter(0), result)) # undecorate # General case, slowest method in1, in2 = tee(iterable) - it = izip(imap(key, in1), count(0,-1), in2) # decorate + it = zip(map(key, in1), count(0,-1), in2) # decorate result = _nlargest(n, it) - return map(itemgetter(2), result) # undecorate + return list(map(itemgetter(2), result)) # undecorate #if __name__ == "__main__": # # Simple sanity test diff --git a/grumpy-runtime-src/third_party/stdlib/linecache.py b/grumpy-runtime-src/third_party/stdlib/linecache.py index 4b97be3f..35daa0b8 100644 --- a/grumpy-runtime-src/third_party/stdlib/linecache.py +++ b/grumpy-runtime-src/third_party/stdlib/linecache.py @@ -49,7 +49,7 @@ def checkcache(filename=None): (This is not checked upon each call!)""" if filename is None: - filenames = cache.keys() + filenames = list(cache.keys()) else: if filename in cache: filenames = [filename] diff --git a/grumpy-runtime-src/third_party/stdlib/mimetools.py b/grumpy-runtime-src/third_party/stdlib/mimetools.py index 30e2ce9d..0eb589d7 100644 --- a/grumpy-runtime-src/third_party/stdlib/mimetools.py +++ b/grumpy-runtime-src/third_party/stdlib/mimetools.py @@ -105,10 +105,10 @@ def getsubtype(self): # ----------------- #try: -import thread +import _thread #except ImportError: # import dummy_thread as thread -_counter_lock = thread.allocate_lock() +_counter_lock = _thread.allocate_lock() del thread _counter = 0 @@ -170,8 +170,7 @@ def decode(input, output, encoding): if encoding in decodetab: pipethrough(input, decodetab[encoding], output) else: - raise ValueError, \ - 'unknown Content-Transfer-Encoding: %s' % encoding + raise ValueError('unknown Content-Transfer-Encoding: %s' % encoding) def encode(input, output, encoding): """Encode common content-transfer-encodings (base64, quopri, uuencode).""" @@ -189,8 +188,7 @@ def encode(input, output, encoding): if encoding in encodetab: pipethrough(input, encodetab[encoding], output) else: - raise ValueError, \ - 'unknown Content-Transfer-Encoding: %s' % encoding + raise ValueError('unknown Content-Transfer-Encoding: %s' % encoding) # The following is no longer used for standard encodings diff --git a/grumpy-runtime-src/third_party/stdlib/optparse.py b/grumpy-runtime-src/third_party/stdlib/optparse.py index aac7f6ef..81cac294 100644 --- a/grumpy-runtime-src/third_party/stdlib/optparse.py +++ b/grumpy-runtime-src/third_party/stdlib/optparse.py @@ -253,10 +253,10 @@ def dedent(self): self.level -= 1 def format_usage(self, usage): - raise NotImplementedError, "subclasses must implement" + raise NotImplementedError("subclasses must implement") def format_heading(self, heading): - raise NotImplementedError, "subclasses must implement" + raise NotImplementedError("subclasses must implement") def _format_text(self, text): """ @@ -428,7 +428,7 @@ def _parse_int(val): return _parse_num(val, int) def _parse_long(val): - return _parse_num(val, long) + return _parse_num(val, int) _builtin_cvt = { "int" : (_parse_int, _("integer")), "long" : (_parse_long, _("long integer")), @@ -633,7 +633,7 @@ def _set_attrs(self, attrs): else: setattr(self, attr, None) if attrs: - attrs = attrs.keys() + attrs = list(attrs.keys()) attrs.sort() raise OptionError( "invalid keyword arguments: %s" % ", ".join(attrs), @@ -663,8 +663,8 @@ def _check_type(self): # complicated check of __builtin__ is only necessary for # Python 2.1 and earlier, and is short-circuited by the # first check on modern Pythons.) - import __builtin__ - if ( type(self.type) is types.TypeType or + import builtins + if ( type(self.type) is type or (hasattr(self.type, "__name__") and getattr(__builtin__, self.type.__name__, None) is self.type) ): self.type = self.type.__name__ @@ -683,7 +683,7 @@ def _check_choice(self): if self.choices is None: raise OptionError( "must supply a list of choices for type 'choice'", self) - elif type(self.choices) not in (types.TupleType, types.ListType): + elif type(self.choices) not in (tuple, list): raise OptionError( "choices must be a list of strings ('%s' supplied)" % str(type(self.choices)).split("'")[1], self) @@ -728,12 +728,12 @@ def _check_callback(self): raise OptionError( "callback not callable: %r" % self.callback, self) if (self.callback_args is not None and - type(self.callback_args) is not types.TupleType): + type(self.callback_args) is not tuple): raise OptionError( "callback_args, if supplied, must be a tuple: not %r" % self.callback_args, self) if (self.callback_kwargs is not None and - type(self.callback_kwargs) is not types.DictType): + type(self.callback_kwargs) is not dict): raise OptionError( "callback_kwargs, if supplied, must be a dict: not %r" % self.callback_kwargs, self) @@ -841,19 +841,19 @@ def take_action(self, action, dest, opt, value, values, parser): SUPPRESS_USAGE = "SUPPRESS"+"USAGE" try: - basestring + str except NameError: def isbasestring(x): - return isinstance(x, (types.StringType, types.UnicodeType)) + return isinstance(x, (bytes, str)) else: def isbasestring(x): - return isinstance(x, basestring) + return isinstance(x, str) class Values(object): def __init__(self, defaults=None): if defaults: - for (attr, val) in defaults.items(): + for (attr, val) in list(defaults.items()): setattr(self, attr, val) def __str__(self): @@ -864,7 +864,7 @@ def __str__(self): def __cmp__(self, other): if isinstance(other, Values): return cmp(self.__dict__, other.__dict__) - elif isinstance(other, types.DictType): + elif isinstance(other, dict): return cmp(self.__dict__, other) else: return -1 @@ -896,7 +896,7 @@ def _update(self, dict, mode): elif mode == "loose": self._update_loose(dict) else: - raise ValueError, "invalid update mode: %r" % mode + raise ValueError("invalid update mode: %r" % mode) def read_module(self, modname, mode="careful"): __import__(modname) @@ -905,7 +905,7 @@ def read_module(self, modname, mode="careful"): def read_file(self, filename, mode="careful"): vars = {} - execfile(filename, vars) + exec(compile(open(filename).read(), filename, 'exec'), vars) self._update(vars, mode) def ensure_value(self, attr, value): @@ -975,7 +975,7 @@ def _share_option_mappings(self, parser): def set_conflict_handler(self, handler): if handler not in ("error", "resolve"): - raise ValueError, "invalid conflict_resolution value %r" % handler + raise ValueError("invalid conflict_resolution value %r" % handler) self.conflict_handler = handler def set_description(self, description): @@ -1025,14 +1025,14 @@ def add_option(self, *args, **kwargs): """add_option(Option) add_option(opt_str, ..., kwarg=val, ...) """ - if type(args[0]) in types.StringTypes: + if type(args[0]) in (str,): option = self.option_class(*args, **kwargs) elif len(args) == 1 and not kwargs: option = args[0] if not isinstance(option, Option): - raise TypeError, "not an Option instance: %r" % option + raise TypeError("not an Option instance: %r" % option) else: - raise TypeError, "invalid arguments" + raise TypeError("invalid arguments") self._check_conflict(option) @@ -1353,16 +1353,16 @@ def get_default_values(self): def add_option_group(self, *args, **kwargs): # XXX lots of overlap with OptionContainer.add_option() - if type(args[0]) is types.StringType: + if type(args[0]) is bytes: group = OptionGroup(self, *args, **kwargs) elif len(args) == 1 and not kwargs: group = args[0] if not isinstance(group, OptionGroup): - raise TypeError, "not an OptionGroup instance: %r" % group + raise TypeError("not an OptionGroup instance: %r" % group) if group.parser is not self: - raise ValueError, "invalid OptionGroup (wrong parser)" + raise ValueError("invalid OptionGroup (wrong parser)") else: - raise TypeError, "invalid arguments" + raise TypeError("invalid arguments") self.option_groups.append(group) return group @@ -1416,7 +1416,7 @@ def parse_args(self, args=None, values=None): try: stop = self._process_args(largs, rargs, values) - except (BadOptionError, OptionValueError), err: + except (BadOptionError, OptionValueError) as err: self.error(str(err)) args = largs + rargs @@ -1629,7 +1629,7 @@ def print_usage(self, file=None): or not defined. """ if self.usage: - print >>file, self.get_usage() + print(self.get_usage(), file=file) def get_version(self): if self.version: @@ -1646,7 +1646,7 @@ def print_version(self, file=None): name. Does nothing if self.version is empty or undefined. """ if self.version: - print >>file, self.get_version() + print(self.get_version(), file=file) def format_option_help(self, formatter=None): if formatter is None: @@ -1715,7 +1715,7 @@ def _match_abbrev(s, wordmap): return s else: # Isolate all words with s as a prefix. - possibilities = [word for word in wordmap.keys() + possibilities = [word for word in list(wordmap.keys()) if word.startswith(s)] # No exact match, so there had better be just one possibility. if len(possibilities) == 1: diff --git a/grumpy-runtime-src/third_party/stdlib/pprint.py b/grumpy-runtime-src/third_party/stdlib/pprint.py index ed6310be..a0950b5b 100644 --- a/grumpy-runtime-src/third_party/stdlib/pprint.py +++ b/grumpy-runtime-src/third_party/stdlib/pprint.py @@ -36,8 +36,8 @@ import sys as _sys import warnings -import StringIO -_StringIO = StringIO.StringIO +import io +_StringIO = io.StringIO # try: # from cStringIO import StringIO as _StringIO @@ -157,7 +157,7 @@ def _format(self, o, stream, indent, allowance, context, level): if length: context[objid] = 1 indent = indent + self._indent_per_level - items = _sorted(o.items()) + items = _sorted(list(o.items())) key, ent = items[0] rep = self._repr(key, context, level) write(rep) @@ -284,7 +284,7 @@ def _safe_repr(o, context, maxlevels, level): append = components.append level += 1 saferepr = _safe_repr - for k, v in _sorted(o.items()): + for k, v in _sorted(list(o.items())): krepr, kreadable, krecur = saferepr(k, context, maxlevels, level) vrepr, vreadable, vrecur = saferepr(v, context, maxlevels, level) append("%s: %s" % (krepr, vrepr)) diff --git a/grumpy-runtime-src/third_party/stdlib/quopri.py b/grumpy-runtime-src/third_party/stdlib/quopri.py index 8788afc2..5002cc85 100644 --- a/grumpy-runtime-src/third_party/stdlib/quopri.py +++ b/grumpy-runtime-src/third_party/stdlib/quopri.py @@ -105,7 +105,7 @@ def write(s, output=output, lineEnd='\n'): def encodestring(s, quotetabs = 0, header = 0): if b2a_qp is not None: return b2a_qp(s, quotetabs = quotetabs, header = header) - from cStringIO import StringIO + from io import StringIO infp = StringIO(s) outfp = StringIO() encode(infp, outfp, quotetabs, header) @@ -159,7 +159,7 @@ def decode(input, output, header = 0): def decodestring(s, header = 0): if a2b_qp is not None: return a2b_qp(s, header = header) - from cStringIO import StringIO + from io import StringIO infp = StringIO(s) outfp = StringIO() decode(infp, outfp, header = header) @@ -194,12 +194,12 @@ def main(): import getopt try: opts, args = getopt.getopt(sys.argv[1:], 'td') - except getopt.error, msg: + except getopt.error as msg: sys.stdout = sys.stderr - print msg - print "usage: quopri [-t | -d] [file] ..." - print "-t: quote tabs" - print "-d: decode; default encode" + print(msg) + print("usage: quopri [-t | -d] [file] ...") + print("-t: quote tabs") + print("-d: decode; default encode") sys.exit(2) deco = 0 tabs = 0 @@ -208,7 +208,7 @@ def main(): if o == '-d': deco = 1 if tabs and deco: sys.stdout = sys.stderr - print "-t and -d are mutually exclusive" + print("-t and -d are mutually exclusive") sys.exit(2) if not args: args = ['-'] sts = 0 @@ -218,7 +218,7 @@ def main(): else: try: fp = open(file) - except IOError, msg: + except IOError as msg: sys.stderr.write("%s: can't open (%s)\n" % (file, msg)) sts = 1 continue diff --git a/grumpy-runtime-src/third_party/stdlib/random.py b/grumpy-runtime-src/third_party/stdlib/random.py index 7b52bd86..e759c9a8 100644 --- a/grumpy-runtime-src/third_party/stdlib/random.py +++ b/grumpy-runtime-src/third_party/stdlib/random.py @@ -114,7 +114,7 @@ def seed(self, a=None): ## -------------------- integer methods ------------------- - def randrange(self, start, stop=None, step=1, _int=int, _maxwidth=1L< 0: if istart >= _maxwidth: return self._randbelow(istart) return _int(self.random() * istart) - raise ValueError, "empty range for randrange()" + raise ValueError("empty range for randrange()") # stop argument supplied. istop = _int(stop) if istop != stop: - raise ValueError, "non-integer stop for randrange()" + raise ValueError("non-integer stop for randrange()") width = istop - istart if step == 1 and width > 0: # Note that @@ -157,21 +157,21 @@ def randrange(self, start, stop=None, step=1, _int=int, _maxwidth=1L< 0: n = (width + istep - 1) // istep elif istep < 0: n = (width + istep + 1) // istep else: - raise ValueError, "zero step for randrange()" + raise ValueError("zero step for randrange()") if n <= 0: - raise ValueError, "empty range for randrange()" + raise ValueError("empty range for randrange()") if n >= _maxwidth: return istart + istep*self._randbelow(n) @@ -200,7 +200,7 @@ def shuffle(self, x, random=None): if random is None: random = self.random _int = int - 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] @@ -569,7 +569,7 @@ def uniform(self, a, b): def _test_generator(n, func, args): import time - print n, 'times', func.__name__ + print(n, 'times', func.__name__) total = 0.0 sqsum = 0.0 smallest = 1e10 @@ -582,11 +582,11 @@ def _test_generator(n, func, args): smallest = min(x, smallest) largest = max(x, largest) t1 = time.time() - print round(t1-t0, 3), 'sec,', + print(round(t1-t0, 3), 'sec,', end=' ') avg = total/n stddev = _sqrt(sqsum/n - avg*avg) - print 'avg %g, stddev %g, min %g, max %g' % \ - (avg, stddev, smallest, largest) + print('avg %g, stddev %g, min %g, max %g' % \ + (avg, stddev, smallest, largest)) def _test(N=2000): diff --git a/grumpy-runtime-src/third_party/stdlib/re.py b/grumpy-runtime-src/third_party/stdlib/re.py index f9888add..8885eddc 100644 --- a/grumpy-runtime-src/third_party/stdlib/re.py +++ b/grumpy-runtime-src/third_party/stdlib/re.py @@ -247,11 +247,11 @@ def _compile(*key): raise ValueError('Cannot process flags argument with a compiled pattern') return pattern if not sre_compile.isstring(pattern): - raise TypeError, "first argument must be string or compiled pattern" + raise TypeError("first argument must be string or compiled pattern") try: p = sre_compile.compile(pattern, flags) - except error, v: - raise error, v # invalid expression + except error as v: + raise error(v) # invalid expression if not bypass_cache: if len(_cache) >= _MAXCACHE: _cache.clear() @@ -272,8 +272,8 @@ def _compile_repl(*key): repl, pattern = key try: p = sre_parse.parse_template(repl, pattern) - except error, v: - raise error, v # invalid expression + except error as v: + raise error(v) # invalid expression if len(_cache_repl) >= _MAXCACHE: _cache_repl.clear() _cache_repl[key] = p @@ -296,12 +296,12 @@ def filter(match, template=template): # register myself for pickling -import copy_reg +import copyreg def _pickle(p): return _compile, (p.pattern, p.flags) -copy_reg.pickle(_pattern_type, _pickle, _compile) +copyreg.pickle(_pattern_type, _pickle, _compile) # -------------------------------------------------------------------- # experimental stuff (see python-dev discussions for details) diff --git a/grumpy-runtime-src/third_party/stdlib/re_tests.py b/grumpy-runtime-src/third_party/stdlib/re_tests.py index 485b109b..b49f7c4a 100755 --- a/grumpy-runtime-src/third_party/stdlib/re_tests.py +++ b/grumpy-runtime-src/third_party/stdlib/re_tests.py @@ -6,7 +6,7 @@ # Re test suite and benchmark suite v1.5 # The 3 possible outcomes for each pattern -[SUCCEED, FAIL, SYNTAX_ERROR] = range(3) +[SUCCEED, FAIL, SYNTAX_ERROR] = list(range(3)) # Benchmark suite (needs expansion) # diff --git a/grumpy-runtime-src/third_party/stdlib/repr.py b/grumpy-runtime-src/third_party/stdlib/repr.py index a1bc9250..bfefbfe8 100644 --- a/grumpy-runtime-src/third_party/stdlib/repr.py +++ b/grumpy-runtime-src/third_party/stdlib/repr.py @@ -2,7 +2,7 @@ __all__ = ["Repr","repr"] -import __builtin__ +import builtins import itertools class Repr(object): @@ -31,7 +31,7 @@ def repr1(self, x, level): if hasattr(self, 'repr_' + typename): return getattr(self, 'repr_' + typename)(x, level) else: - s = __builtin__.repr(x) + s = builtins.repr(x) if len(s) > self.maxother: i = max(0, (self.maxother-3)//2) j = max(0, self.maxother-3-i) @@ -89,16 +89,16 @@ def repr_dict(self, x, level): return '{%s}' % (s,) def repr_str(self, x, level): - s = __builtin__.repr(x[:self.maxstring]) + s = builtins.repr(x[:self.maxstring]) if len(s) > self.maxstring: i = max(0, (self.maxstring-3)//2) j = max(0, self.maxstring-3-i) - s = __builtin__.repr(x[:i] + x[len(x)-j:]) + s = builtins.repr(x[:i] + x[len(x)-j:]) s = s[:i] + '...' + s[len(s)-j:] return s def repr_long(self, x, level): - s = __builtin__.repr(x) # XXX Hope this isn't too slow... + s = builtins.repr(x) # XXX Hope this isn't too slow... if len(s) > self.maxlong: i = max(0, (self.maxlong-3)//2) j = max(0, self.maxlong-3-i) @@ -107,7 +107,7 @@ def repr_long(self, x, level): def repr_instance(self, x, level): try: - s = __builtin__.repr(x) + s = builtins.repr(x) # Bugs in x.__repr__() can cause arbitrary # exceptions -- then make up something except Exception: diff --git a/grumpy-runtime-src/third_party/stdlib/rfc822.py b/grumpy-runtime-src/third_party/stdlib/rfc822.py index a69e40e6..c6b2d467 100644 --- a/grumpy-runtime-src/third_party/stdlib/rfc822.py +++ b/grumpy-runtime-src/third_party/stdlib/rfc822.py @@ -116,7 +116,7 @@ def __init__(self, fp, seekable = 1): def rewindbody(self): """Rewind the file to the start of the body (if seekable).""" if not self.seekable: - raise IOError, "unseekable file" + raise IOError("unseekable file") self.fp.seek(self.startofbody) def readheaders(self): @@ -450,18 +450,18 @@ def __iter__(self): def keys(self): """Get all of a message's header field names.""" - return self.dict.keys() + return list(self.dict.keys()) def values(self): """Get all of a message's header field values.""" - return self.dict.values() + return list(self.dict.values()) def items(self): """Get all of a message's headers. Returns a list of name, value tuples. """ - return self.dict.items() + return list(self.dict.items()) def __str__(self): return ''.join(self.headers) @@ -985,32 +985,32 @@ def formatdate(timeval=None): if sys.argv[1:]: file = sys.argv[1] f = open(file, 'r') m = Message(f) - print 'From:', m.getaddr('from') - print 'To:', m.getaddrlist('to') - print 'Subject:', m.getheader('subject') - print 'Date:', m.getheader('date') + print('From:', m.getaddr('from')) + print('To:', m.getaddrlist('to')) + print('Subject:', m.getheader('subject')) + print('Date:', m.getheader('date')) date = m.getdate_tz('date') tz = date[-1] date = time.localtime(mktime_tz(date)) if date: - print 'ParsedDate:', time.asctime(date), + print('ParsedDate:', time.asctime(date), end=' ') hhmmss = tz hhmm, ss = divmod(hhmmss, 60) hh, mm = divmod(hhmm, 60) - print "%+03d%02d" % (hh, mm), - if ss: print ".%02d" % ss, - print + print("%+03d%02d" % (hh, mm), end=' ') + if ss: print(".%02d" % ss, end=' ') + print() else: - print 'ParsedDate:', None + print('ParsedDate:', None) m.rewindbody() n = 0 while f.readline(): n += 1 - print 'Lines:', n - print '-'*70 - print 'len =', len(m) - if 'Date' in m: print 'Date =', m['Date'] + print('Lines:', n) + print('-'*70) + print('len =', len(m)) + if 'Date' in m: print('Date =', m['Date']) if 'X-Nonsense' in m: pass - print 'keys =', m.keys() - print 'values =', m.values() - print 'items =', m.items() + print('keys =', list(m.keys())) + print('values =', list(m.values())) + print('items =', list(m.items())) diff --git a/grumpy-runtime-src/third_party/stdlib/sched.py b/grumpy-runtime-src/third_party/stdlib/sched.py index 1c5d944f..1a0f112f 100644 --- a/grumpy-runtime-src/third_party/stdlib/sched.py +++ b/grumpy-runtime-src/third_party/stdlib/sched.py @@ -139,4 +139,4 @@ def queue(self): # With heapq, two events scheduled at the same time will show in # the actual order they would be retrieved. events = self._queue[:] - return map(heapq.heappop, [events]*len(events)) + return list(map(heapq.heappop, [events]*len(events))) diff --git a/grumpy-runtime-src/third_party/stdlib/sre_compile.py b/grumpy-runtime-src/third_party/stdlib/sre_compile.py index a8576858..9a55b715 100644 --- a/grumpy-runtime-src/third_party/stdlib/sre_compile.py +++ b/grumpy-runtime-src/third_party/stdlib/sre_compile.py @@ -25,7 +25,7 @@ if _sre.CODESIZE == 2: MAXCODE = 65535 else: - MAXCODE = 0xFFFFFFFFL + MAXCODE = 0xFFFFFFFF _LITERAL_CODES = set([LITERAL, NOT_LITERAL]) _REPEATING_CODES = set([REPEAT, MIN_REPEAT, MAX_REPEAT]) @@ -118,7 +118,7 @@ def fixup(literal, flags=flags): emit(OPCODES[ANY]) elif op in REPEATING_CODES: if flags & SRE_FLAG_TEMPLATE: - raise error, "internal: unsupported template operator" + raise error("internal: unsupported template operator") emit(OPCODES[REPEAT]) skip = _len(code); emit(0) emit(av[0]) @@ -167,7 +167,7 @@ def fixup(literal, flags=flags): else: lo, hi = av[1].getwidth() if lo != hi: - raise error, "look-behind requires fixed-width pattern" + raise error("look-behind requires fixed-width pattern") emit(lo) # look behind _compile(code, av[1], flags) emit(OPCODES[SUCCESS]) @@ -228,7 +228,7 @@ def fixup(literal, flags=flags): else: code[skipyes] = _len(code) - skipyes + 1 else: - raise ValueError, ("unsupported operand type", op) + raise ValueError("unsupported operand type", op) def _compile_charset(charset, flags, code, fixup=None, fixes=None): # compile charset subprogram @@ -257,7 +257,7 @@ def _compile_charset(charset, flags, code, fixup=None, fixes=None): else: emit(CHCODES[av]) else: - raise error, "internal: unsupported set operator" + raise error("internal: unsupported set operator") emit(OPCODES[FAILURE]) def _optimize_charset(charset, fixup, fixes, isunicode): @@ -279,9 +279,9 @@ def _optimize_charset(charset, fixup, fixes, isunicode): else: charmap[av] = 1 elif op is RANGE: - r = range(av[0], av[1]+1) + r = list(range(av[0], av[1]+1)) if fixup: - r = map(fixup, r) + r = list(map(fixup, r)) if fixup and fixes: for i in r: charmap[i] = 1 @@ -409,7 +409,7 @@ def char_find(l, s, start): return out def _fixup_range(lo, hi, ranges, fixup): - for i in map(fixup, range(lo, hi+1)): + for i in map(fixup, list(range(lo, hi+1))): for k, (lo, hi) in enumerate(ranges): if i < lo: if l == lo - 1: @@ -567,7 +567,7 @@ def _compile_info(code, pattern, flags): code += (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 @@ -578,11 +578,11 @@ def _compile_info(code, pattern, flags): code[skip] = len(code) - skip try: - unicode + str except NameError: STRING_TYPES = (type(""),) else: - STRING_TYPES = (type(""), type(unicode(""))) + STRING_TYPES = (type(""), type(str(""))) def isstring(obj): for tp in STRING_TYPES: @@ -627,7 +627,7 @@ def compile(p, flags=0): # map in either direction groupindex = p.pattern.groupdict indexgroup = [None] * p.pattern.groups - for k, i in groupindex.items(): + for k, i in list(groupindex.items()): indexgroup[i] = k return _sre.compile( diff --git a/grumpy-runtime-src/third_party/stdlib/sre_parse.py b/grumpy-runtime-src/third_party/stdlib/sre_parse.py index c99e6443..3007e21b 100644 --- a/grumpy-runtime-src/third_party/stdlib/sre_parse.py +++ b/grumpy-runtime-src/third_party/stdlib/sre_parse.py @@ -80,7 +80,7 @@ def opengroup(self, name=None): if name is not None: ogid = self.groupdict.get(name, None) if ogid is not None: - raise error, ("redefinition of group name %s as group %d; " + raise error("redefinition of group name %s as group %d; " "was group %d" % (repr(name), gid, ogid)) self.groupdict[name] = gid self.open.append(gid) @@ -102,40 +102,40 @@ def __init__(self, pattern, data=None): def dump(self, level=0): seqtypes = (tuple, list) for op, av in self.data: - print level*" " + op, + print(level*" " + op, end=' ') if op == IN: # member sublanguage - print + print() for op, a in av: - print (level+1)*" " + op, a + print((level+1)*" " + op, a) elif op == BRANCH: - print + print() for i, a in enumerate(av[1]): if i: - print level*" " + "or" + print(level*" " + "or") a.dump(level+1) elif op == GROUPREF_EXISTS: condgroup, item_yes, item_no = av - print condgroup + print(condgroup) item_yes.dump(level+1) if item_no: - print level*" " + "else" + print(level*" " + "else") item_no.dump(level+1) elif isinstance(av, seqtypes): nl = 0 for a in av: if isinstance(a, SubPattern): if not nl: - print + print() a.dump(level+1) nl = 1 else: - print a, + print(a, end=' ') nl = 0 if not nl: - print + print() else: - print av + print(av) def __repr__(self): return repr(self.data) def __len__(self): @@ -204,22 +204,22 @@ def __next(self): try: c = self.string[self.index + 1] except IndexError: - raise error, "bogus escape (end of line)" + raise error("bogus escape (end of line)") char = char + c self.index = self.index + len(char) self.next = char def match(self, char, skip=1): - if char == self.next: + if char == self.__next__: if skip: self.__next() return 1 return 0 def get(self): - this = self.next + this = self.__next__ self.__next() return this def tell(self): - return self.index, self.next + return self.index, self.__next__ def seek(self, index): self.index, self.next = index @@ -250,25 +250,25 @@ def _class_escape(source, escape): c = escape[1:2] if c == "x": # hexadecimal escape (exactly two digits) - while source.next in HEXDIGITS and len(escape) < 4: + while source.__next__ in HEXDIGITS and len(escape) < 4: escape = escape + source.get() escape = escape[2:] if len(escape) != 2: - raise error, "bogus escape: %s" % repr("\\" + escape) + raise error("bogus escape: %s" % repr("\\" + escape)) return LITERAL, int(escape, 16) & 0xff elif c in OCTDIGITS: # octal escape (up to three digits) - while source.next in OCTDIGITS and len(escape) < 4: + while source.__next__ in OCTDIGITS and len(escape) < 4: escape = escape + source.get() escape = escape[1:] return LITERAL, int(escape, 8) & 0xff elif c in DIGITS: - raise error, "bogus escape: %s" % repr(escape) + raise error("bogus escape: %s" % repr(escape)) if len(escape) == 2: return LITERAL, ord(escape[1]) except ValueError: pass - raise error, "bogus escape: %s" % repr(escape) + raise error("bogus escape: %s" % repr(escape)) def _escape(source, escape, state): # handle escape code in expression @@ -282,22 +282,22 @@ def _escape(source, escape, state): c = escape[1:2] if c == "x": # hexadecimal escape - while source.next in HEXDIGITS and len(escape) < 4: + while source.__next__ in HEXDIGITS and len(escape) < 4: escape = escape + source.get() if len(escape) != 4: raise ValueError return LITERAL, int(escape[2:], 16) & 0xff elif c == "0": # octal escape - while source.next in OCTDIGITS and len(escape) < 4: + while source.__next__ in OCTDIGITS and len(escape) < 4: escape = escape + source.get() return LITERAL, int(escape[1:], 8) & 0xff elif c in DIGITS: # octal escape *or* decimal group reference (sigh) - if source.next in DIGITS: + if source.__next__ in DIGITS: escape = escape + source.get() if (escape[1] in OCTDIGITS and escape[2] in OCTDIGITS and - source.next in OCTDIGITS): + source.__next__ in OCTDIGITS): # got three octal digits; this is an octal escape escape = escape + source.get() return LITERAL, int(escape[1:], 8) & 0xff @@ -305,7 +305,7 @@ def _escape(source, escape, state): group = int(escape[1:]) if group < state.groups: if not state.checkgroup(group): - raise error, "cannot refer to open group" + raise error("cannot refer to open group") # if state.lookbehind: # import warnings # warnings.warn('group references in lookbehind ' @@ -317,7 +317,7 @@ def _escape(source, escape, state): return LITERAL, ord(escape[1]) except ValueError: pass - raise error, "bogus escape: %s" % repr(escape) + raise error("bogus escape: %s" % repr(escape)) def _parse_sub(source, state, nested=1): # parse an alternation: a|b|c @@ -331,10 +331,10 @@ def _parse_sub(source, state, nested=1): continue if not nested: break - if not source.next or sourcematch(")", 0): + if not source.__next__ or sourcematch(")", 0): break else: - raise error, "pattern not properly closed" + raise error("pattern not properly closed") if len(items) == 1: return items[0] @@ -389,11 +389,11 @@ def _parse_sub_cond(source, state, condgroup): if source.match("|"): item_no = _parse(source, state) if source.match("|"): - raise error, "conditional backref with more than two branches" + raise error("conditional backref with more than two branches") else: item_no = None - if source.next and not source.match(")", 0): - raise error, "pattern not properly closed" + if source.__next__ and not source.match(")", 0): + raise error("pattern not properly closed") subpattern = SubPattern(state) subpattern.append((GROUPREF_EXISTS, (condgroup, item_yes, item_no))) return subpattern @@ -419,7 +419,7 @@ def _parse(source, state): while 1: - if source.next in PATTERNENDERS: + if source.__next__ in PATTERNENDERS: break # end of subpattern this = sourceget() if this is None: @@ -458,7 +458,7 @@ def _parse(source, state): elif this: code1 = LITERAL, ord(this) else: - raise error, "unexpected end of regular expression" + raise error("unexpected end of regular expression") if sourcematch("-"): # potential range this = sourceget() @@ -474,14 +474,14 @@ def _parse(source, state): else: code2 = LITERAL, ord(this) if code1[0] != LITERAL or code2[0] != LITERAL: - raise error, "bad character range" + raise error("bad character range") lo = code1[1] hi = code2[1] if hi < lo: - raise error, "bad character range" + raise error("bad character range") setappend((RANGE, (lo, hi))) else: - raise error, "unexpected end of regular expression" + raise error("unexpected end of regular expression") else: if code1[0] is IN: code1 = code1[1][0] @@ -506,16 +506,16 @@ def _parse(source, state): elif this == "+": min, max = 1, MAXREPEAT elif this == "{": - if source.next == "}": + if source.__next__ == "}": subpatternappend((LITERAL, ord(this))) continue here = source.tell() min, max = 0, MAXREPEAT lo = hi = "" - while source.next in DIGITS: + while source.__next__ in DIGITS: lo = lo + source.get() if sourcematch(","): - while source.next in DIGITS: + while source.__next__ in DIGITS: hi = hi + sourceget() else: hi = lo @@ -534,16 +534,16 @@ def _parse(source, state): if max < min: raise error("bad repeat interval") else: - raise error, "not supported" + raise error("not supported") # figure out which item to repeat if subpattern: item = subpattern[-1:] else: item = None if not item or (_len(item) == 1 and item[0][0] == AT): - raise error, "nothing to repeat" + raise error("nothing to repeat") if item[0][0] in REPEATCODES: - raise error, "multiple repeat" + raise error("multiple repeat") if sourcematch("?"): subpattern[-1] = (MIN_REPEAT, (min, max, item)) else: @@ -567,7 +567,7 @@ def _parse(source, state): while 1: char = sourceget() if char is None: - raise error, "unterminated name" + raise error("unterminated name") if char == ">": break name = name + char @@ -583,7 +583,7 @@ def _parse(source, state): while 1: char = sourceget() if char is None: - raise error, "unterminated name" + raise error("unterminated name") if char == ")": break name = name + char @@ -607,27 +607,27 @@ def _parse(source, state): else: char = sourceget() if char is None: - raise error, "unexpected end of pattern" - raise error, "unknown specifier: ?P%s" % char + raise error("unexpected end of pattern") + raise error("unknown specifier: ?P%s" % char) elif sourcematch(":"): # non-capturing group group = 2 elif sourcematch("#"): # comment while 1: - if source.next is None or source.next == ")": + if source.__next__ is None or source.__next__ == ")": break sourceget() if not sourcematch(")"): - raise error, "unbalanced parenthesis" + raise error("unbalanced parenthesis") continue - elif source.next in ASSERTCHARS: + elif source.__next__ in ASSERTCHARS: # lookahead assertions char = sourceget() dir = 1 if char == "<": - if source.next not in LOOKBEHINDASSERTCHARS: - raise error, "syntax error" + if source.__next__ not in LOOKBEHINDASSERTCHARS: + raise error("syntax error") dir = -1 # lookbehind char = sourceget() state.lookbehind += 1 @@ -635,7 +635,7 @@ def _parse(source, state): if dir < 0: state.lookbehind -= 1 if not sourcematch(")"): - raise error, "unbalanced parenthesis" + raise error("unbalanced parenthesis") if char == "=": subpatternappend((ASSERT, (dir, p))) else: @@ -647,7 +647,7 @@ def _parse(source, state): while 1: char = sourceget() if char is None: - raise error, "unterminated name" + raise error("unterminated name") if char == ")": break condname = condname + char @@ -664,7 +664,7 @@ def _parse(source, state): try: condgroup = int(condname) except ValueError: - raise error, "bad character in group name" + raise error("bad character in group name") # if state.lookbehind: # import warnings # warnings.warn('group references in lookbehind ' @@ -672,9 +672,9 @@ def _parse(source, state): # RuntimeWarning) else: # flags - if not source.next in FLAGS: - raise error, "unexpected end of pattern" - while source.next in FLAGS: + if not source.__next__ in FLAGS: + raise error("unexpected end of pattern") + while source.__next__ in FLAGS: state.flags = state.flags | FLAGS[sourceget()] if group: # parse group contents @@ -688,7 +688,7 @@ def _parse(source, state): else: p = _parse_sub(source, state) if not sourcematch(")"): - raise error, "unbalanced parenthesis" + raise error("unbalanced parenthesis") if group is not None: state.closegroup(group) subpatternappend((SUBPATTERN, (group, p))) @@ -696,10 +696,10 @@ def _parse(source, state): while 1: char = sourceget() if char is None: - raise error, "unexpected end of pattern" + raise error("unexpected end of pattern") if char == ")": break - raise error, "unknown extension" + raise error("unknown extension") elif this == "^": subpatternappend((AT, AT_BEGINNING)) @@ -712,7 +712,7 @@ def _parse(source, state): subpatternappend(code) else: - raise error, "parser error" + raise error("parser error") return subpattern @@ -730,9 +730,9 @@ def parse(str, flags=0, pattern=None): tail = source.get() if tail == ")": - raise error, "unbalanced parenthesis" + raise error("unbalanced parenthesis") elif tail: - raise error, "bogus characters at end of regular expression" + raise error("bogus characters at end of regular expression") if not (flags & SRE_FLAG_VERBOSE) and p.pattern.flags & SRE_FLAG_VERBOSE: # the VERBOSE flag was switched on inside the pattern. to be @@ -760,7 +760,7 @@ def literal(literal, p=p, pappend=a): if type(sep) is type(""): makechar = chr else: - makechar = unichr + makechar = chr while 1: this = sget() if this is None: @@ -774,19 +774,19 @@ def literal(literal, p=p, pappend=a): while 1: char = sget() if char is None: - raise error, "unterminated group name" + raise error("unterminated group name") if char == ">": break name = name + char if not name: - raise error, "missing group name" + raise error("missing group name") try: index = int(name) if index < 0: - raise error, "negative group number" + raise error("negative group number") except ValueError: if not isname(name): - raise error, "bad character in group name" + raise error("bad character in group name") try: index = pattern.groupindex[name] except KeyError: @@ -795,17 +795,17 @@ def literal(literal, p=p, pappend=a): raise IndexError(msg) a((MARK, index)) elif c == "0": - if s.next in OCTDIGITS: + if s.__next__ in OCTDIGITS: this = this + sget() - if s.next in OCTDIGITS: + if s.__next__ in OCTDIGITS: this = this + sget() literal(makechar(int(this[1:], 8) & 0xff)) elif c in DIGITS: isoctal = False - if s.next in DIGITS: + if s.__next__ in DIGITS: this = this + sget() if (c in OCTDIGITS and this[2] in OCTDIGITS and - s.next in OCTDIGITS): + s.__next__ in OCTDIGITS): this = this + sget() isoctal = True literal(makechar(int(this[1:], 8) & 0xff)) @@ -842,7 +842,7 @@ def expand_template(template, match): for index, group in groups: literals[index] = s = g(group) if s is None: - raise error, "unmatched group" + raise error("unmatched group") except IndexError: - raise error, "invalid group reference" + raise error("invalid group reference") return sep.join(literals) diff --git a/grumpy-runtime-src/third_party/stdlib/string.py b/grumpy-runtime-src/third_party/stdlib/string.py index 21b50bfe..06a30e04 100644 --- a/grumpy-runtime-src/third_party/stdlib/string.py +++ b/grumpy-runtime-src/third_party/stdlib/string.py @@ -37,7 +37,7 @@ # Use str to convert Unicode literal in case of -U # TODO: use map once implemented # l = map(chr, xrange(256)) -l = [chr(x) for x in xrange(256)] +l = [chr(x) for x in range(256)] _idmap = str('').join(l) del l @@ -69,12 +69,12 @@ def maketrans(fromstr, tostr): """ if len(fromstr) != len(tostr): - raise ValueError, "maketrans arguments must have same length" + raise ValueError("maketrans arguments must have same length") global _idmapL if not _idmapL: _idmapL = list(_idmap) L = _idmapL[:] - fromstr = map(ord, fromstr) + fromstr = list(map(ord, fromstr)) for i in range(len(fromstr)): L[fromstr[i]] = tostr[i] return ''.join(L) @@ -134,9 +134,8 @@ def __init__(cls, name, bases, dct): cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE) -class Template(object): +class Template(object, metaclass=_TemplateMetaclass): """A string class for supporting $-substitutions.""" - __metaclass__ = _TemplateMetaclass delimiter = '$' idpattern = r'[_a-z][_a-z0-9]*' @@ -391,7 +390,7 @@ def rfind(s, *args): # for a bit of speed _float = float _int = int -_long = long +_long = int # Convert string to float def atof(s): @@ -477,7 +476,7 @@ def zfill(x, width): of the specified width. The string x is never truncated. """ - if not isinstance(x, basestring): + if not isinstance(x, str): x = repr(x) return x.zfill(width) @@ -612,7 +611,7 @@ def _vformat(self, format_string, args, kwargs, used_args, recursion_depth): def get_value(self, key, args, kwargs): - if isinstance(key, (int, long)): + if isinstance(key, int): return args[key] else: return kwargs[key] diff --git a/grumpy-runtime-src/third_party/stdlib/textwrap.py b/grumpy-runtime-src/third_party/stdlib/textwrap.py index 0b0d4e44..19f41041 100644 --- a/grumpy-runtime-src/third_party/stdlib/textwrap.py +++ b/grumpy-runtime-src/third_party/stdlib/textwrap.py @@ -10,7 +10,7 @@ import string, re try: - _unicode = unicode + _unicode = str except NameError: # If Python is built without Unicode support, the unicode type # will not exist. Fake one. @@ -83,7 +83,7 @@ class TextWrapper(object): whitespace_trans = '\x00\x01\x02\x03\x04\x05\x06\x07\x08 \x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\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' unicode_whitespace_trans = {} - uspace = ord(u' ') + uspace = ord(' ') for x in map(ord, _whitespace): unicode_whitespace_trans[x] = uspace @@ -432,4 +432,4 @@ def dedent(text): if __name__ == "__main__": #print dedent("\tfoo\n\tbar") #print dedent(" \thello there\n \t how are you?") - print dedent("Hello there.\n This is indented.") + print(dedent("Hello there.\n This is indented.")) diff --git a/grumpy-runtime-src/third_party/stdlib/threading.py b/grumpy-runtime-src/third_party/stdlib/threading.py index 1c34c848..2410ff9a 100644 --- a/grumpy-runtime-src/third_party/stdlib/threading.py +++ b/grumpy-runtime-src/third_party/stdlib/threading.py @@ -3,7 +3,7 @@ import sys as _sys try: - import thread + import _thread except ImportError: del _sys.modules[__name__] raise @@ -32,10 +32,10 @@ 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Thread', 'Timer', 'setprofile', 'settrace', 'local', 'stack_size'] -_start_new_thread = thread.start_new_thread -_allocate_lock = thread.allocate_lock -_get_ident = thread.get_ident -ThreadError = thread.error +_start_new_thread = _thread.start_new_thread +_allocate_lock = _thread.allocate_lock +_get_ident = _thread.get_ident +ThreadError = _thread.error del thread @@ -615,7 +615,7 @@ def wait(self, timeout=None): return self.__flag # Helper to generate new thread names -_counter = _count().next +_counter = _count().__next__ _counter() # Consume 0 so first non-main thread has id 1. def _newname(template="Thread-%d"): return template % _counter() @@ -802,27 +802,27 @@ def __bootstrap_inner(self): # _sys) in case sys.stderr was redefined since the creation of # self. if _sys and _sys.stderr is not None: - print>>_sys.stderr, ("Exception in thread %s:\n%s" % - (self.name, _format_exc())) + print(("Exception in thread %s:\n%s" % + (self.name, _format_exc())), file=_sys.stderr) elif self.__stderr is not None: # Do the best job possible w/o a huge amt. of code to # approximate a traceback (code ideas from # Lib/traceback.py) exc_type, exc_value, exc_tb = _sys.exc_info() try: - print>>self.__stderr, ( + print(( "Exception in thread " + self.name + - " (most likely raised during interpreter shutdown):") - print>>self.__stderr, ( - "Traceback (most recent call last):") + " (most likely raised during interpreter shutdown):"), file=self.__stderr) + print(( + "Traceback (most recent call last):"), file=self.__stderr) while exc_tb: - print>>self.__stderr, ( + print(( ' File "%s", line %s, in %s' % (exc_tb.tb_frame.f_code.co_filename, exc_tb.tb_lineno, - exc_tb.tb_frame.f_code.co_name)) + exc_tb.tb_frame.f_code.co_name)), file=self.__stderr) exc_tb = exc_tb.tb_next - print>>self.__stderr, ("%s: %s" % (exc_type, exc_value)) + print(("%s: %s" % (exc_type, exc_value)), file=self.__stderr) # Make sure that exc_tb gets deleted since it is a memory # hog; deleting everything else is just for thoroughness finally: @@ -1161,7 +1161,7 @@ def activeCount(): def _enumerate(): # Same as enumerate(), but without the lock. Internal use only. - return _active.values() + _limbo.values() + return list(_active.values()) + list(_limbo.values()) def enumerate(): """Return a list of all Thread objects currently alive. @@ -1172,9 +1172,9 @@ def enumerate(): """ with _active_limbo_lock: - return _active.values() + _limbo.values() + return list(_active.values()) + list(_limbo.values()) -from thread import stack_size +from _thread import stack_size # Create the main thread object, # and make it available for the interpreter @@ -1278,7 +1278,7 @@ def __del__(self): for thread in threads: try: - __dict__ = thread.__dict__ + __dict__ = _thread.__dict__ except AttributeError: # Thread is dying, rest in peace. continue @@ -1309,16 +1309,16 @@ def _after_fork(): # Any lock/condition variable may be currently locked or in an # invalid state, so we reinitialize them. if hasattr(thread, '_reset_internal_locks'): - thread._reset_internal_locks() + _thread._reset_internal_locks() if thread is current: # There is only one active thread. We reset the ident to # its new value since it can have changed. ident = _get_ident() - thread.__ident = ident + _thread.__ident = ident new_active[ident] = thread else: # All the others are already stopped. - thread.__stop() + _thread.__stop() _limbo.clear() _active.clear() @@ -1388,7 +1388,7 @@ def __init__(self, queue, count): def run(self): while self.count > 0: item = self.queue.get() - print item + print(item) self.count = self.count - 1 NP = 3 diff --git a/grumpy-runtime-src/third_party/stdlib/traceback.py b/grumpy-runtime-src/third_party/stdlib/traceback.py index b0b9005c..9ee05c71 100644 --- a/grumpy-runtime-src/third_party/stdlib/traceback.py +++ b/grumpy-runtime-src/third_party/stdlib/traceback.py @@ -217,7 +217,7 @@ def _some_str(value): except Exception: pass try: - value = unicode(value) + value = str(value) return value.encode("ascii", "backslashreplace") except Exception: pass diff --git a/grumpy-runtime-src/third_party/stdlib/types.py b/grumpy-runtime-src/third_party/stdlib/types.py index 65e1fb62..d378cf80 100644 --- a/grumpy-runtime-src/third_party/stdlib/types.py +++ b/grumpy-runtime-src/third_party/stdlib/types.py @@ -28,7 +28,7 @@ # types.StringTypes", you should use "isinstance(x, basestring)". But # we keep around for compatibility with Python 2.2. try: - UnicodeType = unicode + UnicodeType = str StringTypes = (StringType, UnicodeType) except NameError: StringTypes = (StringType,) diff --git a/grumpy-runtime-src/third_party/stdlib/unittest_case.py b/grumpy-runtime-src/third_party/stdlib/unittest_case.py index 999fed95..70f9c9cd 100644 --- a/grumpy-runtime-src/third_party/stdlib/unittest_case.py +++ b/grumpy-runtime-src/third_party/stdlib/unittest_case.py @@ -65,7 +65,7 @@ def skip(reason): Unconditionally skip a test. """ def decorator(test_item): - if not isinstance(test_item, (type, types.ClassType)): + if not isinstance(test_item, type): # @functools.wraps(test_item) def skip_wrapper(*args, **kwargs): raise SkipTest(reason) @@ -213,7 +213,7 @@ def __init__(self, methodName='runTest'): self.addTypeEqualityFunc(set, 'assertSetEqual') self.addTypeEqualityFunc(frozenset, 'assertSetEqual') try: - self.addTypeEqualityFunc(unicode, 'assertMultiLineEqual') + self.addTypeEqualityFunc(str, 'assertMultiLineEqual') except NameError: # No unicode support in this build pass @@ -508,7 +508,7 @@ def _getAssertEqualityFunc(self, first, second): if type(first) is type(second): asserter = self._type_equality_funcs.get(type(first)) if asserter is not None: - if isinstance(asserter, basestring): + if isinstance(asserter, str): asserter = getattr(self, asserter) return asserter @@ -689,7 +689,7 @@ def assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None): elements = (seq_type_name.capitalize(), seq1_repr, seq2_repr) differing = '%ss differ: %s != %s\n' % elements - for i in xrange(min(len1, len2)): + for i in range(min(len1, len2)): try: item1 = seq1[i] except (TypeError, IndexError, NotImplementedError): @@ -784,16 +784,16 @@ def assertSetEqual(self, set1, set2, msg=None): """ try: difference1 = set1.difference(set2) - except TypeError, e: + except TypeError as e: self.fail('invalid type when attempting set difference: %s' % e) - except AttributeError, e: + except AttributeError as e: self.fail('first argument does not support set difference: %s' % e) try: difference2 = set2.difference(set1) - except TypeError, e: + except TypeError as e: self.fail('invalid type when attempting set difference: %s' % e) - except AttributeError, e: + except AttributeError as e: self.fail('second argument does not support set difference: %s' % e) if not (difference1 or difference2): @@ -855,7 +855,7 @@ def assertDictContainsSubset(self, expected, actual, msg=None): """Checks whether actual is a superset of expected.""" missing = [] mismatched = [] - for key, value in expected.iteritems(): + for key, value in expected.items(): if key not in actual: missing.append(key) elif value != actual[key]: @@ -919,9 +919,9 @@ def assertItemsEqual(self, expected_seq, actual_seq, msg=None): def assertMultiLineEqual(self, first, second, msg=None): """Assert that two multi-line strings are equal.""" - self.assertIsInstance(first, basestring, + self.assertIsInstance(first, str, 'First argument is not a string') - self.assertIsInstance(second, basestring, + self.assertIsInstance(second, str, 'Second argument is not a string') if first != second: @@ -1011,7 +1011,7 @@ def assertRaisesRegexp(self, expected_exception, expected_regexp, def assertRegexpMatches(self, text, expected_regexp, msg=None): """Fail the test unless the text matches the regular expression.""" - if isinstance(expected_regexp, basestring): + if isinstance(expected_regexp, str): expected_regexp = re.compile(expected_regexp) if not expected_regexp.search(text): msg = msg or "Regexp didn't match" @@ -1020,7 +1020,7 @@ def assertRegexpMatches(self, text, expected_regexp, msg=None): def assertNotRegexpMatches(self, text, unexpected_regexp, msg=None): """Fail the test if the text matches the regular expression.""" - if isinstance(unexpected_regexp, basestring): + if isinstance(unexpected_regexp, str): unexpected_regexp = re.compile(unexpected_regexp) match = unexpected_regexp.search(text) if match: diff --git a/grumpy-runtime-src/third_party/stdlib/unittest_loader.py b/grumpy-runtime-src/third_party/stdlib/unittest_loader.py index 072729f1..e839e017 100644 --- a/grumpy-runtime-src/third_party/stdlib/unittest_loader.py +++ b/grumpy-runtime-src/third_party/stdlib/unittest_loader.py @@ -59,7 +59,7 @@ def loadTestsFromTestCase(self, testCaseClass): testCaseNames = self.getTestCaseNames(testCaseClass) if not testCaseNames and hasattr(testCaseClass, 'runTest'): testCaseNames = ['runTest'] - loaded_suite = self.suiteClass(map(testCaseClass, testCaseNames)) + loaded_suite = self.suiteClass(list(map(testCaseClass, testCaseNames))) return loaded_suite def loadTestsFromModule(self, module, use_load_tests=True): @@ -75,7 +75,7 @@ def loadTestsFromModule(self, module, use_load_tests=True): if use_load_tests and load_tests is not None: try: return load_tests(self, tests, None) - except Exception, e: + except Exception as e: return _make_failed_load_tests(module.__name__, e, self.suiteClass) return tests @@ -296,7 +296,7 @@ def _find_tests(self, start_dir, pattern): else: try: yield load_tests(self, tests, pattern) - except Exception, e: + except Exception as e: yield _make_failed_load_tests(package.__name__, e, self.suiteClass) diff --git a/grumpy-runtime-src/third_party/stdlib/unittest_result.py b/grumpy-runtime-src/third_party/stdlib/unittest_result.py index fcd5ed15..27bf53b0 100644 --- a/grumpy-runtime-src/third_party/stdlib/unittest_result.py +++ b/grumpy-runtime-src/third_party/stdlib/unittest_result.py @@ -5,7 +5,7 @@ import traceback # from StringIO import StringIO -import StringIO as _StringIO +import io as _StringIO StringIO = _StringIO.StringIO # from . import util diff --git a/grumpy-runtime-src/third_party/stdlib/unittest_runner.py b/grumpy-runtime-src/third_party/stdlib/unittest_runner.py index e18bc222..97b21d2d 100644 --- a/grumpy-runtime-src/third_party/stdlib/unittest_runner.py +++ b/grumpy-runtime-src/third_party/stdlib/unittest_runner.py @@ -175,9 +175,9 @@ def run(self, test): expectedFails = unexpectedSuccesses = skipped = 0 try: - results = map(len, (result.expectedFailures, + results = list(map(len, (result.expectedFailures, result.unexpectedSuccesses, - result.skipped)) + result.skipped))) except AttributeError: pass else: @@ -186,7 +186,7 @@ def run(self, test): infos = [] if not result.wasSuccessful(): self.stream.write("FAILED") - failed, errored = map(len, (result.failures, result.errors)) + failed, errored = list(map(len, (result.failures, result.errors))) if failed: infos.append("failures=%d" % failed) if errored: diff --git a/grumpy-runtime-src/third_party/stdlib/unittest_suite.py b/grumpy-runtime-src/third_party/stdlib/unittest_suite.py index 81c379c5..cd70683e 100644 --- a/grumpy-runtime-src/third_party/stdlib/unittest_suite.py +++ b/grumpy-runtime-src/third_party/stdlib/unittest_suite.py @@ -57,7 +57,7 @@ def addTest(self, test): self._tests.append(test) def addTests(self, tests): - if isinstance(tests, basestring): + if isinstance(tests, str): raise TypeError("tests must be an iterable of tests, not a string") for test in tests: self.addTest(test) @@ -183,7 +183,7 @@ def _handleModuleFixture(self, test, result): _call_if_exists(result, '_setupStdout') try: setUpModule() - except Exception, e: + except Exception as e: if isinstance(result, _DebugResult): raise result._moduleSetUpFailed = True @@ -242,7 +242,7 @@ def _tearDownPreviousClass(self, test, result): _call_if_exists(result, '_setupStdout') try: tearDownClass() - except Exception, e: + except Exception as e: if isinstance(result, _DebugResult): raise className = util.strclass(previousClass) diff --git a/grumpy-runtime-src/third_party/stdlib/unittest_util.py b/grumpy-runtime-src/third_party/stdlib/unittest_util.py index b717b50c..addd0fab 100644 --- a/grumpy-runtime-src/third_party/stdlib/unittest_util.py +++ b/grumpy-runtime-src/third_party/stdlib/unittest_util.py @@ -127,13 +127,13 @@ def __repr__(self): def _asdict(self): 'Return a new OrderedDict which maps field names to their values' # return OrderedDict(zip(self._fields, self)) - return dict(zip(self._fields, self)) + return dict(list(zip(self._fields, self))) def _replace(_self, **kwds): 'Return a new Mismatch object replacing specified fields with new values' - result = _self._make(map(kwds.pop, ('actual', 'expected', 'value'), _self)) + result = _self._make(list(map(kwds.pop, ('actual', 'expected', 'value'), _self))) if kwds: - raise ValueError('Got unexpected field names: %r' % kwds.keys()) + raise ValueError('Got unexpected field names: %r' % list(kwds.keys())) return result def __getnewargs__(self): @@ -199,12 +199,12 @@ def _count_diff_hashable(actual, expected): # elements must be hashable s, t = _ordered_count(actual), _ordered_count(expected) result = [] - for elem, cnt_s in s.items(): + for elem, cnt_s in list(s.items()): cnt_t = t.get(elem, 0) if cnt_s != cnt_t: diff = _Mismatch(cnt_s, cnt_t, elem) result.append(diff) - for elem, cnt_t in t.items(): + for elem, cnt_t in list(t.items()): if elem not in s: diff = _Mismatch(0, cnt_t, elem) result.append(diff) diff --git a/grumpy-runtime-src/third_party/stdlib/urlparse.py b/grumpy-runtime-src/third_party/stdlib/urlparse.py index 4fdf1f6c..c40fb3c1 100644 --- a/grumpy-runtime-src/third_party/stdlib/urlparse.py +++ b/grumpy-runtime-src/third_party/stdlib/urlparse.py @@ -153,13 +153,13 @@ def __repr__(self): def _asdict(self): 'Return a new OrderedDict which maps field names to their values' - return OrderedDict(zip(self._fields, self)) + return OrderedDict(list(zip(self._fields, self))) def _replace(_self, **kwds): 'Return a new SplitResult object replacing specified fields with new values' - result = _self._make(map(kwds.pop, ('scheme', 'netloc', 'path', 'query', 'fragment'), _self)) + result = _self._make(list(map(kwds.pop, ('scheme', 'netloc', 'path', 'query', 'fragment'), _self))) if kwds: - raise ValueError('Got unexpected field names: %r' % kwds.keys()) + raise ValueError('Got unexpected field names: %r' % list(kwds.keys())) return result def __getnewargs__(self): @@ -216,13 +216,13 @@ def __repr__(self): def _asdict(self): 'Return a new OrderedDict which maps field names to their values' - return OrderedDict(zip(self._fields, self)) + return OrderedDict(list(zip(self._fields, self))) def _replace(_self, **kwds): 'Return a new ParseResult object replacing specified fields with new values' - result = _self._make(map(kwds.pop, ('scheme', 'netloc', 'path', 'params', 'query', 'fragment'), _self)) + result = _self._make(list(map(kwds.pop, ('scheme', 'netloc', 'path', 'params', 'query', 'fragment'), _self))) if kwds: - raise ValueError('Got unexpected field names: %r' % kwds.keys()) + raise ValueError('Got unexpected field names: %r' % list(kwds.keys())) return result def __getnewargs__(self): @@ -437,13 +437,13 @@ def urldefrag(url): return url, '' try: - unicode + str except NameError: def _is_unicode(x): return 0 else: def _is_unicode(x): - return isinstance(x, unicode) + return isinstance(x, str) # unquote method for parse_qs and parse_qsl # Cannot use directly from urllib as it would create a circular reference @@ -536,7 +536,7 @@ def parse_qsl(qs, keep_blank_values=0, strict_parsing=0): nv = name_value.split('=', 1) if len(nv) != 2: if strict_parsing: - raise ValueError, "bad query field: %r" % (name_value,) + raise ValueError("bad query field: %r" % (name_value,)) # Handle case of a control-name with no equal sign if keep_blank_values: nv.append('') diff --git a/grumpy-runtime-src/third_party/stdlib/uu.py b/grumpy-runtime-src/third_party/stdlib/uu.py index f8fa4c47..8a5ae02e 100644 --- a/grumpy-runtime-src/third_party/stdlib/uu.py +++ b/grumpy-runtime-src/third_party/stdlib/uu.py @@ -48,7 +48,7 @@ def encode(in_file, out_file, name=None, mode=None): try: if in_file == '-': in_file = sys.stdin - elif isinstance(in_file, basestring): + elif isinstance(in_file, str): if name is None: name = os.path.basename(in_file) if mode is None: @@ -63,7 +63,7 @@ def encode(in_file, out_file, name=None, mode=None): # if out_file == '-': out_file = sys.stdout - elif isinstance(out_file, basestring): + elif isinstance(out_file, str): out_file = open(out_file, 'wb') opened_files.append(out_file) # @@ -72,11 +72,11 @@ def encode(in_file, out_file, name=None, mode=None): if name is None: name = '-' if mode is None: - mode = 0666 + mode = 0o666 # # Write the data # - out_file.write('begin %o %s\n' % ((mode&0777),name)) + out_file.write('begin %o %s\n' % ((mode&0o777),name)) data = in_file.read(45) while len(data) > 0: out_file.write(binascii.b2a_uu(data)) @@ -95,7 +95,7 @@ def decode(in_file, out_file=None, mode=None, quiet=0): opened_files = [] if in_file == '-': in_file = sys.stdin - elif isinstance(in_file, basestring): + elif isinstance(in_file, str): in_file = open(in_file) opened_files.append(in_file) try: @@ -126,7 +126,7 @@ def decode(in_file, out_file=None, mode=None, quiet=0): # if out_file == '-': out_file = sys.stdout - elif isinstance(out_file, basestring): + elif isinstance(out_file, str): fp = open(out_file, 'wb') try: os.path.chmod(out_file, mode) @@ -141,7 +141,7 @@ def decode(in_file, out_file=None, mode=None, quiet=0): while s and s.strip() != 'end': try: data = binascii.a2b_uu(s) - except binascii.Error, v: + except binascii.Error as v: # Workaround for broken uuencoders by /Fredrik Lundh nbytes = (((ord(s[0])-32) & 63) * 4 + 5) // 3 data = binascii.a2b_uu(s[:nbytes]) @@ -177,18 +177,18 @@ def test(): if options.decode: if options.text: - if isinstance(output, basestring): + if isinstance(output, str): output = open(output, 'w') else: - print sys.argv[0], ': cannot do -t to stdout' + print(sys.argv[0], ': cannot do -t to stdout') sys.exit(1) decode(input, output) else: if options.text: - if isinstance(input, basestring): + if isinstance(input, str): input = open(input, 'r') else: - print sys.argv[0], ': cannot do -t from stdin' + print(sys.argv[0], ': cannot do -t from stdin') sys.exit(1) encode(input, output) diff --git a/grumpy-runtime-src/third_party/stdlib/warnings.py b/grumpy-runtime-src/third_party/stdlib/warnings.py index 374bce89..bfb1bfc4 100644 --- a/grumpy-runtime-src/third_party/stdlib/warnings.py +++ b/grumpy-runtime-src/third_party/stdlib/warnings.py @@ -41,7 +41,7 @@ def _show_warning(message, category, filename, lineno, file=None, line=None): def formatwarning(message, category, filename, lineno, line=None): """Function to format a warning the standard way.""" try: - unicodetype = unicode + unicodetype = str except NameError: unicodetype = () try: @@ -53,13 +53,13 @@ def formatwarning(message, category, filename, lineno, line=None): if line: line = line.strip() if isinstance(s, unicodetype) and isinstance(line, str): - line = unicode(line, 'latin1') + line = str(line, 'latin1') s += " %s\n" % line if isinstance(s, unicodetype) and isinstance(filename, str): enc = sys.getfilesystemencoding() if enc: try: - filename = unicode(filename, enc) + filename = str(filename, enc) except UnicodeDecodeError: pass s = "%s:%s" % (filename, s) @@ -79,10 +79,10 @@ def filterwarnings(action, message="", category=Warning, module="", lineno=0, """ assert action in ("error", "ignore", "always", "default", "module", "once"), "invalid action: %r" % (action,) - assert isinstance(message, basestring), "message must be a string" + assert isinstance(message, str), "message must be a string" assert isinstance(category, type), "category must be a class" assert issubclass(category, Warning), "category must be a Warning subclass" - assert isinstance(module, basestring), "module must be a string" + assert isinstance(module, str), "module must be a string" assert isinstance(lineno, int) and lineno >= 0, \ "lineno must be an int >= 0" item = (action, re.compile(message, re.I), category, @@ -125,8 +125,8 @@ def _processoptions(args): for arg in args: try: _setoption(arg) - except _OptionError, msg: - print >>sys.stderr, "Invalid -W option ignored:", msg + except _OptionError as msg: + print("Invalid -W option ignored:", msg, file=sys.stderr) # Helper for _processoptions() def _setoption(arg): diff --git a/grumpy-tools-src/grumpy_tools/benchcmp.py b/grumpy-tools-src/grumpy_tools/benchcmp.py index eced9512..5f53fb16 100755 --- a/grumpy-tools-src/grumpy_tools/benchcmp.py +++ b/grumpy-tools-src/grumpy_tools/benchcmp.py @@ -16,7 +16,7 @@ """Runs two benchmark programs and compares their results.""" -from __future__ import print_function + import argparse import subprocess @@ -38,7 +38,7 @@ def main(args): results1 = _RunBenchmark(args.prog1) benchmarks = set(results1.keys()) results2 = {} - for _ in xrange(args.runs - 1): + for _ in range(args.runs - 1): _MergeResults(results1, _RunBenchmark(args.prog1), benchmarks) _MergeResults(results2, _RunBenchmark(args.prog2), benchmarks) _MergeResults(results2, _RunBenchmark(args.prog2), benchmarks) @@ -48,7 +48,7 @@ def main(args): def _MergeResults(merged, results, benchmarks): benchmarks = set(benchmarks) - for k, v in results.iteritems(): + for k, v in results.items(): if k not in benchmarks: _Die('unmatched benchmark: {}', k) merged[k] = max(merged.get(k, 0), v) diff --git a/grumpy-tools-src/grumpy_tools/cli.py b/grumpy-tools-src/grumpy_tools/cli.py index 736164ad..cec5a08e 100644 --- a/grumpy-tools-src/grumpy_tools/cli.py +++ b/grumpy-tools-src/grumpy_tools/cli.py @@ -3,7 +3,7 @@ """Console script for grumpy_tools.""" import os import sys -from StringIO import StringIO +from io import StringIO from pkg_resources import resource_filename, Requirement, DistributionNotFound import logging logger = logging.getLogger(__package__) diff --git a/grumpy-tools-src/grumpy_tools/compiler/util.py b/grumpy-tools-src/grumpy_tools/compiler/util.py index 3d517b67..c8e0a860 100644 --- a/grumpy-tools-src/grumpy_tools/compiler/util.py +++ b/grumpy-tools-src/grumpy_tools/compiler/util.py @@ -16,12 +16,12 @@ """Utilities for generating Go code.""" -from __future__ import unicode_literals + import codecs import contextlib import string -import StringIO +import io import textwrap try: @@ -65,7 +65,7 @@ class Writer(object): """Utility class for writing blocks of Go code to a file-like object.""" def __init__(self, out=None): - self.out = codecs.getwriter('utf8')(out or StringIO.StringIO()) + self.out = codecs.getwriter('utf8')(out or io.StringIO()) self.indent_level = 0 def getvalue(self): @@ -139,7 +139,7 @@ def dedent(self, n=1): def go_str(value): """Returns value as a valid Go string literal.""" - io = StringIO.StringIO() + io = io.StringIO() io.write('"') for c in value: if c in _ESCAPES: diff --git a/grumpy-tools-src/grumpy_tools/coverparse.py b/grumpy-tools-src/grumpy_tools/coverparse.py index a63e6fce..6917bad8 100755 --- a/grumpy-tools-src/grumpy_tools/coverparse.py +++ b/grumpy-tools-src/grumpy_tools/coverparse.py @@ -16,7 +16,7 @@ """Parse a Go coverage file and prints a message for lines missing coverage.""" -from __future__ import print_function + import collections import re @@ -39,7 +39,7 @@ def _ParseCover(f): raise RuntimeError('invalid coverage line: {!r}'.format(line)) filename, line_start, line_end, count = match.groups() if not int(count): - for i in xrange(int(line_start), int(line_end) + 1): + for i in range(int(line_start), int(line_end) + 1): uncovered[filename].add(i) return uncovered @@ -50,7 +50,7 @@ def main(): uncovered = _ParseCover(f) for filename in sorted(uncovered.keys()): for lineno in sorted(uncovered[filename]): - print('{}:{}'.format(filename, lineno)) + print(('{}:{}'.format(filename, lineno))) if __name__ == '__main__': diff --git a/grumpy-tools-src/grumpy_tools/diffrange.py b/grumpy-tools-src/grumpy_tools/diffrange.py index c56f4291..7b5a2897 100755 --- a/grumpy-tools-src/grumpy_tools/diffrange.py +++ b/grumpy-tools-src/grumpy_tools/diffrange.py @@ -16,7 +16,7 @@ """Convert a unified diff into a list of modified files and line numbers.""" -from __future__ import print_function + import sys @@ -32,7 +32,7 @@ def __init__(self, f): def __iter__(self): return self - def next(self): + def __next__(self): if self._next is not None: cur = self._next else: @@ -78,7 +78,7 @@ def main(): if line.startswith('+++'): filename = line.split()[1] for n in _ReadHunks(buf): - print('{}:{}'.format(filename, n)) + print(('{}:{}'.format(filename, n))) if __name__ == '__main__': diff --git a/grumpy-tools-src/grumpy_tools/genmake.py b/grumpy-tools-src/grumpy_tools/genmake.py index 774617f6..1a366ea8 100755 --- a/grumpy-tools-src/grumpy_tools/genmake.py +++ b/grumpy-tools-src/grumpy_tools/genmake.py @@ -16,7 +16,7 @@ """Generate a Makefile for Python targets in a GOPATH directory.""" -from __future__ import print_function + import argparse import os diff --git a/grumpy-tools-src/grumpy_tools/grumpc.py b/grumpy-tools-src/grumpy_tools/grumpc.py index 8e1bd789..60122631 100755 --- a/grumpy-tools-src/grumpy_tools/grumpc.py +++ b/grumpy-tools-src/grumpy_tools/grumpc.py @@ -17,12 +17,12 @@ """A Python -> Go transcompiler.""" -from __future__ import unicode_literals + import argparse import os import sys -from StringIO import StringIO +from io import StringIO import textwrap import pickle import logging diff --git a/grumpy-tools-src/grumpy_tools/grumprun.py b/grumpy-tools-src/grumpy_tools/grumprun.py index 90761ee3..ef6a605c 100755 --- a/grumpy-tools-src/grumpy_tools/grumprun.py +++ b/grumpy-tools-src/grumpy_tools/grumprun.py @@ -29,7 +29,7 @@ import sys import tempfile import logging -from StringIO import StringIO +from io import StringIO from .compiler import imputil from .pep_support.pep3147pycache import make_transpiled_module_folders diff --git a/grumpy-tools-src/grumpy_tools/pydeps.py b/grumpy-tools-src/grumpy_tools/pydeps.py index a26d9de4..c3d189c3 100755 --- a/grumpy-tools-src/grumpy_tools/pydeps.py +++ b/grumpy-tools-src/grumpy_tools/pydeps.py @@ -15,7 +15,7 @@ # limitations under the License. """Outputs names of modules imported by a script.""" -from __future__ import absolute_import + import os import sys @@ -42,7 +42,7 @@ def _deps(): else: parts = imp.name.split('.') # Iterate over all packages and the leaf module. - for i in xrange(len(parts)): + for i in range(len(parts)): name = '.'.join(parts[:i+1]) if name and name not in names: names.add(name) diff --git a/grumpy-tools-src/tests/dummymodule/__init__.py b/grumpy-tools-src/tests/dummymodule/__init__.py index 8e04a22c..651857d0 100644 --- a/grumpy-tools-src/tests/dummymodule/__init__.py +++ b/grumpy-tools-src/tests/dummymodule/__init__.py @@ -1,4 +1,4 @@ -import dummysubmodule1 +from tests.dummymodule import dummysubmodule1 def dummyfunc0(): print("Func0") diff --git a/grumpy-tools-src/tests/dummymodule/dummysubmodule1/__init__.py b/grumpy-tools-src/tests/dummymodule/dummysubmodule1/__init__.py index d2455ce7..88fca532 100644 --- a/grumpy-tools-src/tests/dummymodule/dummysubmodule1/__init__.py +++ b/grumpy-tools-src/tests/dummymodule/dummysubmodule1/__init__.py @@ -1,5 +1,5 @@ -import dummysubmodule2 -import dummysubmodule2b +from tests.dummymodule.dummysubmodule1 import dummysubmodule2 +from tests.dummymodule.dummysubmodule1 import dummysubmodule2b def dummyfunc1(): print("Func1") diff --git a/grumpy-tools-src/tests/import_havingpkgmain.py b/grumpy-tools-src/tests/import_havingpkgmain.py index c0dcfbb9..875ff541 100644 --- a/grumpy-tools-src/tests/import_havingpkgmain.py +++ b/grumpy-tools-src/tests/import_havingpkgmain.py @@ -1,4 +1,4 @@ -from __future__ import print_function + print('STARTING') from havingmainpkg.__main__ import main From e19c142a5f13538bca9e9d6bf4f50a9c9f0714c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=87a=C4=9F=C4=B1l=20Ulu=C5=9Fahin?= Date: Tue, 18 Sep 2018 20:42:54 +0100 Subject: [PATCH 2/4] more refactoring --- .../benchmarks/comprehension.py | 2 +- grumpy-runtime-src/benchmarks/loop.py | 2 +- grumpy-runtime-src/lib/cStringIO.py | 14 +-- grumpy-runtime-src/lib/itertools.py | 2 +- grumpy-runtime-src/setup.py | 2 +- grumpy-runtime-src/testing/builtin_test.py | 2 +- grumpy-runtime-src/testing/import_test.py | 2 +- .../ouroboros/test/test_operator.py | 8 +- .../third_party/pypy/_collections.py | 2 +- grumpy-runtime-src/third_party/pypy/_csv.py | 2 +- .../third_party/pypy/_functools.py | 2 +- .../third_party/stdlib/StringIO.py | 14 +-- .../third_party/stdlib/UserDict.py | 20 ++-- .../third_party/stdlib/base64.py | 6 +- .../third_party/stdlib/collections.py | 8 +- .../third_party/stdlib/fpformat.py | 2 +- .../third_party/stdlib/getopt.py | 2 +- .../third_party/stdlib/heapq.py | 10 +- .../third_party/stdlib/json/__init__.py | 2 +- .../third_party/stdlib/json/decoder.py | 12 +- .../third_party/stdlib/json/encoder.py | 28 ++--- .../third_party/stdlib/test/list_tests.py | 26 ++--- .../third_party/stdlib/test/lock_tests.py | 4 +- .../third_party/stdlib/test/mapping_tests.py | 104 +++++++++--------- .../third_party/stdlib/test/seq_tests.py | 56 +++++----- .../third_party/stdlib/test/string_tests.py | 76 ++++++------- .../third_party/stdlib/test/test_argparse.py | 20 ++-- .../third_party/stdlib/test/test_bisect.py | 18 +-- .../third_party/stdlib/test/test_datetime.py | 32 +++--- .../third_party/stdlib/test/test_dict.py | 42 +++---- .../stdlib/test/test_dummy_thread.py | 30 ++--- .../stdlib/test/test_genericpath.py | 24 ++-- .../third_party/stdlib/test/test_list.py | 2 +- .../third_party/stdlib/test/test_mimetools.py | 16 +-- .../third_party/stdlib/test/test_queue.py | 34 +++--- .../third_party/stdlib/test/test_quopri.py | 10 +- .../third_party/stdlib/test/test_rfc822.py | 10 +- .../third_party/stdlib/test/test_select.py | 6 +- .../third_party/stdlib/test/test_slice.py | 6 +- .../third_party/stdlib/test/test_stat.py | 4 +- .../third_party/stdlib/test/test_string.py | 22 ++-- .../third_party/stdlib/test/test_support.py | 12 +- .../third_party/stdlib/test/test_threading.py | 66 +++++------ .../third_party/stdlib/test/test_tuple.py | 6 +- .../third_party/stdlib/test/test_uu.py | 68 ++++++------ .../third_party/stdlib/textwrap.py | 2 +- .../third_party/stdlib/unittest_case.py | 2 +- grumpy-runtime-src/third_party/stdlib/uu.py | 4 +- 48 files changed, 423 insertions(+), 423 deletions(-) diff --git a/grumpy-runtime-src/benchmarks/comprehension.py b/grumpy-runtime-src/benchmarks/comprehension.py index 7eee77f5..51bf7e35 100644 --- a/grumpy-runtime-src/benchmarks/comprehension.py +++ b/grumpy-runtime-src/benchmarks/comprehension.py @@ -37,7 +37,7 @@ def BenchmarkListCompCreate(b): def BenchmarkDictCompCreate(b): for _ in range(b.N): - {x: x for x in range(1000)} # pylint: disable=expression-not-assigned + {x: x for x in list(range(1000))} # pylint: disable=expression-not-assigned if __name__ == '__main__': diff --git a/grumpy-runtime-src/benchmarks/loop.py b/grumpy-runtime-src/benchmarks/loop.py index e3e5869f..2157545f 100644 --- a/grumpy-runtime-src/benchmarks/loop.py +++ b/grumpy-runtime-src/benchmarks/loop.py @@ -29,7 +29,7 @@ def BenchmarkWhileCounter(b): def BenchmarkWhileXRange(b): - i = iter(range(b.N)) + i = iter(list(range(b.N))) try: while True: next(i) diff --git a/grumpy-runtime-src/lib/cStringIO.py b/grumpy-runtime-src/lib/cStringIO.py index 72dcb200..15f9399f 100644 --- a/grumpy-runtime-src/lib/cStringIO.py +++ b/grumpy-runtime-src/lib/cStringIO.py @@ -291,14 +291,14 @@ def test(): if f.getvalue() != text: raise RuntimeError('write failed') length = f.tell() - print('File length =', length) + print(('File length =', length)) f.seek(len(lines[0])) f.write(lines[1]) f.seek(0) - print('First line =', repr(f.readline())) - print('Position =', f.tell()) + print(('First line =', repr(f.readline()))) + print(('Position =', f.tell())) line = f.readline() - print('Second line =', repr(line)) + print(('Second line =', repr(line))) f.seek(-len(line), 1) line2 = f.read(len(line)) if line != line2: @@ -310,13 +310,13 @@ def test(): line2 = f.read() if line != line2: raise RuntimeError('bad result after seek back from EOF') - print('Read', len(list), 'more lines') - print('File length =', f.tell()) + print(('Read', len(list), 'more lines')) + print(('File length =', f.tell())) if f.tell() != length: raise RuntimeError('bad length') f.truncate(length/2) f.seek(0, 2) - print('Truncated length =', f.tell()) + print(('Truncated length =', f.tell())) if f.tell() != length/2: raise RuntimeError('truncate did not adjust length') f.close() diff --git a/grumpy-runtime-src/lib/itertools.py b/grumpy-runtime-src/lib/itertools.py index f715901d..416f9c67 100644 --- a/grumpy-runtime-src/lib/itertools.py +++ b/grumpy-runtime-src/lib/itertools.py @@ -133,7 +133,7 @@ def imap(function, *iterables): def islice(iterable, *args): s = slice(*args) - it = iter(range(s.start or 0, s.stop or sys.maxsize, s.step or 1)) + it = iter(list(range(s.start or 0, s.stop or sys.maxsize, s.step or 1))) nexti = next(it) for i, element in enumerate(iterable): if i == nexti: diff --git a/grumpy-runtime-src/setup.py b/grumpy-runtime-src/setup.py index bcb14a43..18940c24 100644 --- a/grumpy-runtime-src/setup.py +++ b/grumpy-runtime-src/setup.py @@ -86,7 +86,7 @@ def _glob_deep(directory, pattern, rmtree=None): filename = os.path.join(root, basename) for filtered_name in blacklisted: if filtered_name in filename: - print('Trying to rmtree', filename) + print(('Trying to rmtree', filename)) shutil.rmtree(filename, ignore_errors=True) continue # Skip this blacklisted one. yield filename diff --git a/grumpy-runtime-src/testing/builtin_test.py b/grumpy-runtime-src/testing/builtin_test.py index f232ced4..bf5aeccf 100644 --- a/grumpy-runtime-src/testing/builtin_test.py +++ b/grumpy-runtime-src/testing/builtin_test.py @@ -346,7 +346,7 @@ class Foo(object): assert list(map(str, (1, 2, 3))) == ["1", "2", "3"] # assert map(str, (1.0, 2.0, 3.0)) == ["1", "2", "3"] assert list(map(str, list(range(3)))) == ["0", "1", "2"] -assert list(map(str, range(3))) == ["0", "1", "2"] +assert list(map(str, list(range(3)))) == ["0", "1", "2"] assert list(map(int, ["1", "2", "3"])) == [1, 2, 3] assert list(map(int, "123")) == [1, 2, 3] assert list(map(int, {"1": "a", "2": "b"})) == [1, 2] diff --git a/grumpy-runtime-src/testing/import_test.py b/grumpy-runtime-src/testing/import_test.py index 1896e7bd..08f65758 100644 --- a/grumpy-runtime-src/testing/import_test.py +++ b/grumpy-runtime-src/testing/import_test.py @@ -14,4 +14,4 @@ import sys -print(sys.maxsize) +print((sys.maxsize)) diff --git a/grumpy-runtime-src/third_party/ouroboros/test/test_operator.py b/grumpy-runtime-src/third_party/ouroboros/test/test_operator.py index 3ba34b88..24cfeddf 100644 --- a/grumpy-runtime-src/third_party/ouroboros/test/test_operator.py +++ b/grumpy-runtime-src/third_party/ouroboros/test/test_operator.py @@ -158,7 +158,7 @@ def test_truediv(self): def test_getitem(self): #operator = self.module - a = range(10) + a = list(range(10)) self.assertRaises(TypeError, operator.getitem) self.assertRaises(TypeError, operator.getitem, a, None) self.assertTrue(operator.getitem(a, 2) == 2) @@ -240,8 +240,8 @@ def test_contains(self): #operator = self.module self.assertRaises(TypeError, operator.contains) self.assertRaises(TypeError, operator.contains, None, None) - self.assertTrue(operator.contains(range(4), 2)) - self.assertFalse(operator.contains(range(4), 5)) + self.assertTrue(operator.contains(list(range(4)), 2)) + self.assertFalse(operator.contains(list(range(4)), 5)) def test_setitem(self): #operator = self.module @@ -377,7 +377,7 @@ def __getitem__(self, name): [('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)]) # multiple gets - data = list(map(str, range(20))) + data = list(map(str, list(range(20)))) self.assertEqual(operator.itemgetter(2,10,5)(data), ('2', '10', '5')) self.assertRaises(TypeError, operator.itemgetter(2, 'x', 5), data) diff --git a/grumpy-runtime-src/third_party/pypy/_collections.py b/grumpy-runtime-src/third_party/pypy/_collections.py index 0d6fc362..c1d671fd 100644 --- a/grumpy-runtime-src/third_party/pypy/_collections.py +++ b/grumpy-runtime-src/third_party/pypy/_collections.py @@ -433,5 +433,5 @@ def __reduce__(self): This API is used by pickle.py and copy.py. """ - return (type(self), (self.default_factory,), None, None, iter(self.items())) + return (type(self), (self.default_factory,), None, None, iter(list(self.items()))) diff --git a/grumpy-runtime-src/third_party/pypy/_csv.py b/grumpy-runtime-src/third_party/pypy/_csv.py index 7de3a66a..a46a8abc 100644 --- a/grumpy-runtime-src/third_party/pypy/_csv.py +++ b/grumpy-runtime-src/third_party/pypy/_csv.py @@ -95,7 +95,7 @@ def __new__(cls, dialect, **kwargs): # Can we reuse this instance? if (isinstance(dialect, Dialect) - and all(value is None for value in iter(kwargs.values()))): + and all(value is None for value in iter(list(kwargs.values())))): return dialect self = object.__new__(cls) diff --git a/grumpy-runtime-src/third_party/pypy/_functools.py b/grumpy-runtime-src/third_party/pypy/_functools.py index e0e2ff29..0f7c3912 100644 --- a/grumpy-runtime-src/third_party/pypy/_functools.py +++ b/grumpy-runtime-src/third_party/pypy/_functools.py @@ -63,7 +63,7 @@ def __call__(self, *fargs, **fkeywords): return self._func(*(self._args + fargs), **fkeywords) def __reduce__(self): - d = dict((k, v) for k, v in iter(self.__dict__.items()) if k not in + d = dict((k, v) for k, v in iter(list(self.__dict__.items())) if k not in ('_func', '_args', '_keywords')) if len(d) == 0: d = None diff --git a/grumpy-runtime-src/third_party/stdlib/StringIO.py b/grumpy-runtime-src/third_party/stdlib/StringIO.py index 72dcb200..15f9399f 100644 --- a/grumpy-runtime-src/third_party/stdlib/StringIO.py +++ b/grumpy-runtime-src/third_party/stdlib/StringIO.py @@ -291,14 +291,14 @@ def test(): if f.getvalue() != text: raise RuntimeError('write failed') length = f.tell() - print('File length =', length) + print(('File length =', length)) f.seek(len(lines[0])) f.write(lines[1]) f.seek(0) - print('First line =', repr(f.readline())) - print('Position =', f.tell()) + print(('First line =', repr(f.readline()))) + print(('Position =', f.tell())) line = f.readline() - print('Second line =', repr(line)) + print(('Second line =', repr(line))) f.seek(-len(line), 1) line2 = f.read(len(line)) if line != line2: @@ -310,13 +310,13 @@ def test(): line2 = f.read() if line != line2: raise RuntimeError('bad result after seek back from EOF') - print('Read', len(list), 'more lines') - print('File length =', f.tell()) + print(('Read', len(list), 'more lines')) + print(('File length =', f.tell())) if f.tell() != length: raise RuntimeError('bad length') f.truncate(length/2) f.seek(0, 2) - print('Truncated length =', f.tell()) + print(('Truncated length =', f.tell())) if f.tell() != length/2: raise RuntimeError('truncate did not adjust length') f.close() diff --git a/grumpy-runtime-src/third_party/stdlib/UserDict.py b/grumpy-runtime-src/third_party/stdlib/UserDict.py index b535ab9d..aa57ca3e 100644 --- a/grumpy-runtime-src/third_party/stdlib/UserDict.py +++ b/grumpy-runtime-src/third_party/stdlib/UserDict.py @@ -55,9 +55,9 @@ def copy(self): return c def keys(self): return list(self.data.keys()) def items(self): return list(self.data.items()) - def iteritems(self): return iter(self.data.items()) - def iterkeys(self): return iter(self.data.keys()) - def itervalues(self): return iter(self.data.values()) + def iteritems(self): return iter(list(self.data.items())) + def iterkeys(self): return iter(list(self.data.keys())) + def itervalues(self): return iter(list(self.data.values())) def values(self): return list(self.data.values()) def has_key(self, key): return key in self.data def update(*args, **kwargs): @@ -148,10 +148,10 @@ def iterkeys(self): # fourth level uses definitions from lower levels def itervalues(self): - for _, v in self.items(): + for _, v in list(self.items()): yield v def values(self): - return [v for _, v in self.items()] + return [v for _, v in list(self.items())] def items(self): return list(self.items()) def clear(self): @@ -177,7 +177,7 @@ def pop(self, key, *args): return value def popitem(self): try: - k, v = next(iter(self.items())) + k, v = next(iter(list(self.items()))) except StopIteration: raise KeyError('container is empty') del self[k] @@ -187,7 +187,7 @@ def update(self, other=None, **kwargs): if other is None: pass elif hasattr(other, 'iteritems'): # iteritems saves memory and lookups - for k, v in other.items(): + for k, v in list(other.items()): self[k] = v elif hasattr(other, 'keys'): for k in list(other.keys()): @@ -203,12 +203,12 @@ def get(self, key, default=None): except KeyError: return default def __repr__(self): - return repr(dict(iter(self.items()))) + return repr(dict(iter(list(self.items())))) def __cmp__(self, other): if other is None: return 1 if isinstance(other, DictMixin): - other = dict(iter(other.items())) - return cmp(dict(iter(self.items())), other) + other = dict(iter(list(other.items()))) + return cmp(dict(iter(list(self.items()))), other) def __len__(self): return len(list(self.keys())) diff --git a/grumpy-runtime-src/third_party/stdlib/base64.py b/grumpy-runtime-src/third_party/stdlib/base64.py index 3e3caeb3..42072669 100755 --- a/grumpy-runtime-src/third_party/stdlib/base64.py +++ b/grumpy-runtime-src/third_party/stdlib/base64.py @@ -339,10 +339,10 @@ def test(): except getopt.error as msg: sys.stdout = sys.stderr print(msg) - print("""usage: %s [-d|-e|-u|-t] [file|-] + print(("""usage: %s [-d|-e|-u|-t] [file|-] -d, -u: decode -e: encode (default) - -t: encode and decode string 'Aladdin:open sesame'"""%sys.argv[0]) + -t: encode and decode string 'Aladdin:open sesame'"""%sys.argv[0])) sys.exit(2) func = encode for o, a in opts: @@ -361,7 +361,7 @@ def test1(): s0 = "Aladdin:open sesame" s1 = encodestring(s0) s2 = decodestring(s1) - print(s0, repr(s1), s2) + print((s0, repr(s1), s2)) if __name__ == '__main__': diff --git a/grumpy-runtime-src/third_party/stdlib/collections.py b/grumpy-runtime-src/third_party/stdlib/collections.py index eab0e45e..3f74731a 100644 --- a/grumpy-runtime-src/third_party/stdlib/collections.py +++ b/grumpy-runtime-src/third_party/stdlib/collections.py @@ -501,8 +501,8 @@ def most_common(self, n=None): ''' # Emulate Bag.sortedByCount from Smalltalk if n is None: - return sorted(iter(self.items()), key=_itemgetter(1), reverse=True) - return _heapq.nlargest(n, iter(self.items()), key=_itemgetter(1)) + return sorted(iter(list(self.items())), key=_itemgetter(1), reverse=True) + return _heapq.nlargest(n, iter(list(self.items())), key=_itemgetter(1)) def elements(self): '''Iterator over elements repeating each as many times as its count. @@ -524,7 +524,7 @@ def elements(self): ''' # Emulate Bag.do from Smalltalk and Multiset.begin from C++. - return _chain.from_iterable(_starmap(_repeat, iter(self.items()))) + return _chain.from_iterable(_starmap(_repeat, iter(list(self.items())))) # Override dict methods where necessary @@ -567,7 +567,7 @@ def update(*args, **kwds): if isinstance(iterable, Mapping): if self: self_get = self.get - for elem, count in iterable.items(): + for elem, count in list(iterable.items()): self[elem] = self_get(elem, 0) + count else: super(Counter, self).update(iterable) # fast path when counter is empty diff --git a/grumpy-runtime-src/third_party/stdlib/fpformat.py b/grumpy-runtime-src/third_party/stdlib/fpformat.py index fd4d7114..14ebd893 100644 --- a/grumpy-runtime-src/third_party/stdlib/fpformat.py +++ b/grumpy-runtime-src/third_party/stdlib/fpformat.py @@ -140,6 +140,6 @@ def test(): try: while 1: x, digs = eval(input('Enter (x, digs): ')) - print(x, fix(x, digs), sci(x, digs)) + print((x, fix(x, digs), sci(x, digs))) except (EOFError, KeyboardInterrupt): pass diff --git a/grumpy-runtime-src/third_party/stdlib/getopt.py b/grumpy-runtime-src/third_party/stdlib/getopt.py index 79575f67..bc3111ff 100644 --- a/grumpy-runtime-src/third_party/stdlib/getopt.py +++ b/grumpy-runtime-src/third_party/stdlib/getopt.py @@ -207,4 +207,4 @@ def short_has_arg(opt, shortopts): if __name__ == '__main__': import sys - print(getopt(sys.argv[1:], "a:b", ["alpha=", "beta"])) + print((getopt(sys.argv[1:], "a:b", ["alpha=", "beta"]))) diff --git a/grumpy-runtime-src/third_party/stdlib/heapq.py b/grumpy-runtime-src/third_party/stdlib/heapq.py index b76ee38b..7532b114 100644 --- a/grumpy-runtime-src/third_party/stdlib/heapq.py +++ b/grumpy-runtime-src/third_party/stdlib/heapq.py @@ -191,7 +191,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(range(n//2)): + for i in reversed(list(range(n//2))): _siftup(x, i) def _heappushpop_max(heap, item): @@ -429,13 +429,13 @@ def nsmallest(n, iterable, key=None): # When key is none, use simpler decoration if key is None: - it = zip(iterable, count()) # decorate + it = list(zip(iterable, count())) # decorate result = _nsmallest(n, it) return list(map(itemgetter(0), result)) # undecorate # General case, slowest method in1, in2 = tee(iterable) - it = zip(map(key, in1), count(), in2) # decorate + it = list(zip(list(map(key, in1)), count(), in2)) # decorate result = _nsmallest(n, it) return list(map(itemgetter(2), result)) # undecorate @@ -467,13 +467,13 @@ def nlargest(n, iterable, key=None): # When key is none, use simpler decoration if key is None: - it = zip(iterable, count(0,-1)) # decorate + it = list(zip(iterable, count(0,-1))) # decorate result = _nlargest(n, it) return list(map(itemgetter(0), result)) # undecorate # General case, slowest method in1, in2 = tee(iterable) - it = zip(map(key, in1), count(0,-1), in2) # decorate + it = list(zip(list(map(key, in1)), count(0,-1), in2)) # decorate result = _nlargest(n, it) return list(map(itemgetter(2), result)) # undecorate diff --git a/grumpy-runtime-src/third_party/stdlib/json/__init__.py b/grumpy-runtime-src/third_party/stdlib/json/__init__.py index 9541a096..8dd2ff6e 100644 --- a/grumpy-runtime-src/third_party/stdlib/json/__init__.py +++ b/grumpy-runtime-src/third_party/stdlib/json/__init__.py @@ -136,7 +136,7 @@ def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, will be skipped instead of raising a ``TypeError``. If ``ensure_ascii`` is true (the default), all non-ASCII characters in the - output are escaped with ``\uXXXX`` sequences, and the result is a ``str`` + output are escaped with ``\\uXXXX`` sequences, and the result is a ``str`` instance consisting of ASCII characters only. If ``ensure_ascii`` is ``False``, some chunks written to ``fp`` may be ``unicode`` instances. This usually happens because the input contains unicode strings or the diff --git a/grumpy-runtime-src/third_party/stdlib/json/decoder.py b/grumpy-runtime-src/third_party/stdlib/json/decoder.py index ea40886c..fa4b0feb 100644 --- a/grumpy-runtime-src/third_party/stdlib/json/decoder.py +++ b/grumpy-runtime-src/third_party/stdlib/json/decoder.py @@ -59,8 +59,8 @@ def errmsg(msg, doc, pos, end=None): STRINGCHUNK = re.compile(r'(.*?)(["\\\x00-\x1f])', FLAGS) BACKSLASH = { - '"': u'"', '\\': u'\\', '/': u'/', - 'b': u'\b', 'f': u'\f', 'n': u'\n', 'r': u'\r', 't': u'\t', + '"': '"', '\\': '\\', '/': '/', + 'b': '\b', 'f': '\f', 'n': '\n', 'r': '\r', 't': '\t', } DEFAULT_ENCODING = "utf-8" @@ -99,8 +99,8 @@ def py_scanstring(s, end, encoding=None, strict=True, content, terminator = chunk.groups() # Content is contains zero or more unescaped string characters if content: - if not isinstance(content, unicode): - content = unicode(content, encoding) + if not isinstance(content, str): + content = str(content, encoding) _append(content) # Terminator is the end of string, a literal control character, # or a backslash denoting that an escape sequence follows @@ -138,10 +138,10 @@ def py_scanstring(s, end, encoding=None, strict=True, if 0xdc00 <= uni2 <= 0xdfff: uni = 0x10000 + (((uni - 0xd800) << 10) | (uni2 - 0xdc00)) end += 6 - char = unichr(uni) + char = chr(uni) # Append the unescaped character _append(char) - return u''.join(chunks), end + return ''.join(chunks), end # Use speedup if available diff --git a/grumpy-runtime-src/third_party/stdlib/json/encoder.py b/grumpy-runtime-src/third_party/stdlib/json/encoder.py index ca7a25da..6fc5f1ba 100644 --- a/grumpy-runtime-src/third_party/stdlib/json/encoder.py +++ b/grumpy-runtime-src/third_party/stdlib/json/encoder.py @@ -118,7 +118,7 @@ def __init__(self, skipkeys=False, ensure_ascii=True, skipkeys is True, such items are simply skipped. If *ensure_ascii* is true (the default), all non-ASCII - characters in the output are escaped with \uXXXX sequences, + characters in the output are escaped with \\uXXXX sequences, and the results are str instances consisting of ASCII characters only. If ensure_ascii is False, a result may be a unicode instance. This usually happens if the input contains @@ -201,7 +201,7 @@ def encode(self, o): """ # This is for extremely simple cases and benchmarks. - if isinstance(o, basestring): + if isinstance(o, str): if isinstance(o, str): _encoding = self.encoding if (_encoding is not None @@ -283,14 +283,14 @@ def _make_iterencode(markers, _default, _encoder, _indent, _floatstr, _key_separator, _item_separator, _sort_keys, _skipkeys, _one_shot, ## HACK: hand-optimized bytecode; turn globals into locals ValueError=ValueError, - basestring=basestring, + str=str, dict=dict, float=float, id=id, int=int, isinstance=isinstance, list=list, - long=long, + long=int, str=str, tuple=tuple, ): @@ -319,7 +319,7 @@ def _iterencode_list(lst, _current_indent_level): first = False else: buf = separator - if isinstance(value, basestring): + if isinstance(value, str): yield buf + _encoder(value) elif value is None: yield buf + 'null' @@ -327,7 +327,7 @@ def _iterencode_list(lst, _current_indent_level): yield buf + 'true' elif value is False: yield buf + 'false' - elif isinstance(value, (int, long)): + elif isinstance(value, int): yield buf + str(value) elif isinstance(value, float): yield buf + _floatstr(value) @@ -368,11 +368,11 @@ def _iterencode_dict(dct, _current_indent_level): item_separator = _item_separator first = True if _sort_keys: - items = sorted(dct.items(), key=lambda kv: kv[0]) + items = sorted(list(dct.items()), key=lambda kv: kv[0]) else: - items = dct.iteritems() + items = iter(dct.items()) for key, value in items: - if isinstance(key, basestring): + if isinstance(key, str): pass # JavaScript is weakly typed for these, so it makes sense to # also allow them. Many encoders seem to do something like this. @@ -384,7 +384,7 @@ def _iterencode_dict(dct, _current_indent_level): key = 'false' elif key is None: key = 'null' - elif isinstance(key, (int, long)): + elif isinstance(key, int): key = str(key) elif _skipkeys: continue @@ -396,7 +396,7 @@ def _iterencode_dict(dct, _current_indent_level): yield item_separator yield _encoder(key) yield _key_separator - if isinstance(value, basestring): + if isinstance(value, str): yield _encoder(value) elif value is None: yield 'null' @@ -404,7 +404,7 @@ def _iterencode_dict(dct, _current_indent_level): yield 'true' elif value is False: yield 'false' - elif isinstance(value, (int, long)): + elif isinstance(value, int): yield str(value) elif isinstance(value, float): yield _floatstr(value) @@ -425,7 +425,7 @@ def _iterencode_dict(dct, _current_indent_level): del markers[markerid] def _iterencode(o, _current_indent_level): - if isinstance(o, basestring): + if isinstance(o, str): yield _encoder(o) elif o is None: yield 'null' @@ -433,7 +433,7 @@ def _iterencode(o, _current_indent_level): yield 'true' elif o is False: yield 'false' - elif isinstance(o, (int, long)): + elif isinstance(o, int): yield str(o) elif isinstance(o, float): yield _floatstr(o) diff --git a/grumpy-runtime-src/third_party/stdlib/test/list_tests.py b/grumpy-runtime-src/third_party/stdlib/test/list_tests.py index b468b682..96596f8c 100644 --- a/grumpy-runtime-src/third_party/stdlib/test/list_tests.py +++ b/grumpy-runtime-src/third_party/stdlib/test/list_tests.py @@ -65,7 +65,7 @@ class CommonTest(seq_tests.CommonTest): # os.remove(test_support.TESTFN) def test_set_subscript(self): - a = self.type2test(range(20)) + a = self.type2test(list(range(20))) self.assertRaises(ValueError, a.__setitem__, slice(0, 10, 0), [1,2,3]) self.assertRaises(TypeError, a.__setitem__, slice(0, 10), 1) self.assertRaises(ValueError, a.__setitem__, slice(0, 10, 2), [1,2]) @@ -103,16 +103,16 @@ def test_setitem(self): self.assertRaises(TypeError, a.__setitem__) a = self.type2test([0,1,2,3,4]) - a[0L] = 1 - a[1L] = 2 - a[2L] = 3 + a[0] = 1 + a[1] = 2 + a[2] = 3 self.assertEqual(a, self.type2test([1,2,3,3,4])) a[0] = 5 a[1] = 6 a[2] = 7 self.assertEqual(a, self.type2test([5,6,7,3,4])) - a[-2L] = 88 - a[-1L] = 99 + a[-2] = 88 + a[-1] = 99 self.assertEqual(a, self.type2test([5,6,7,88,99])) a[-2] = 8 a[-1] = 9 @@ -195,8 +195,8 @@ def test_delslice(self): self.assertEqual(a, self.type2test([])) a = self.type2test([0, 1]) - del a[1L:2L] - del a[0L:1L] + del a[1:2] + del a[0:1] self.assertEqual(a, self.type2test([])) a = self.type2test([0, 1]) @@ -204,7 +204,7 @@ def test_delslice(self): self.assertEqual(a, self.type2test([1])) a = self.type2test([0, 1]) - del a[-2L:-1L] + del a[-2:-1] self.assertEqual(a, self.type2test([1])) a = self.type2test([0, 1]) @@ -213,8 +213,8 @@ def test_delslice(self): self.assertEqual(a, self.type2test([])) a = self.type2test([0, 1]) - del a[1L:] - del a[:1L] + del a[1:] + del a[:1] self.assertEqual(a, self.type2test([])) a = self.type2test([0, 1]) @@ -222,7 +222,7 @@ def test_delslice(self): self.assertEqual(a, self.type2test([0])) a = self.type2test([0, 1]) - del a[-1L:] + del a[-1:] self.assertEqual(a, self.type2test([0])) a = self.type2test([0, 1]) @@ -442,7 +442,7 @@ def revcmp(a, b): # The following dumps core in unpatched Python 1.5: def myComparison(x,y): return cmp(x%3, y%7) - z = self.type2test(range(12)) + z = self.type2test(list(range(12))) z.sort(myComparison) self.assertRaises(TypeError, z.sort, 2) diff --git a/grumpy-runtime-src/third_party/stdlib/test/lock_tests.py b/grumpy-runtime-src/third_party/stdlib/test/lock_tests.py index 882112fd..461eb3d3 100644 --- a/grumpy-runtime-src/third_party/stdlib/test/lock_tests.py +++ b/grumpy-runtime-src/third_party/stdlib/test/lock_tests.py @@ -4,7 +4,7 @@ import sys import time -from thread import start_new_thread, get_ident +from _thread import start_new_thread, get_ident import threading import unittest @@ -451,7 +451,7 @@ class BaseSemaphoreTests(BaseTestCase): def test_constructor(self): self.assertRaises(ValueError, self.semtype, value = -1) - self.assertRaises(ValueError, self.semtype, value = -sys.maxint) + self.assertRaises(ValueError, self.semtype, value = -sys.maxsize) def test_acquire(self): sem = self.semtype(1) diff --git a/grumpy-runtime-src/third_party/stdlib/test/mapping_tests.py b/grumpy-runtime-src/third_party/stdlib/test/mapping_tests.py index 1c8cfd90..e1bd89ca 100644 --- a/grumpy-runtime-src/third_party/stdlib/test/mapping_tests.py +++ b/grumpy-runtime-src/third_party/stdlib/test/mapping_tests.py @@ -23,7 +23,7 @@ def _full_mapping(self, data): """Return a mapping object with the value contained in data dictionary""" x = self._empty_mapping() - for key, value in data.items(): + for key, value in list(data.items()): x[key] = value return x @@ -49,9 +49,9 @@ def test_read(self): if d is p: p = p1 #Indexing - for key, value in self.reference.items(): + for key, value in list(self.reference.items()): self.assertEqual(d[key], value) - knownkey = self.other.keys()[0] + knownkey = list(self.other.keys())[0] self.assertRaises(KeyError, lambda:d[knownkey]) #len self.assertEqual(len(p), 0) @@ -64,9 +64,9 @@ def test_read(self): #has_key with test_support.check_py3k_warnings(quiet=True): for k in self.reference: - self.assertTrue(d.has_key(k)) + self.assertTrue(k in d) for k in self.other: - self.assertFalse(d.has_key(k)) + self.assertFalse(k in d) #cmp self.assertEqual(cmp(p,p), 0) self.assertEqual(cmp(d,d), 0) @@ -81,13 +81,13 @@ def check_iterandlist(iter, lst, ref): self.assertTrue(hasattr(iter, '__iter__')) x = list(iter) self.assertTrue(set(x)==set(lst)==set(ref)) - check_iterandlist(d.iterkeys(), d.keys(), self.reference.keys()) - check_iterandlist(iter(d), d.keys(), self.reference.keys()) - check_iterandlist(d.itervalues(), d.values(), self.reference.values()) - check_iterandlist(d.iteritems(), d.items(), self.reference.items()) + check_iterandlist(iter(d.keys()), list(d.keys()), list(self.reference.keys())) + check_iterandlist(iter(d), list(d.keys()), list(self.reference.keys())) + check_iterandlist(iter(d.values()), list(d.values()), list(self.reference.values())) + check_iterandlist(iter(d.items()), list(d.items()), list(self.reference.items())) #get - key, value = d.iteritems().next() - knownkey, knownvalue = self.other.iteritems().next() + key, value = next(iter(d.items())) + knownkey, knownvalue = next(iter(self.other.items())) self.assertEqual(d.get(key, knownvalue), value) self.assertEqual(d.get(knownkey, knownvalue), knownvalue) self.assertNotIn(knownkey, d) @@ -96,24 +96,24 @@ def test_write(self): # Test for write operations on mapping p = self._empty_mapping() #Indexing - for key, value in self.reference.items(): + for key, value in list(self.reference.items()): p[key] = value self.assertEqual(p[key], value) - for key in self.reference.keys(): + for key in list(self.reference.keys()): del p[key] self.assertRaises(KeyError, lambda:p[key]) p = self._empty_mapping() #update p.update(self.reference) self.assertEqual(dict(p), self.reference) - items = p.items() + items = list(p.items()) p = self._empty_mapping() p.update(items) self.assertEqual(dict(p), self.reference) d = self._full_mapping(self.reference) #setdefault - key, value = d.iteritems().next() - knownkey, knownvalue = self.other.iteritems().next() + key, value = next(iter(d.items())) + knownkey, knownvalue = next(iter(self.other.items())) self.assertEqual(d.setdefault(key, knownvalue), value) self.assertEqual(d[key], value) self.assertEqual(d.setdefault(knownkey, knownvalue), knownvalue) @@ -145,21 +145,21 @@ def test_bool(self): def test_keys(self): d = self._empty_mapping() - self.assertEqual(d.keys(), []) + self.assertEqual(list(d.keys()), []) d = self.reference - self.assertIn(self.inmapping.keys()[0], d.keys()) - self.assertNotIn(self.other.keys()[0], d.keys()) + self.assertIn(list(self.inmapping.keys())[0], list(d.keys())) + self.assertNotIn(list(self.other.keys())[0], list(d.keys())) self.assertRaises(TypeError, d.keys, None) def test_values(self): d = self._empty_mapping() - self.assertEqual(d.values(), []) + self.assertEqual(list(d.values()), []) self.assertRaises(TypeError, d.values, None) def test_items(self): d = self._empty_mapping() - self.assertEqual(d.items(), []) + self.assertEqual(list(d.items()), []) self.assertRaises(TypeError, d.items, None) @@ -169,7 +169,7 @@ def test_len(self): def test_getitem(self): d = self.reference - self.assertEqual(d[self.inmapping.keys()[0]], self.inmapping.values()[0]) + self.assertEqual(d[list(self.inmapping.keys())[0]], list(self.inmapping.values())[0]) self.assertRaises(TypeError, d.__getitem__) @@ -178,7 +178,7 @@ def test_update(self): # mapping argument d = self._empty_mapping() d.update(self.other) - self.assertEqual(d.items(), self.other.items()) + self.assertEqual(list(d.items()), list(self.other.items())) # No argument d = self._empty_mapping() @@ -187,13 +187,13 @@ def test_update(self): # item sequence d = self._empty_mapping() - d.update(self.other.items()) - self.assertEqual(d.items(), self.other.items()) + d.update(list(self.other.items())) + self.assertEqual(list(d.items()), list(self.other.items())) # Iterator d = self._empty_mapping() - d.update(self.other.iteritems()) - self.assertEqual(d.items(), self.other.items()) + d.update(iter(self.other.items())) + self.assertEqual(list(d.items()), list(self.other.items())) # FIXME: Doesn't work with UserDict # self.assertRaises((TypeError, AttributeError), d.update, None) @@ -204,13 +204,13 @@ class SimpleUserDict(object): def __init__(self): self.d = outerself.reference def keys(self): - return self.d.keys() + return list(self.d.keys()) def __getitem__(self, i): return self.d[i] d.clear() d.update(SimpleUserDict()) - i1 = d.items() - i2 = self.reference.items() + i1 = list(d.items()) + i2 = list(self.reference.items()) def safe_sort_key(kv): k, v = kv @@ -236,7 +236,7 @@ def __init__(self): self.i = 1 def __iter__(self): return self - def next(self): + def __next__(self): if self.i: self.i = 0 return 'a' @@ -253,7 +253,7 @@ def __init__(self): self.i = ord('a') def __iter__(self): return self - def next(self): + def __next__(self): if self.i <= ord('z'): rtn = chr(self.i) self.i += 1 @@ -268,7 +268,7 @@ def __getitem__(self, key): class badseq(object): def __iter__(self): return self - def next(self): + def __next__(self): raise Exc() self.assertRaises(Exc, d.update, badseq()) @@ -279,13 +279,13 @@ def next(self): def test_get(self): d = self._empty_mapping() - self.assertTrue(d.get(self.other.keys()[0]) is None) - self.assertEqual(d.get(self.other.keys()[0], 3), 3) + self.assertTrue(d.get(list(self.other.keys())[0]) is None) + self.assertEqual(d.get(list(self.other.keys())[0], 3), 3) d = self.reference - self.assertTrue(d.get(self.other.keys()[0]) is None) - self.assertEqual(d.get(self.other.keys()[0], 3), 3) - self.assertEqual(d.get(self.inmapping.keys()[0]), self.inmapping.values()[0]) - self.assertEqual(d.get(self.inmapping.keys()[0], 3), self.inmapping.values()[0]) + self.assertTrue(d.get(list(self.other.keys())[0]) is None) + self.assertEqual(d.get(list(self.other.keys())[0], 3), 3) + self.assertEqual(d.get(list(self.inmapping.keys())[0]), list(self.inmapping.values())[0]) + self.assertEqual(d.get(list(self.inmapping.keys())[0], 3), list(self.inmapping.values())[0]) self.assertRaises(TypeError, d.get) self.assertRaises(TypeError, d.get, None, None, None) @@ -300,9 +300,9 @@ def test_popitem(self): def test_pop(self): d = self._empty_mapping() - k, v = self.inmapping.items()[0] + k, v = list(self.inmapping.items())[0] d[k] = v - self.assertRaises(KeyError, d.pop, self.other.keys()[0]) + self.assertRaises(KeyError, d.pop, list(self.other.keys())[0]) self.assertEqual(d.pop(k), v) self.assertEqual(len(d), 0) @@ -326,9 +326,9 @@ def test_bool(self): def test_keys(self): BasicTestMappingProtocol.test_keys(self) d = self._empty_mapping() - self.assertEqual(d.keys(), []) + self.assertEqual(list(d.keys()), []) d = self._full_mapping({'a': 1, 'b': 2}) - k = d.keys() + k = list(d.keys()) self.assertIn('a', k) self.assertIn('b', k) self.assertNotIn('c', k) @@ -336,19 +336,19 @@ def test_keys(self): def test_values(self): BasicTestMappingProtocol.test_values(self) d = self._full_mapping({1:2}) - self.assertEqual(d.values(), [2]) + self.assertEqual(list(d.values()), [2]) def test_items(self): BasicTestMappingProtocol.test_items(self) d = self._full_mapping({1:2}) - self.assertEqual(d.items(), [(1, 2)]) + self.assertEqual(list(d.items()), [(1, 2)]) def test_has_key(self): d = self._empty_mapping() - self.assertTrue(not d.has_key('a')) + self.assertTrue('a' not in d) d = self._full_mapping({'a': 1, 'b': 2}) - k = d.keys() + k = list(d.keys()) k.sort(key=lambda k: (id(type(k)), k)) self.assertEqual(k, ['a', 'b']) @@ -424,14 +424,14 @@ def test_update(self): # iterator d = self._full_mapping({1:3, 2:4}) - d.update(self._full_mapping({1:2, 3:4, 5:6}).iteritems()) + d.update(iter(self._full_mapping({1:2, 3:4, 5:6}).items())) self.assertEqual(d, {1:2, 2:4, 3:4, 5:6}) class SimpleUserDict(object): def __init__(self): self.d = {1:1, 2:2, 3:3} def keys(self): - return self.d.keys() + return list(self.d.keys()) def __getitem__(self, i): return self.d[i] d.clear() @@ -476,7 +476,7 @@ def __init__(self): class BadSeq(object): def __iter__(self): return self - def next(self): + def __next__(self): raise Exc() self.assertRaises(Exc, self.type2test.fromkeys, BadSeq()) @@ -551,7 +551,7 @@ def test_pop(self): # verify longs/ints get same value when key > 32 bits (for 64-bit archs) # see SF bug #689659 - x = 4503599627370496L + x = 4503599627370496 y = 4503599627370496 h = self._full_mapping({x: 'anything', y: 'something else'}) self.assertEqual(h[x], h[y]) @@ -650,7 +650,7 @@ def __repr__(self): def test_le(self): self.assertTrue(not (self._empty_mapping() < self._empty_mapping())) - self.assertTrue(not (self._full_mapping({1: 2}) < self._full_mapping({1L: 2L}))) + self.assertTrue(not (self._full_mapping({1: 2}) < self._full_mapping({1: 2}))) class Exc(Exception): pass diff --git a/grumpy-runtime-src/third_party/stdlib/test/seq_tests.py b/grumpy-runtime-src/third_party/stdlib/test/seq_tests.py index 6a65f4c3..7a5a46dd 100644 --- a/grumpy-runtime-src/third_party/stdlib/test/seq_tests.py +++ b/grumpy-runtime-src/third_party/stdlib/test/seq_tests.py @@ -27,7 +27,7 @@ def __init__(self, seqn): self.i = 0 def __iter__(self): return self - def next(self): + def __next__(self): if self.i >= len(self.seqn): raise StopIteration v = self.seqn[self.i] self.i += 1 @@ -47,7 +47,7 @@ class IterNextOnly(object): def __init__(self, seqn): self.seqn = seqn self.i = 0 - def next(self): + def __next__(self): if self.i >= len(self.seqn): raise StopIteration v = self.seqn[self.i] self.i += 1 @@ -68,7 +68,7 @@ def __init__(self, seqn): self.i = 0 def __iter__(self): return self - def next(self): + def __next__(self): 3 // 0 class IterFuncStop(object): @@ -77,7 +77,7 @@ def __init__(self, seqn): pass def __iter__(self): return self - def next(self): + def __next__(self): raise StopIteration # from itertools import chain, imap @@ -129,7 +129,7 @@ def __getitem__(self, i): 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", "", list(range(1000)), ('do', 1.2), range(2000,2200,5)): for g in (Sequence, IterFunc, IterGen, # itermulti, iterfunc): iterfunc): @@ -150,12 +150,12 @@ def test_truth(self): 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[long(i)], i) - for i in xrange(-len(u), -1): + self.assertEqual(u[int(i)], i) + for i in range(-len(u), -1): self.assertEqual(u[i], len(u)+i) - self.assertEqual(u[long(i)], len(u)+i) + self.assertEqual(u[int(i)], len(u)+i) self.assertRaises(IndexError, u.__getitem__, -len(u)-1) self.assertRaises(IndexError, u.__getitem__, len(u)) self.assertRaises(ValueError, u.__getitem__, slice(0,10,0)) @@ -204,12 +204,12 @@ def test_getslice(self): self.assertEqual(u[-100:100:], u) self.assertEqual(u[100:-100:-1], u[::-1]) self.assertEqual(u[-100:100:-1], self.type2test([])) - self.assertEqual(u[-100L:100L:2L], self.type2test([0, 2, 4])) + self.assertEqual(u[-100:100:2], self.type2test([0, 2, 4])) # Test extreme cases with long ints a = self.type2test([0,1,2,3,4]) - self.assertEqual(a[ -pow(2,128L): 3 ], self.type2test([0,1,2])) - self.assertEqual(a[ 3: pow(2,145L) ], self.type2test([3,4])) + self.assertEqual(a[ -pow(2,128): 3 ], self.type2test([0,1,2])) + self.assertEqual(a[ 3: pow(2,145) ], self.type2test([3,4])) self.assertRaises(TypeError, u.__getslice__) @@ -269,16 +269,16 @@ def test_addmul(self): self.assertEqual(self.type2test([-1]) + u1, self.type2test([-1, 0])) self.assertEqual(self.type2test(), u2*0) self.assertEqual(self.type2test(), 0*u2) - self.assertEqual(self.type2test(), u2*0L) - self.assertEqual(self.type2test(), 0L*u2) + self.assertEqual(self.type2test(), u2*0) + self.assertEqual(self.type2test(), 0*u2) + self.assertEqual(u2, u2*1) + self.assertEqual(u2, 1*u2) self.assertEqual(u2, u2*1) self.assertEqual(u2, 1*u2) - self.assertEqual(u2, u2*1L) - self.assertEqual(u2, 1L*u2) self.assertEqual(u2+u2, u2*2) self.assertEqual(u2+u2, 2*u2) - self.assertEqual(u2+u2, u2*2L) - self.assertEqual(u2+u2, 2L*u2) + self.assertEqual(u2+u2, u2*2) + self.assertEqual(u2+u2, 2*u2) self.assertEqual(u2+u2+u2, u2*3) self.assertEqual(u2+u2+u2, 3*u2) @@ -311,20 +311,20 @@ def test_getitemoverwriteiter(self): class T(self.type2test): def __getitem__(self, key): return str(key) + '!!!' - self.assertEqual(iter(T((1,2))).next(), 1) + self.assertEqual(next(iter(T((1,2)))), 1) @unittest.skip('grumpy') 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)) def test_bigrepeat(self): import sys - if sys.maxint <= 2147483647: + if sys.maxsize <= 2147483647: x = self.type2test([0]) # x *= 2**16 # self.assertRaises(MemoryError, x.__mul__, 2**16) @@ -337,10 +337,10 @@ def test_bigrepeat(self): def test_subscript(self): a = self.type2test([10, 11]) - self.assertEqual(a.__getitem__(0L), 10) - self.assertEqual(a.__getitem__(1L), 11) - self.assertEqual(a.__getitem__(-2L), 10) - self.assertEqual(a.__getitem__(-1L), 11) + self.assertEqual(a.__getitem__(0), 10) + self.assertEqual(a.__getitem__(1), 11) + self.assertEqual(a.__getitem__(-2), 10) + self.assertEqual(a.__getitem__(-1), 11) self.assertRaises(IndexError, a.__getitem__, -3) self.assertRaises(IndexError, a.__getitem__, 3) self.assertEqual(a.__getitem__(slice(0,1)), self.type2test([10])) @@ -409,8 +409,8 @@ def __eq__(self, other): self.assertEqual(a.index(0, -3), 3) self.assertEqual(a.index(0, 3, 4), 3) self.assertEqual(a.index(0, -3, -2), 3) - self.assertEqual(a.index(0, -4*sys.maxint, 4*sys.maxint), 2) - self.assertRaises(ValueError, a.index, 0, 4*sys.maxint,-4*sys.maxint) + self.assertEqual(a.index(0, -4*sys.maxsize, 4*sys.maxsize), 2) + self.assertRaises(ValueError, a.index, 0, 4*sys.maxsize,-4*sys.maxsize) self.assertRaises(ValueError, a.index, 2, 0, -10) @unittest.skip('grumpy') diff --git a/grumpy-runtime-src/third_party/stdlib/test/string_tests.py b/grumpy-runtime-src/third_party/stdlib/test/string_tests.py index d7941271..d3454424 100644 --- a/grumpy-runtime-src/third_party/stdlib/test/string_tests.py +++ b/grumpy-runtime-src/third_party/stdlib/test/string_tests.py @@ -7,7 +7,7 @@ import _struct as struct from test import test_support # from UserList import UserList -import UserList as _UserList +import collections as _UserList UserList = _UserList.UserList class Sequence(object): @@ -16,7 +16,7 @@ def __len__(self): return len(self.seq) def __getitem__(self, i): return self.seq[i] class BadSeq1(Sequence): - def __init__(self): self.seq = [7, 'hello', 123L] + def __init__(self): self.seq = [7, 'hello', 123] class BadSeq2(Sequence): def __init__(self): self.seq = ['a', 'b', 'c'] @@ -44,7 +44,7 @@ def fixtype(self, obj): elif isinstance(obj, dict): return dict([ (self.fixtype(key), self.fixtype(value)) - for (key, value) in obj.iteritems() + for (key, value) in obj.items() ]) else: return obj @@ -802,7 +802,7 @@ def test_strip_whitespace(self): # self.checkraises(TypeError, 'hello', 'replace', 42, 'h') # self.checkraises(TypeError, 'hello', 'replace', 'h', 42) - @unittest.skipIf(sys.maxint > (1 << 32) or struct.calcsize('P') != 4, + @unittest.skipIf(sys.maxsize > (1 << 32) or struct.calcsize('P') != 4, 'only applies to 32-bit platforms') def test_replace_overflow(self): # Check for overflow checking on 32 bit machines @@ -1039,13 +1039,13 @@ def test___contains__(self): self.checkequal(False, '', '__contains__', 'asdf') def test_subscript(self): - self.checkequal(u'a', 'abc', '__getitem__', 0) - self.checkequal(u'c', 'abc', '__getitem__', -1) - self.checkequal(u'a', 'abc', '__getitem__', 0L) - self.checkequal(u'abc', 'abc', '__getitem__', slice(0, 3)) - self.checkequal(u'abc', 'abc', '__getitem__', slice(0, 1000)) - self.checkequal(u'a', 'abc', '__getitem__', slice(0, 1)) - self.checkequal(u'', 'abc', '__getitem__', slice(0, 0)) + self.checkequal('a', 'abc', '__getitem__', 0) + self.checkequal('c', 'abc', '__getitem__', -1) + self.checkequal('a', 'abc', '__getitem__', 0) + self.checkequal('abc', 'abc', '__getitem__', slice(0, 3)) + self.checkequal('abc', 'abc', '__getitem__', slice(0, 1000)) + self.checkequal('a', 'abc', '__getitem__', slice(0, 1)) + self.checkequal('', 'abc', '__getitem__', slice(0, 0)) self.checkraises(TypeError, 'abc', '__getitem__', 'def') @@ -1071,7 +1071,7 @@ def test_extended_getslice(self): # Skip step 0 (invalid) for step in indices[1:]: L = list(s)[start:stop:step] - self.checkequal(u"".join(L), s, '__getitem__', + self.checkequal("".join(L), s, '__getitem__', slice(start, stop, step)) def test_mul(self): @@ -1098,11 +1098,11 @@ def test_join(self): self.checkequal('abc', 'a', 'join', ('abc',)) self.checkequal('z', 'a', 'join', UserList(['z'])) if test_support.have_unicode: - self.checkequal(unicode('a.b.c'), unicode('.'), 'join', ['a', 'b', 'c']) - self.checkequal(unicode('a.b.c'), '.', 'join', [unicode('a'), 'b', 'c']) - self.checkequal(unicode('a.b.c'), '.', 'join', ['a', unicode('b'), 'c']) - self.checkequal(unicode('a.b.c'), '.', 'join', ['a', 'b', unicode('c')]) - self.checkraises(TypeError, '.', 'join', ['a', unicode('b'), 3]) + self.checkequal(str('a.b.c'), str('.'), 'join', ['a', 'b', 'c']) + self.checkequal(str('a.b.c'), '.', 'join', [str('a'), 'b', 'c']) + self.checkequal(str('a.b.c'), '.', 'join', ['a', str('b'), 'c']) + self.checkequal(str('a.b.c'), '.', 'join', ['a', 'b', str('c')]) + self.checkraises(TypeError, '.', 'join', ['a', str('b'), 3]) for i in [5, 25, 125]: self.checkequal(((('a' * i) + '-') * i)[:-1], '-', 'join', ['a' * i] * i) @@ -1115,12 +1115,12 @@ def test_join(self): self.checkraises(TypeError, ' ', 'join') self.checkraises(TypeError, ' ', 'join', None) self.checkraises(TypeError, ' ', 'join', 7) - self.checkraises(TypeError, ' ', 'join', Sequence([7, 'hello', 123L])) + self.checkraises(TypeError, ' ', 'join', Sequence([7, 'hello', 123])) try: def f(): yield 4 + "" self.fixtype(' ').join(f()) - except TypeError, e: + except TypeError as e: if '+' not in str(e): self.fail('join() ate exception message') else: @@ -1140,11 +1140,11 @@ def test_formatting(self): # unicode raises ValueError, str raises OverflowError self.checkraises((ValueError, OverflowError), '%c', '__mod__', ordinal) - longvalue = sys.maxint + 10L + longvalue = sys.maxsize + 10 slongvalue = str(longvalue) if slongvalue[-1] in ("L","l"): slongvalue = slongvalue[:-1] self.checkequal(' 42', '%3ld', '__mod__', 42) - self.checkequal('42', '%d', '__mod__', 42L) + self.checkequal('42', '%d', '__mod__', 42) self.checkequal('42', '%d', '__mod__', 42.0) self.checkequal(slongvalue, '%d', '__mod__', longvalue) self.checkcall('%d', '__mod__', float(longvalue)) @@ -1197,10 +1197,10 @@ def __getitem__(self, k): 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.14159265359 / 3.0 * 10.0 self.checkcall(format, "__mod__", value) @@ -1239,7 +1239,7 @@ def test_partition(self): self.checkraises(TypeError, S, 'partition', None) # mixed use of str and unicode - self.assertEqual('a/b/c'.partition(u'/'), ('a', '/', 'b/c')) + self.assertEqual('a/b/c'.partition('/'), ('a', '/', 'b/c')) def test_rpartition(self): @@ -1257,7 +1257,7 @@ def test_rpartition(self): self.checkraises(TypeError, S, 'rpartition', None) # mixed use of str and unicode - self.assertEqual('a/b/c'.rpartition(u'/'), ('a/b', '/', 'c')) + self.assertEqual('a/b/c'.rpartition('/'), ('a/b', '/', 'c')) def test_none_arguments(self): # issue 11828 @@ -1301,19 +1301,19 @@ def test_find_etc_raise_correct_error_messages(self): # issue 11828 s = 'hello' x = 'x' - self.assertRaisesRegexp(TypeError, r'\bfind\b', s.find, + self.assertRaisesRegex(TypeError, r'\bfind\b', s.find, x, None, None, None) - self.assertRaisesRegexp(TypeError, r'\brfind\b', s.rfind, + self.assertRaisesRegex(TypeError, r'\brfind\b', s.rfind, x, None, None, None) - self.assertRaisesRegexp(TypeError, r'\bindex\b', s.index, + self.assertRaisesRegex(TypeError, r'\bindex\b', s.index, x, None, None, None) - self.assertRaisesRegexp(TypeError, r'\brindex\b', s.rindex, + self.assertRaisesRegex(TypeError, r'\brindex\b', s.rindex, x, None, None, None) - self.assertRaisesRegexp(TypeError, r'^count\(', s.count, + self.assertRaisesRegex(TypeError, r'^count\(', s.count, x, None, None, None) - self.assertRaisesRegexp(TypeError, r'^startswith\(', s.startswith, + self.assertRaisesRegex(TypeError, r'^startswith\(', s.startswith, x, None, None, None) - self.assertRaisesRegexp(TypeError, r'^endswith\(', s.endswith, + self.assertRaisesRegex(TypeError, r'^endswith\(', s.endswith, x, None, None, None) class MixinStrStringUserStringTest(object): @@ -1322,7 +1322,7 @@ class MixinStrStringUserStringTest(object): 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') @@ -1394,7 +1394,7 @@ class subclass(t): self.assertTrue(s1 is s2) # Should also test mixed-type join. - if t is unicode: + if t is str: s1 = subclass("abcd") s2 = "".join([s1]) self.assertTrue(s1 is not s2) @@ -1406,14 +1406,14 @@ class subclass(t): elif t is str: s1 = subclass("abcd") - s2 = u"".join([s1]) + s2 = "".join([s1]) self.assertTrue(s1 is not s2) - self.assertTrue(type(s2) is unicode) # promotes! + self.assertTrue(type(s2) is str) # promotes! s1 = t("abcd") - s2 = u"".join([s1]) + s2 = "".join([s1]) self.assertTrue(s1 is not s2) - self.assertTrue(type(s2) is unicode) # promotes! + self.assertTrue(type(s2) is str) # promotes! else: self.fail("unexpected type for MixinStrUnicodeTest %r" % t) diff --git a/grumpy-runtime-src/third_party/stdlib/test/test_argparse.py b/grumpy-runtime-src/third_party/stdlib/test/test_argparse.py index 3b8ff273..e2fad506 100644 --- a/grumpy-runtime-src/third_party/stdlib/test/test_argparse.py +++ b/grumpy-runtime-src/third_party/stdlib/test/test_argparse.py @@ -12,7 +12,7 @@ import argparse # from StringIO import StringIO -import StringIO as _StringIO +import io as _StringIO StringIO = _StringIO.StringIO class StdIOBuffer(StringIO): @@ -25,8 +25,8 @@ class TestCase(unittest.TestCase): def assertEqual(self, obj1, obj2): if obj1 != obj2: print('') - print(repr(obj1)) - print(repr(obj2)) + print((repr(obj1))) + print((repr(obj2))) print(obj1) print(obj2) super(TestCase, self).assertEqual(obj1, obj2) @@ -652,7 +652,7 @@ class TestOptionalsChoices(ParserTestCase): argument_signatures = [ Sig('-f', choices='abc'), - Sig('-g', type=int, choices=range(5))] + Sig('-g', type=int, choices=list(range(5)))] failures = ['a', '-f d', '-fad', '-ga', '-g 6'] successes = [ ('', NS(f=None, g=None)), @@ -1155,7 +1155,7 @@ class TestPositionalsChoicesString(ParserTestCase): class TestPositionalsChoicesInt(ParserTestCase): """Test a set of integer choices""" - argument_signatures = [Sig('spam', type=int, choices=range(20))] + argument_signatures = [Sig('spam', type=int, choices=list(range(20)))] failures = ['', '--foo', 'h', '42', 'ef'] successes = [ ('4', NS(spam=4)), @@ -1987,8 +1987,8 @@ def _test_subparser_help(self, args_str, expected_help): except ArgumentParserError: err = sys.exc_info()[1] if err.stdout != expected_help: - print(repr(expected_help)) - print(repr(err.stdout)) + print((repr(expected_help))) + print((repr(err.stdout))) self.assertEqual(err.stdout, expected_help) def test_subparser1_help(self): @@ -2890,11 +2890,11 @@ def _test(self, tester, parser_text): expected_text = getattr(tester, self.func_suffix) expected_text = textwrap.dedent(expected_text) if expected_text != parser_text: - print(repr(expected_text)) - print(repr(parser_text)) + print((repr(expected_text))) + print((repr(parser_text))) for char1, char2 in zip(expected_text, parser_text): if char1 != char2: - print('first diff: %r %r' % (char1, char2)) + print(('first diff: %r %r' % (char1, char2))) break tester.assertEqual(expected_text, parser_text) diff --git a/grumpy-runtime-src/third_party/stdlib/test/test_bisect.py b/grumpy-runtime-src/third_party/stdlib/test/test_bisect.py index ffc1fa79..50edaf8f 100644 --- a/grumpy-runtime-src/third_party/stdlib/test/test_bisect.py +++ b/grumpy-runtime-src/third_party/stdlib/test/test_bisect.py @@ -2,7 +2,7 @@ import unittest from test import test_support #from UserList import UserList -import UserList as _UserList +import collections as _UserList UserList = _UserList.UserList # We do a bit of trickery here to be able to test both the C implementation @@ -152,7 +152,7 @@ def test_large_range(self): mod = self.module n = sys.maxsize try: - data = xrange(n-1) + data = range(n-1) except OverflowError: self.skipTest("can't create a xrange() object of size `sys.maxsize`") self.assertEqual(mod.bisect_left(data, n-3), n-3) @@ -181,8 +181,8 @@ def test_random(self, n=25): import random as _random randrange = _random.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 = self.module.bisect_left(data, elem) @@ -198,9 +198,9 @@ def test_random(self, n=25): 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.assertTrue(lo <= ip <= hi) @@ -245,7 +245,7 @@ def test_vsBuiltinSort(self, n=500): choice = _random.choice for insorted in (list(), UserList()): - for i in xrange(n): + for i in range(n): digit = choice("0123456789") if digit in "02468": f = self.module.insort_left @@ -376,11 +376,11 @@ 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() - print counts + print(counts) if __name__ == "__main__": test_main(verbose=True) diff --git a/grumpy-runtime-src/third_party/stdlib/test/test_datetime.py b/grumpy-runtime-src/third_party/stdlib/test/test_datetime.py index b7bf2afd..02cc9781 100644 --- a/grumpy-runtime-src/third_party/stdlib/test/test_datetime.py +++ b/grumpy-runtime-src/third_party/stdlib/test/test_datetime.py @@ -28,7 +28,7 @@ # An arbitrary collection of objects of non-datetime types, for testing # mixed-type comparisons. -OTHERSTUFF = (10, 10L, 34.5, "abc", {}, [], ()) +OTHERSTUFF = (10, 10, 34.5, "abc", {}, [], ()) ############################################################################# @@ -145,8 +145,8 @@ def test_harmless_mixed_comparison(self): self.assertFalse(() == me) self.assertTrue(() != me) - self.assertIn(me, [1, 20L, [], me]) - self.assertIn([], [me, 1, 20L, []]) + self.assertIn(me, [1, 20, [], me]) + self.assertIn([], [me, 1, 20, []]) def test_harmful_mixed_comparison(self): me = self.theclass(1, 1, 1) @@ -215,13 +215,13 @@ def test_computations(self): eq(td(0, 0, 60*1000000), b) eq(a*10, td(70)) eq(a*10, 10*a) - eq(a*10L, 10*a) + eq(a*10, 10*a) eq(b*10, td(0, 600)) eq(10*b, td(0, 600)) - eq(b*10L, td(0, 600)) + eq(b*10, td(0, 600)) eq(c*10, td(0, 0, 10000)) eq(10*c, td(0, 0, 10000)) - eq(c*10L, td(0, 0, 10000)) + eq(c*10, td(0, 0, 10000)) eq(a*-1, -a) eq(b*-2, -b-b) eq(c*-2, -c+-c) @@ -246,7 +246,7 @@ def test_disallowed_computations(self): a = timedelta(42) # Add/sub ints, longs, floats should be illegal - for i in 1, 1L, 1.0: + for i in 1, 1, 1.0: self.assertRaises(TypeError, lambda: a+i) self.assertRaises(TypeError, lambda: a-i) self.assertRaises(TypeError, lambda: i+a) @@ -263,7 +263,7 @@ def test_disallowed_computations(self): # Division of int by timedelta doesn't make sense. # Division by zero doesn't make sense. - for zero in 0, 0L: + for zero in 0, 0: self.assertRaises(TypeError, lambda: zero // a) self.assertRaises(ZeroDivisionError, lambda: a // zero) @@ -586,7 +586,7 @@ def test_ordinal_conversions(self): # 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() @@ -603,7 +603,7 @@ def test_ordinal_conversions(self): dim = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] for year, isleap in (2000, True), (2002, False): n = self.theclass(year, 1, 1).toordinal() - for month, maxday in zip(range(1, 13), dim): + for month, maxday in zip(list(range(1, 13)), dim): if month == 2 and isleap: maxday += 1 for day in range(1, maxday+1): @@ -690,7 +690,7 @@ def test_computations(self): b = self.theclass(1956, 1, 31) diff = a-b - self.assertEqual(diff.days, 46*365 + len(range(1956, 2002, 4))) + self.assertEqual(diff.days, 46*365 + len(list(range(1956, 2002, 4)))) self.assertEqual(diff.seconds, 0) self.assertEqual(diff.microseconds, 0) @@ -715,7 +715,7 @@ def test_computations(self): self.assertEqual(a - (a - day), day) # Add/sub ints, longs, floats should be illegal - for i in 1, 1L, 1.0: + for i in 1, 1, 1.0: self.assertRaises(TypeError, lambda: a+i) self.assertRaises(TypeError, lambda: a-i) self.assertRaises(TypeError, lambda: i+a) @@ -850,7 +850,7 @@ def test_iso_long_years(self): 320 348 376 325 353 381 """ - iso_long_years = map(int, ISO_LONG_YEARS_TABLE.split()) + iso_long_years = list(map(int, ISO_LONG_YEARS_TABLE.split())) iso_long_years.sort() L = [] for i in range(400): @@ -881,7 +881,7 @@ def test_strftime(self): self.assertRaises(TypeError, t.strftime, 42) # arg wrong type # test that unicode input is allowed (issue 2782) - self.assertEqual(t.strftime(u"%m"), "03") + self.assertEqual(t.strftime("%m"), "03") # A naive object replaces %z and %Z w/ empty strings. self.assertEqual(t.strftime("'%z' '%Z'"), "'' ''") @@ -1366,7 +1366,7 @@ def test_computations(self): a = self.theclass(2002, 1, 31) b = self.theclass(1956, 1, 31) diff = a-b - self.assertEqual(diff.days, 46*365 + len(range(1956, 2002, 4))) + self.assertEqual(diff.days, 46*365 + len(list(range(1956, 2002, 4)))) self.assertEqual(diff.seconds, 0) self.assertEqual(diff.microseconds, 0) a = self.theclass(2002, 3, 2, 17, 6) @@ -1412,7 +1412,7 @@ def test_computations(self): self.assertEqual(a - (week + day + hour + millisec), (((a - week) - day) - hour) - millisec) # Add/sub ints, longs, floats should be illegal - for i in 1, 1L, 1.0: + for i in 1, 1, 1.0: self.assertRaises(TypeError, lambda: a+i) self.assertRaises(TypeError, lambda: a-i) self.assertRaises(TypeError, lambda: i+a) diff --git a/grumpy-runtime-src/third_party/stdlib/test/test_dict.py b/grumpy-runtime-src/third_party/stdlib/test/test_dict.py index 9a4f3f9a..e20ecedf 100644 --- a/grumpy-runtime-src/third_party/stdlib/test/test_dict.py +++ b/grumpy-runtime-src/third_party/stdlib/test/test_dict.py @@ -32,39 +32,39 @@ def test_bool(self): @unittest.expectedFailure def test_keys(self): d = {} - self.assertEqual(d.keys(), []) + self.assertEqual(list(d.keys()), []) d = {'a': 1, 'b': 2} - k = d.keys() + k = list(d.keys()) # self.assertEqual(set(k), {'a', 'b'}) self.assertIn('a', k) self.assertIn('b', k) - self.assertTrue(d.has_key('a')) - self.assertTrue(d.has_key('b')) + self.assertTrue('a' in d) + self.assertTrue('b' in d) self.assertRaises(TypeError, d.keys, None) def test_values(self): d = {} - self.assertEqual(d.values(), []) + self.assertEqual(list(d.values()), []) d = {1:2} - self.assertEqual(d.values(), [2]) + self.assertEqual(list(d.values()), [2]) self.assertRaises(TypeError, d.values, None) def test_items(self): d = {} - self.assertEqual(d.items(), []) + self.assertEqual(list(d.items()), []) d = {1:2} - self.assertEqual(d.items(), [(1, 2)]) + self.assertEqual(list(d.items()), [(1, 2)]) self.assertRaises(TypeError, d.items, None) @unittest.expectedFailure def test_has_key(self): d = {} - self.assertFalse(d.has_key('a')) + self.assertFalse('a' in d) d = {'a': 1, 'b': 2} - k = d.keys() + k = list(d.keys()) k.sort() self.assertEqual(k, ['a', 'b']) @@ -150,7 +150,7 @@ class SimpleUserDict(object): def __init__(self): self.d = {1:1, 2:2, 3:3} def keys(self): - return self.d.keys() + return list(self.d.keys()) def __getitem__(self, i): return self.d[i] d.clear() @@ -172,7 +172,7 @@ def __init__(self): self.i = 1 def __iter__(self): return self - def next(self): + def __next__(self): if self.i: self.i = 0 return 'a' @@ -189,7 +189,7 @@ def __init__(self): self.i = ord('a') def __iter__(self): return self - def next(self): + def __next__(self): if self.i <= ord('z'): rtn = chr(self.i) self.i += 1 @@ -203,7 +203,7 @@ def __getitem__(self, key): class badseq(object): def __iter__(self): return self - def next(self): + def __next__(self): raise Exc() self.assertRaises(Exc, {}.update, badseq()) @@ -246,7 +246,7 @@ def __init__(self): class BadSeq(object): def __iter__(self): return self - def next(self): + def __next__(self): raise Exc() self.assertRaises(Exc, dict.fromkeys, BadSeq()) @@ -258,13 +258,13 @@ def __setitem__(self, key, value): self.assertRaises(Exc, baddict2.fromkeys, [1]) # test fast path for dictionary inputs - d = dict(zip(range(6), range(6))) - self.assertEqual(dict.fromkeys(d, 0), dict(zip(range(6), [0]*6))) + d = dict(list(zip(list(range(6)), list(range(6))))) + self.assertEqual(dict.fromkeys(d, 0), dict(list(zip(list(range(6)), [0]*6)))) class baddict3(dict): def __new__(cls): return d - d = {i : i for i in range(10)} + d = {i : i for i in list(range(10))} res = d.copy() res.update(a=None, b=None, c=None) # self.assertEqual(baddict3.fromkeys({"a", "b", "c"}), res) @@ -379,7 +379,7 @@ def test_pop(self): # verify longs/ints get same value when key > 32 bits # (for 64-bit archs). See SF bug #689659. - x = 4503599627370496L + x = 4503599627370496 y = 4503599627370496 h = {x: 'anything', y: 'something else'} self.assertEqual(h[x], h[y]) @@ -434,7 +434,7 @@ def __repr__(self): @unittest.expectedFailure def test_le(self): self.assertFalse({} < {}) - self.assertFalse({1: 2} < {1L: 2L}) + self.assertFalse({1: 2} < {1: 2}) class Exc(Exception): pass @@ -467,7 +467,7 @@ def __missing__(self, key): self.assertEqual(d[1], 2) self.assertEqual(d[3], 4) self.assertNotIn(2, d) - self.assertNotIn(2, d.keys()) + self.assertNotIn(2, list(d.keys())) self.assertEqual(d[2], 42) class E(dict): diff --git a/grumpy-runtime-src/third_party/stdlib/test/test_dummy_thread.py b/grumpy-runtime-src/third_party/stdlib/test/test_dummy_thread.py index 29a85315..fa0fb460 100644 --- a/grumpy-runtime-src/third_party/stdlib/test/test_dummy_thread.py +++ b/grumpy-runtime-src/third_party/stdlib/test/test_dummy_thread.py @@ -5,9 +5,9 @@ implementation as its sole argument. """ -import dummy_thread as _thread +import _dummy_thread as _thread import time -import Queue +import queue import random import unittest from test import test_support @@ -73,13 +73,13 @@ def delay_unlock(to_unlock, delay): start_time = int(time.time()) _thread.start_new_thread(delay_unlock,(self.lock, DELAY)) if test_support.verbose: - print - print "*** Waiting for thread to release the lock "\ - "(approx. %s sec.) ***" % DELAY + print() + print("*** Waiting for thread to release the lock "\ + "(approx. %s sec.) ***" % DELAY) self.lock.acquire() end_time = int(time.time()) if test_support.verbose: - print "done" + print("done") self.assertGreaterEqual(end_time - start_time, DELAY, "Blocking by unconditional acquiring failed.") @@ -125,7 +125,7 @@ def arg_tester(queue, arg1=False, arg2=False): """Use to test _thread.start_new_thread() passes args properly.""" queue.put((arg1, arg2)) - testing_queue = Queue.Queue(1) + testing_queue = queue.Queue(1) _thread.start_new_thread(arg_tester, (testing_queue, True, True)) result = testing_queue.get() self.assertTrue(result[0] and result[1], @@ -149,12 +149,12 @@ def queue_mark(queue, delay): queue.put(_thread.get_ident()) thread_count = 5 - testing_queue = Queue.Queue(thread_count) + testing_queue = queue.Queue(thread_count) if test_support.verbose: - print - print "*** Testing multiple thread creation "\ - "(will take approx. %s to %s sec.) ***" % (DELAY, thread_count) - for count in xrange(thread_count): + print() + print("*** Testing multiple thread creation "\ + "(will take approx. %s to %s sec.) ***" % (DELAY, thread_count)) + for count in range(thread_count): if DELAY: local_delay = round(random.random(), 1) else: @@ -163,7 +163,7 @@ def queue_mark(queue, delay): (testing_queue, local_delay)) time.sleep(DELAY) if test_support.verbose: - print 'done' + print('done') self.assertEqual(testing_queue.qsize(), thread_count, "Not all %s threads executed properly after %s sec." % (thread_count, DELAY)) @@ -174,8 +174,8 @@ def test_main(imported_module=None): _thread = imported_module DELAY = 2 if test_support.verbose: - print - print "*** Using %s as _thread module ***" % _thread + print() + print("*** Using %s as _thread module ***" % _thread) test_support.run_unittest(LockTests, MiscTests, ThreadTests) if __name__ == '__main__': diff --git a/grumpy-runtime-src/third_party/stdlib/test/test_genericpath.py b/grumpy-runtime-src/third_party/stdlib/test/test_genericpath.py index 03c283fe..62188fbe 100644 --- a/grumpy-runtime-src/third_party/stdlib/test/test_genericpath.py +++ b/grumpy-runtime-src/third_party/stdlib/test/test_genericpath.py @@ -229,11 +229,11 @@ def check(value, expected): check('$spam}bar', '%s}bar' % snonascii) check(unonascii, unonascii) - check(u'$spam bar', u'%s bar' % unonascii) - check(u'${spam}bar', u'%sbar' % unonascii) - check(u'${%s}bar' % unonascii, u'ham%sbar' % unonascii) - check(u'$bar%s bar' % unonascii, u'$bar%s bar' % unonascii) - check(u'$spam}bar', u'%s}bar' % unonascii) + check('$spam bar', '%s bar' % unonascii) + check('${spam}bar', '%sbar' % unonascii) + check('${%s}bar' % unonascii, 'ham%sbar' % unonascii) + check('$bar%s bar' % unonascii, '$bar%s bar' % unonascii) + check('$spam}bar', '%s}bar' % unonascii) def test_abspath(self): self.assertIn("foo", self.pathmodule.abspath("foo")) @@ -248,18 +248,18 @@ def test_realpath(self): @test_support.requires_unicode def test_normpath_issue5827(self): # Make sure normpath preserves unicode - for path in (u'', u'.', u'/', u'\\', u'///foo/.//bar//'): - self.assertIsInstance(self.pathmodule.normpath(path), unicode) + for path in ('', '.', '/', '\\', '///foo/.//bar//'): + self.assertIsInstance(self.pathmodule.normpath(path), str) @test_support.requires_unicode def test_abspath_issue3426(self): # Check that abspath returns unicode when the arg is unicode # with both ASCII and non-ASCII cwds. abspath = self.pathmodule.abspath - for path in (u'', u'fuu', u'f\xf9\xf9', u'/fuu', u'U:\\'): - self.assertIsInstance(abspath(path), unicode) + for path in ('', 'fuu', 'f\xf9\xf9', '/fuu', 'U:\\'): + self.assertIsInstance(abspath(path), str) - unicwd = u'\xe7w\xf0' + unicwd = '\xe7w\xf0' try: fsencoding = test_support.TESTFN_ENCODING or "ascii" unicwd.encode(fsencoding) @@ -268,8 +268,8 @@ def test_abspath_issue3426(self): pass else: with test_support.temp_cwd(unicwd): - for path in (u'', u'fuu', u'f\xf9\xf9', u'/fuu', u'U:\\'): - self.assertIsInstance(abspath(path), unicode) + for path in ('', 'fuu', 'f\xf9\xf9', '/fuu', 'U:\\'): + self.assertIsInstance(abspath(path), str) @unittest.skipIf(sys.platform == 'darwin', "Mac OS X denies the creation of a directory with an invalid utf8 name") diff --git a/grumpy-runtime-src/third_party/stdlib/test/test_list.py b/grumpy-runtime-src/third_party/stdlib/test/test_list.py index 611575f1..119659fe 100644 --- a/grumpy-runtime-src/third_party/stdlib/test/test_list.py +++ b/grumpy-runtime-src/third_party/stdlib/test/test_list.py @@ -31,7 +31,7 @@ def test_basic(self): # 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.maxsize // 2)) # This code used to segfault in Py2.4a3 x = [] diff --git a/grumpy-runtime-src/third_party/stdlib/test/test_mimetools.py b/grumpy-runtime-src/third_party/stdlib/test/test_mimetools.py index e3745ee5..3aced5a1 100644 --- a/grumpy-runtime-src/third_party/stdlib/test/test_mimetools.py +++ b/grumpy-runtime-src/third_party/stdlib/test/test_mimetools.py @@ -2,12 +2,12 @@ from test import test_support import string -import StringIO +import io #mimetools = test_support.import_module("mimetools", deprecated=True) import mimetools -msgtext1 = mimetools.Message(StringIO.StringIO( +msgtext1 = mimetools.Message(io.StringIO( """Content-Type: text/plain; charset=iso-8859-1; format=flowed Content-Transfer-Encoding: 8bit @@ -20,24 +20,24 @@ def test_decodeencode(self): start = string.ascii_letters + "=" + string.digits + "\n" for enc in ['7bit','8bit','base64','quoted-printable', 'uuencode', 'x-uuencode', 'uue', 'x-uue']: - i = StringIO.StringIO(start) - o = StringIO.StringIO() + i = io.StringIO(start) + o = io.StringIO() mimetools.encode(i, o, enc) - i = StringIO.StringIO(o.getvalue()) - o = StringIO.StringIO() + i = io.StringIO(o.getvalue()) + o = io.StringIO() mimetools.decode(i, o, enc) self.assertEqual(o.getvalue(), start) @unittest.expectedFailure def test_boundary(self): s = set([""]) - for i in xrange(100): + for i in range(100): nb = mimetools.choose_boundary() self.assertNotIn(nb, s) s.add(nb) def test_message(self): - msg = mimetools.Message(StringIO.StringIO(msgtext1)) + msg = mimetools.Message(io.StringIO(msgtext1)) self.assertEqual(msg.gettype(), "text/plain") self.assertEqual(msg.getmaintype(), "text") self.assertEqual(msg.getsubtype(), "plain") diff --git a/grumpy-runtime-src/third_party/stdlib/test/test_queue.py b/grumpy-runtime-src/third_party/stdlib/test/test_queue.py index 90292e2e..3050f05b 100644 --- a/grumpy-runtime-src/third_party/stdlib/test/test_queue.py +++ b/grumpy-runtime-src/third_party/stdlib/test/test_queue.py @@ -1,6 +1,6 @@ # Some simple queue module tests, plus some failure conditions # to ensure the Queue locks remain stable. -import Queue +import queue import time import unittest from test import test_support @@ -90,7 +90,7 @@ def setUp(self): def simple_queue_test(self, q): if not q.empty(): - raise RuntimeError, "Call this function with an empty queue" + raise RuntimeError("Call this function with an empty queue") # I guess we better check things actually queue correctly a little :) q.put(111) q.put(333) @@ -112,12 +112,12 @@ def simple_queue_test(self, q): try: q.put(full, block=0) self.fail("Didn't appear to block with a full queue") - except Queue.Full: + except queue.Full: pass try: q.put(full, timeout=0.01) self.fail("Didn't appear to time-out with a full queue") - except Queue.Full: + except queue.Full: pass # Test a blocking put self.do_blocking_test(q.put, (full,), q.get, ()) @@ -129,12 +129,12 @@ def simple_queue_test(self, q): try: q.get(block=0) self.fail("Didn't appear to block with an empty queue") - except Queue.Empty: + except queue.Empty: pass try: q.get(timeout=0.01) self.fail("Didn't appear to time-out with an empty queue") - except Queue.Empty: + except queue.Empty: pass # Test a blocking get self.do_blocking_test(q.get, (), q.put, ('empty',)) @@ -155,7 +155,7 @@ def queue_join_test(self, q): self.cum = 0 for i in (0,1): threading.Thread(target=self.worker, args=(q,)).start() - for i in xrange(100): + for i in range(100): q.put(i) q.join() self.assertEqual(self.cum, sum(range(100)), @@ -196,13 +196,13 @@ def test_simple_queue(self): class QueueTest(BaseQueueTest, unittest.TestCase): - type2test = Queue.Queue + type2test = queue.Queue class LifoQueueTest(BaseQueueTest, unittest.TestCase): - type2test = Queue.LifoQueue + type2test = queue.LifoQueue class PriorityQueueTest(BaseQueueTest, unittest.TestCase): - type2test = Queue.PriorityQueue + type2test = queue.PriorityQueue @@ -210,27 +210,27 @@ class PriorityQueueTest(BaseQueueTest, unittest.TestCase): class FailingQueueException(Exception): pass -class FailingQueue(Queue.Queue): +class FailingQueue(queue.Queue): def __init__(self, *args): self.fail_next_put = False self.fail_next_get = False - Queue.Queue.__init__(self, *args) + queue.Queue.__init__(self, *args) def _put(self, item): if self.fail_next_put: self.fail_next_put = False - raise FailingQueueException, "You Lose" - return Queue.Queue._put(self, item) + raise FailingQueueException("You Lose") + return queue.Queue._put(self, item) def _get(self): if self.fail_next_get: self.fail_next_get = False - raise FailingQueueException, "You Lose" - return Queue.Queue._get(self) + raise FailingQueueException("You Lose") + return queue.Queue._get(self) class FailingQueueTest(BlockingTestMixin, unittest.TestCase): def failing_queue_test(self, q): if not q.empty(): - raise RuntimeError, "Call this function with an empty queue" + raise RuntimeError("Call this function with an empty queue") for i in range(QUEUE_SIZE-1): q.put(i) # Test a failing non-blocking put. diff --git a/grumpy-runtime-src/third_party/stdlib/test/test_quopri.py b/grumpy-runtime-src/third_party/stdlib/test/test_quopri.py index c179a263..63ad5d44 100644 --- a/grumpy-runtime-src/third_party/stdlib/test/test_quopri.py +++ b/grumpy-runtime-src/third_party/stdlib/test/test_quopri.py @@ -1,7 +1,7 @@ from test import test_support import unittest -import sys, cStringIO #, subprocess +import sys, io #, subprocess import quopri @@ -145,16 +145,16 @@ def test_idempotent_string(self): @withpythonimplementation def test_encode(self): for p, e in self.STRINGS: - infp = cStringIO.StringIO(p) - outfp = cStringIO.StringIO() + infp = io.StringIO(p) + outfp = io.StringIO() quopri.encode(infp, outfp, quotetabs=False) self.assertTrue(outfp.getvalue() == e) @withpythonimplementation def test_decode(self): for p, e in self.STRINGS: - infp = cStringIO.StringIO(e) - outfp = cStringIO.StringIO() + infp = io.StringIO(e) + outfp = io.StringIO() quopri.decode(infp, outfp) self.assertTrue(outfp.getvalue() == p) diff --git a/grumpy-runtime-src/third_party/stdlib/test/test_rfc822.py b/grumpy-runtime-src/third_party/stdlib/test/test_rfc822.py index 0f89ce16..47d6e7b8 100644 --- a/grumpy-runtime-src/third_party/stdlib/test/test_rfc822.py +++ b/grumpy-runtime-src/third_party/stdlib/test/test_rfc822.py @@ -5,9 +5,9 @@ import rfc822 try: - from cStringIO import StringIO + from io import StringIO except ImportError: - from StringIO import StringIO + from io import StringIO class MessageTestCase(unittest.TestCase): @@ -26,7 +26,7 @@ def test_get(self): def test_setdefault(self): msg = self.create_message( 'To: "last, first" \n\ntest\n') - self.assertTrue(not msg.has_key("New-Header")) + self.assertTrue("New-Header" not in msg) self.assertTrue(msg.setdefault("New-Header", "New-Value") == "New-Value") self.assertTrue(msg.setdefault("New-Header", "Different-Value") == "New-Value") @@ -43,7 +43,7 @@ def check(self, msg, results): try: mn, ma = results[i][0], results[i][1] except IndexError: - print 'extra parsed address:', repr(n), repr(a) + print('extra parsed address:', repr(n), repr(a)) continue i = i + 1 self.assertEqual(mn, n, @@ -53,7 +53,7 @@ def check(self, msg, results): if mn == n and ma == a: pass else: - print 'not found:', repr(n), repr(a) + print('not found:', repr(n), repr(a)) out = m.getdate('date') if out: diff --git a/grumpy-runtime-src/third_party/stdlib/test/test_select.py b/grumpy-runtime-src/third_party/stdlib/test/test_select.py index 4b024fc7..fdbe1268 100644 --- a/grumpy-runtime-src/third_party/stdlib/test/test_select.py +++ b/grumpy-runtime-src/third_party/stdlib/test/test_select.py @@ -33,17 +33,17 @@ def test_select(self): p = os.popen(cmd, 'r') for tout in (0, 1, 2, 4, 8, 16) + (None,)*10: if test_support.verbose: - print 'timeout =', tout + print('timeout =', tout) rfd, wfd, xfd = select.select([p], [], [], tout) if (rfd, wfd, xfd) == ([], [], []): continue if (rfd, wfd, xfd) == ([p], [], []): line = p.readline() if test_support.verbose: - print repr(line) + print(repr(line)) if not line: if test_support.verbose: - print 'EOF' + print('EOF') break continue self.fail('Unexpected return values from select():', rfd, wfd, xfd) diff --git a/grumpy-runtime-src/third_party/stdlib/test/test_slice.py b/grumpy-runtime-src/third_party/stdlib/test/test_slice.py index 1bd3492b..805506ef 100644 --- a/grumpy-runtime-src/third_party/stdlib/test/test_slice.py +++ b/grumpy-runtime-src/third_party/stdlib/test/test_slice.py @@ -107,11 +107,11 @@ def test_indices(self): slice(100, -100, -1).indices(10), slice(None, None, -1).indices(10) ) - self.assertEqual(slice(-100L, 100L, 2L).indices(10), (0, 10, 2)) + 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.maxsize - 1], [0]) - self.assertRaises(OverflowError, slice(None).indices, 1L<<100) + self.assertRaises(OverflowError, slice(None).indices, 1<<100) @unittest.expectedFailure def test_setslice_without_getslice(self): diff --git a/grumpy-runtime-src/third_party/stdlib/test/test_stat.py b/grumpy-runtime-src/third_party/stdlib/test/test_stat.py index 51f078a1..dad3c85d 100644 --- a/grumpy-runtime-src/third_party/stdlib/test/test_stat.py +++ b/grumpy-runtime-src/third_party/stdlib/test/test_stat.py @@ -155,10 +155,10 @@ def test_devices(self): @unittest.skip('grumpy') def test_module_attributes(self): - for key, value in self.stat_struct.items(): + for key, value in list(self.stat_struct.items()): modvalue = getattr(stat, key) self.assertEqual(value, modvalue, key) - for key, value in self.permission_bits.items(): + for key, value in list(self.permission_bits.items()): modvalue = getattr(stat, key) self.assertEqual(value, modvalue, key) for key in self.file_flags: diff --git a/grumpy-runtime-src/third_party/stdlib/test/test_string.py b/grumpy-runtime-src/third_party/stdlib/test/test_string.py index 5bcda5fa..67fedd35 100644 --- a/grumpy-runtime-src/third_party/stdlib/test/test_string.py +++ b/grumpy-runtime-src/third_party/stdlib/test/test_string.py @@ -4,7 +4,7 @@ Template = string.Template from test import test_support, string_tests # from UserList import UserList -import UserList as _UserList +import collections as _UserList UserList = _UserList.UserList class StringTest( @@ -39,11 +39,11 @@ def test_join(self): self.checkequal('abc', ('abc',), 'join', 'a') self.checkequal('z', UserList(['z']), 'join', 'a') if test_support.have_unicode: - self.checkequal(unicode('a.b.c'), ['a', 'b', 'c'], 'join', unicode('.')) - self.checkequal(unicode('a.b.c'), [unicode('a'), 'b', 'c'], 'join', '.') - self.checkequal(unicode('a.b.c'), ['a', unicode('b'), 'c'], 'join', '.') - self.checkequal(unicode('a.b.c'), ['a', 'b', unicode('c')], 'join', '.') - self.checkraises(TypeError, ['a', unicode('b'), 3], 'join', '.') + self.checkequal(str('a.b.c'), ['a', 'b', 'c'], 'join', str('.')) + self.checkequal(str('a.b.c'), [str('a'), 'b', 'c'], 'join', '.') + self.checkequal(str('a.b.c'), ['a', str('b'), 'c'], 'join', '.') + self.checkequal(str('a.b.c'), ['a', 'b', str('c')], 'join', '.') + self.checkraises(TypeError, ['a', str('b'), 3], 'join', '.') for i in [5, 25, 125]: self.checkequal( ((('a' * i) + '-') * i)[:-1], @@ -58,7 +58,7 @@ def test_join(self): def f(): yield 4 + "" self.fixtype(' ').join(f()) - except TypeError, e: + except TypeError as e: if '+' not in str(e): self.fail('join() ate exception message') else: @@ -84,7 +84,7 @@ def test_atoi(self): self.assertRaises(ValueError, string.atoi, " x1 ") def test_atol(self): - self.assertEqual(string.atol(" 1 "), 1L) + self.assertEqual(string.atol(" 1 "), 1) self.assertRaises(ValueError, string.atol, " 1x ") self.assertRaises(ValueError, string.atol, " x1 ") @@ -182,7 +182,7 @@ class CheckAllUsedFormatter(string.Formatter): def check_unused_args(self, used_args, args, kwargs): # Track which arguments actually got used unused_args = set(kwargs.keys()) - unused_args.update(range(0, len(args))) + unused_args.update(list(range(0, len(args)))) for arg in used_args: unused_args.remove(arg) @@ -388,8 +388,8 @@ class MyTemplate(Template): def test_unicode_values(self): s = Template('$who likes $what') - d = dict(who=u't\xffm', what=u'f\xfe\fed') - self.assertEqual(s.substitute(d), u't\xffm likes f\xfe\x0ced') + d = dict(who='t\xffm', what='f\xfe\fed') + self.assertEqual(s.substitute(d), 't\xffm likes f\xfe\x0ced') def test_keyword_arguments(self): eq = self.assertEqual diff --git a/grumpy-runtime-src/third_party/stdlib/test/test_support.py b/grumpy-runtime-src/third_party/stdlib/test/test_support.py index 906ace0c..b9780399 100644 --- a/grumpy-runtime-src/third_party/stdlib/test/test_support.py +++ b/grumpy-runtime-src/third_party/stdlib/test/test_support.py @@ -21,7 +21,7 @@ # import struct # import sysconfig try: - import thread + import _thread except ImportError: thread = None @@ -564,7 +564,7 @@ def unlink(filename): # is_jython = sys.platform.startswith('java') try: - unicode + str have_unicode = True except NameError: have_unicode = False @@ -985,7 +985,7 @@ def __delitem__(self, envvar): del self._environ[envvar] def keys(self): - return self._environ.keys() + return list(self._environ.keys()) def set(self, envvar, value): self[envvar] = value @@ -997,7 +997,7 @@ def __enter__(self): return self def __exit__(self, *ignore_exc): - for (k, v) in self._changed.items(): + for (k, v) in list(self._changed.items()): if v is None: if k in self._environ: del self._environ[k] @@ -1524,7 +1524,7 @@ def run_unittest(*classes): def threading_setup(): if thread: - return (thread._count(),) + return (_thread._count(),) else: return (1,) @@ -1534,7 +1534,7 @@ def threading_cleanup(nb_threads): _MAX_COUNT = 10 for count in range(_MAX_COUNT): - n = thread._count() + n = _thread._count() if n == nb_threads: break time.sleep(0.1) diff --git a/grumpy-runtime-src/third_party/stdlib/test/test_threading.py b/grumpy-runtime-src/third_party/stdlib/test/test_threading.py index d8f2a5fa..e82ed68a 100644 --- a/grumpy-runtime-src/third_party/stdlib/test/test_threading.py +++ b/grumpy-runtime-src/third_party/stdlib/test/test_threading.py @@ -8,7 +8,7 @@ import re import sys #thread = test.test_support.import_module('thread') -import thread +import _thread #threading = test.test_support.import_module('threading') import threading import time @@ -45,26 +45,26 @@ def __init__(self, name, testcase, sema, mutex, nrunning): def run(self): delay = random.random() / 10000.0 if verbose: - print 'task %s will run for %s usec' % ( - self.name, delay * 1e6) + print('task %s will run for %s usec' % ( + self.name, delay * 1e6)) with self.sema: with self.mutex: self.nrunning.inc() if verbose: - print self.nrunning.get(), 'tasks are running' + print(self.nrunning.get(), 'tasks are running') self.testcase.assertLessEqual(self.nrunning.get(), 3) time.sleep(delay) if verbose: - print 'task', self.name, 'done' + print('task', self.name, 'done') with self.mutex: self.nrunning.dec() self.testcase.assertGreaterEqual(self.nrunning.get(), 0) if verbose: - print '%s is finished. %d tasks are running' % ( - self.name, self.nrunning.get()) + print('%s is finished. %d tasks are running' % ( + self.name, self.nrunning.get())) class BaseTestCase(unittest.TestCase): def setUp(self): @@ -95,19 +95,19 @@ def test_various_ops(self): t = TestThread(""%i, self, sema, mutex, numrunning) threads.append(t) self.assertIsNone(t.ident) - self.assertRegexpMatches(repr(t), r'^$') + self.assertRegex(repr(t), r'^$') t.start() if verbose: - print 'waiting for all tasks to complete' + print('waiting for all tasks to complete') for t in threads: t.join(NUMTASKS) self.assertFalse(t.is_alive()) self.assertNotEqual(t.ident, 0) self.assertIsNotNone(t.ident) - self.assertRegexpMatches(repr(t), r'^$') + self.assertRegex(repr(t), r'^$') if verbose: - print 'all tasks done' + print('all tasks done') self.assertEqual(numrunning.get(), 0) def test_ident_of_no_threading_threads(self): @@ -118,7 +118,7 @@ def f(): done.set() done = threading.Event() ident = [] - thread.start_new_thread(f, ()) + _thread.start_new_thread(f, ()) done.wait() self.assertIsNotNone(ident[0]) # Kill the "immortal" _DummyThread @@ -127,10 +127,10 @@ def f(): # run with a small(ish) thread stack size (256kB) def test_various_ops_small_stack(self): if verbose: - print 'with 256kB thread stack size...' + print('with 256kB thread stack size...') try: threading.stack_size(262144) - except thread.error: + except _thread.error: self.skipTest('platform does not support changing thread stack size') self.test_various_ops() threading.stack_size(0) @@ -138,10 +138,10 @@ def test_various_ops_small_stack(self): # run with a large thread stack size (1MB) def test_various_ops_large_stack(self): if verbose: - print 'with 1MB thread stack size...' + print('with 1MB thread stack size...') try: threading.stack_size(0x100000) - except thread.error: + except _thread.error: self.skipTest('platform does not support changing thread stack size') self.test_various_ops() threading.stack_size(0) @@ -156,7 +156,7 @@ def f(mutex): mutex = threading.Lock() mutex.acquire() - tid = thread.start_new_thread(f, (mutex,)) + tid = _thread.start_new_thread(f, (mutex,)) # Wait for the thread to finish. mutex.acquire() self.assertIn(tid, threading._active) @@ -181,7 +181,7 @@ class AsyncExc(Exception): exception = ctypes.py_object(AsyncExc) # First check it works when setting the exception from the same thread. - tid = thread.get_ident() + tid = _thread.get_ident() try: result = set_async_exc(ctypes.c_long(tid), exception) @@ -210,7 +210,7 @@ class AsyncExc(Exception): class Worker(threading.Thread): def run(self): - self.id = thread.get_ident() + self.id = _thread.get_ident() self.finished = False try: @@ -225,32 +225,32 @@ def run(self): t.daemon = True # so if this fails, we don't hang Python at shutdown t.start() if verbose: - print " started worker thread" + print(" started worker thread") # Try a thread id that doesn't make sense. if verbose: - print " trying nonsensical thread id" + print(" trying nonsensical thread id") result = set_async_exc(ctypes.c_long(-1), exception) self.assertEqual(result, 0) # no thread states modified # Now raise an exception in the worker thread. if verbose: - print " waiting for worker thread to get started" + print(" waiting for worker thread to get started") ret = worker_started.wait() self.assertTrue(ret) if verbose: - print " verifying worker hasn't exited" + print(" verifying worker hasn't exited") self.assertFalse(t.finished) if verbose: - print " attempting to raise asynch exception in worker" + print(" attempting to raise asynch exception in worker") result = set_async_exc(ctypes.c_long(t.id), exception) self.assertEqual(result, 1) # one thread state modified if verbose: - print " waiting for worker to say it caught the exception" + print(" waiting for worker to say it caught the exception") worker_saw_exception.wait(timeout=10) self.assertTrue(t.finished) if verbose: - print " all OK -- joining worker" + print(" all OK -- joining worker") if t.finished: t.join() # else the thread is still running, and we have no way to kill it @@ -258,12 +258,12 @@ def run(self): def test_limbo_cleanup(self): # Issue 7481: Failure to start thread should cleanup the limbo map. def fail_new_thread(*args): - raise thread.error() + raise _thread.error() _start_new_thread = threading._start_new_thread threading._start_new_thread = fail_new_thread try: t = threading.Thread(target=lambda: None) - self.assertRaises(thread.error, t.start) + self.assertRaises(_thread.error, t.start) self.assertFalse( t in threading._limbo, "Failed to cleanup _limbo map on failure of Thread.start().") @@ -377,7 +377,7 @@ def test_enumerate_after_join(self): enum = threading.enumerate old_interval = sys.getcheckinterval() try: - for i in xrange(1, 100): + for i in range(1, 100): # Try a couple times at each thread-switching interval # to get more interleavings. sys.setcheckinterval(i // 5) @@ -786,8 +786,8 @@ class ThreadingExceptionTests(BaseTestCase): # multiple times. def test_start_thread_again(self): thread = threading.Thread() - thread.start() - self.assertRaises(RuntimeError, thread.start) + _thread.start() + self.assertRaises(RuntimeError, _thread.start) def test_joining_current_thread(self): current_thread = threading.current_thread() @@ -795,11 +795,11 @@ def test_joining_current_thread(self): def test_joining_inactive_thread(self): thread = threading.Thread() - self.assertRaises(RuntimeError, thread.join) + self.assertRaises(RuntimeError, _thread.join) def test_daemonize_active_thread(self): thread = threading.Thread() - thread.start() + _thread.start() self.assertRaises(RuntimeError, setattr, thread, "daemon", True) @unittest.skip('grumpy') diff --git a/grumpy-runtime-src/third_party/stdlib/test/test_tuple.py b/grumpy-runtime-src/third_party/stdlib/test/test_tuple.py index 3e5b6fbf..ddce174c 100644 --- a/grumpy-runtime-src/third_party/stdlib/test/test_tuple.py +++ b/grumpy-runtime-src/third_party/stdlib/test/test_tuple.py @@ -47,7 +47,7 @@ def test_tupleresizebug(self): 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 @@ -66,10 +66,10 @@ def test_hash(self): # 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 + zip(base) + [(i, j) for i in xp for j in base] + xp + list(zip(base)) collisions = len(inps) - len(set(map(hash, inps))) self.assertTrue(collisions <= 15) diff --git a/grumpy-runtime-src/third_party/stdlib/test/test_uu.py b/grumpy-runtime-src/third_party/stdlib/test/test_uu.py index db998815..1e4bcc95 100644 --- a/grumpy-runtime-src/third_party/stdlib/test/test_uu.py +++ b/grumpy-runtime-src/third_party/stdlib/test/test_uu.py @@ -6,7 +6,7 @@ import unittest from test import test_support -import sys, os, uu, cStringIO +import sys, os, uu, io import uu plaintext = "The smooth-scaled python crept over the sleeping dog\n" @@ -20,45 +20,45 @@ class UUTest(unittest.TestCase): def test_encode(self): - inp = cStringIO.StringIO(plaintext) - out = cStringIO.StringIO() + inp = io.StringIO(plaintext) + out = io.StringIO() uu.encode(inp, out, "t1") - self.assertEqual(out.getvalue(), encodedtextwrapped % (0666, "t1")) - inp = cStringIO.StringIO(plaintext) - out = cStringIO.StringIO() - uu.encode(inp, out, "t1", 0644) - self.assertEqual(out.getvalue(), encodedtextwrapped % (0644, "t1")) + self.assertEqual(out.getvalue(), encodedtextwrapped % (0o666, "t1")) + inp = io.StringIO(plaintext) + out = io.StringIO() + uu.encode(inp, out, "t1", 0o644) + self.assertEqual(out.getvalue(), encodedtextwrapped % (0o644, "t1")) def test_decode(self): - inp = cStringIO.StringIO(encodedtextwrapped % (0666, "t1")) - out = cStringIO.StringIO() + inp = io.StringIO(encodedtextwrapped % (0o666, "t1")) + out = io.StringIO() uu.decode(inp, out) self.assertEqual(out.getvalue(), plaintext) - inp = cStringIO.StringIO( + inp = io.StringIO( "UUencoded files may contain many lines,\n" + "even some that have 'begin' in them.\n" + - encodedtextwrapped % (0666, "t1") + encodedtextwrapped % (0o666, "t1") ) - out = cStringIO.StringIO() + out = io.StringIO() uu.decode(inp, out) self.assertEqual(out.getvalue(), plaintext) def test_truncatedinput(self): - inp = cStringIO.StringIO("begin 644 t1\n" + encodedtext) - out = cStringIO.StringIO() + inp = io.StringIO("begin 644 t1\n" + encodedtext) + out = io.StringIO() try: uu.decode(inp, out) self.fail("No exception raised") - except uu.Error, e: + except uu.Error as e: self.assertEqual(str(e), "Truncated input file") def test_missingbegin(self): - inp = cStringIO.StringIO("") - out = cStringIO.StringIO() + inp = io.StringIO("") + out = io.StringIO() try: uu.decode(inp, out) self.fail("No exception raised") - except uu.Error, e: + except uu.Error as e: self.assertEqual(str(e), "No valid begin line found in input file") def test_garbage_padding(self): @@ -72,8 +72,8 @@ def test_garbage_padding(self): ) plaintext = "\x33" # 00110011 - inp = cStringIO.StringIO(encodedtext) - out = cStringIO.StringIO() + inp = io.StringIO(encodedtext) + out = io.StringIO() uu.decode(inp, out, quiet=True) self.assertEqual(out.getvalue(), plaintext) @@ -92,17 +92,17 @@ def tearDown(self): sys.stdout = self.stdout def test_encode(self): - sys.stdin = cStringIO.StringIO(plaintext) - sys.stdout = cStringIO.StringIO() - uu.encode("-", "-", "t1", 0666) + sys.stdin = io.StringIO(plaintext) + sys.stdout = io.StringIO() + uu.encode("-", "-", "t1", 0o666) self.assertEqual( sys.stdout.getvalue(), - encodedtextwrapped % (0666, "t1") + encodedtextwrapped % (0o666, "t1") ) def test_decode(self): - sys.stdin = cStringIO.StringIO(encodedtextwrapped % (0666, "t1")) - sys.stdout = cStringIO.StringIO() + sys.stdin = io.StringIO(encodedtextwrapped % (0o666, "t1")) + sys.stdout = io.StringIO() uu.decode("-", "-") self.assertEqual(sys.stdout.getvalue(), plaintext) @@ -141,21 +141,21 @@ def test_encode(self): fin = open(self.tmpin, 'rb') fout = open(self.tmpout, 'w') - uu.encode(fin, fout, self.tmpin, mode=0644) + uu.encode(fin, fout, self.tmpin, mode=0o644) fin.close() fout.close() fout = open(self.tmpout, 'r') s = fout.read() fout.close() - self.assertEqual(s, encodedtextwrapped % (0644, self.tmpin)) + self.assertEqual(s, encodedtextwrapped % (0o644, self.tmpin)) # in_file and out_file as filenames - uu.encode(self.tmpin, self.tmpout, self.tmpin, mode=0644) + uu.encode(self.tmpin, self.tmpout, self.tmpin, mode=0o644) fout = open(self.tmpout, 'r') s = fout.read() fout.close() - self.assertEqual(s, encodedtextwrapped % (0644, self.tmpin)) + self.assertEqual(s, encodedtextwrapped % (0o644, self.tmpin)) finally: self._kill(fin) @@ -166,7 +166,7 @@ def test_decode(self): try: test_support.unlink(self.tmpin) f = open(self.tmpin, 'w') - f.write(encodedtextwrapped % (0644, self.tmpout)) + f.write(encodedtextwrapped % (0o644, self.tmpout)) f.close() f = open(self.tmpin, 'r') @@ -186,7 +186,7 @@ def test_decode_filename(self): try: test_support.unlink(self.tmpin) f = open(self.tmpin, 'w') - f.write(encodedtextwrapped % (0644, self.tmpout)) + f.write(encodedtextwrapped % (0o644, self.tmpout)) f.close() uu.decode(self.tmpin) @@ -202,7 +202,7 @@ def test_decodetwice(self): # Verify that decode() will refuse to overwrite an existing file f = None try: - f = cStringIO.StringIO(encodedtextwrapped % (0644, self.tmpout)) + f = io.StringIO(encodedtextwrapped % (0o644, self.tmpout)) f = open(self.tmpin, 'r') uu.decode(f) diff --git a/grumpy-runtime-src/third_party/stdlib/textwrap.py b/grumpy-runtime-src/third_party/stdlib/textwrap.py index 19f41041..62d6aa86 100644 --- a/grumpy-runtime-src/third_party/stdlib/textwrap.py +++ b/grumpy-runtime-src/third_party/stdlib/textwrap.py @@ -432,4 +432,4 @@ def dedent(text): if __name__ == "__main__": #print dedent("\tfoo\n\tbar") #print dedent(" \thello there\n \t how are you?") - print(dedent("Hello there.\n This is indented.")) + print((dedent("Hello there.\n This is indented."))) diff --git a/grumpy-runtime-src/third_party/stdlib/unittest_case.py b/grumpy-runtime-src/third_party/stdlib/unittest_case.py index 70f9c9cd..da1c8ae2 100644 --- a/grumpy-runtime-src/third_party/stdlib/unittest_case.py +++ b/grumpy-runtime-src/third_party/stdlib/unittest_case.py @@ -855,7 +855,7 @@ def assertDictContainsSubset(self, expected, actual, msg=None): """Checks whether actual is a superset of expected.""" missing = [] mismatched = [] - for key, value in expected.items(): + for key, value in list(expected.items()): if key not in actual: missing.append(key) elif value != actual[key]: diff --git a/grumpy-runtime-src/third_party/stdlib/uu.py b/grumpy-runtime-src/third_party/stdlib/uu.py index 8a5ae02e..36d0901c 100644 --- a/grumpy-runtime-src/third_party/stdlib/uu.py +++ b/grumpy-runtime-src/third_party/stdlib/uu.py @@ -180,7 +180,7 @@ def test(): if isinstance(output, str): output = open(output, 'w') else: - print(sys.argv[0], ': cannot do -t to stdout') + print((sys.argv[0], ': cannot do -t to stdout')) sys.exit(1) decode(input, output) else: @@ -188,7 +188,7 @@ def test(): if isinstance(input, str): input = open(input, 'r') else: - print(sys.argv[0], ': cannot do -t from stdin') + print((sys.argv[0], ': cannot do -t from stdin')) sys.exit(1) encode(input, output) From 51bd89463cc32a88b628b4f2b204fdde2e43cf42 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=87a=C4=9F=C4=B1l=20Ulu=C5=9Fahin?= Date: Tue, 18 Sep 2018 20:44:19 +0100 Subject: [PATCH 3/4] more refactoring on tools folder --- .../grumpy_tools/compiler/block.py | 6 +- .../grumpy_tools/compiler/block_test.py | 88 +++++++++---------- .../grumpy_tools/compiler/expr.py | 6 +- .../grumpy_tools/compiler/expr_visitor.py | 6 +- .../compiler/expr_visitor_test.py | 2 +- .../grumpy_tools/compiler/imputil.py | 4 +- .../grumpy_tools/compiler/imputil_test.py | 10 +-- .../grumpy_tools/compiler/shard_test.py | 2 +- .../grumpy_tools/compiler/stmt.py | 6 +- .../grumpy_tools/compiler/stmt_test.py | 22 ++--- .../grumpy_tools/compiler/util_test.py | 2 +- .../pep_support/pep3147pycache.py | 4 +- .../vendor/pythonparser/__init__.py | 2 +- .../vendor/pythonparser/algorithm.py | 4 +- .../grumpy_tools/vendor/pythonparser/ast.py | 5 +- .../vendor/pythonparser/diagnostic.py | 5 +- .../grumpy_tools/vendor/pythonparser/lexer.py | 16 ++-- .../vendor/pythonparser/parser.py | 48 +++++----- .../vendor/pythonparser/source.py | 2 +- .../tests/havingmainpkg/__main__.py | 2 +- 20 files changed, 118 insertions(+), 124 deletions(-) diff --git a/grumpy-tools-src/grumpy_tools/compiler/block.py b/grumpy-tools-src/grumpy_tools/compiler/block.py index 2287fab2..b2757aca 100644 --- a/grumpy-tools-src/grumpy_tools/compiler/block.py +++ b/grumpy-tools-src/grumpy_tools/compiler/block.py @@ -16,7 +16,7 @@ """Classes for analyzing and storing the state of Python code blocks.""" -from __future__ import unicode_literals + import abc import collections @@ -49,11 +49,9 @@ def __init__(self, breakvar): self.breakvar = breakvar -class Block(object): +class Block(object, metaclass=abc.ABCMeta): """Represents a Python block such as a function or class definition.""" - __metaclass__ = abc.ABCMeta - def __init__(self, parent, name): self.root = parent.root if parent else self self.parent = parent diff --git a/grumpy-tools-src/grumpy_tools/compiler/block_test.py b/grumpy-tools-src/grumpy_tools/compiler/block_test.py index 56e29d4b..a64b679b 100644 --- a/grumpy-tools-src/grumpy_tools/compiler/block_test.py +++ b/grumpy-tools-src/grumpy_tools/compiler/block_test.py @@ -16,7 +16,7 @@ """Tests Package, Block, BlockVisitor and related classes.""" -from __future__ import unicode_literals + import textwrap import unittest @@ -61,29 +61,29 @@ def testResolveName(self): module_block, 'keyword_func', block_vars, False) class1_block = block.ClassBlock(module_block, 'Class1', set()) class2_block = block.ClassBlock(func1_block, 'Class2', set()) - self.assertRegexpMatches(self._ResolveName(module_block, 'foo'), + self.assertRegex(self._ResolveName(module_block, 'foo'), r'ResolveGlobal\b.*foo') - self.assertRegexpMatches(self._ResolveName(module_block, 'bar'), + self.assertRegex(self._ResolveName(module_block, 'bar'), r'ResolveGlobal\b.*bar') - self.assertRegexpMatches(self._ResolveName(module_block, 'baz'), + self.assertRegex(self._ResolveName(module_block, 'baz'), r'ResolveGlobal\b.*baz') - self.assertRegexpMatches(self._ResolveName(func1_block, 'foo'), + self.assertRegex(self._ResolveName(func1_block, 'foo'), r'CheckLocal\b.*foo') - self.assertRegexpMatches(self._ResolveName(func1_block, 'bar'), + self.assertRegex(self._ResolveName(func1_block, 'bar'), r'ResolveGlobal\b.*bar') - self.assertRegexpMatches(self._ResolveName(func1_block, 'baz'), + self.assertRegex(self._ResolveName(func1_block, 'baz'), r'ResolveGlobal\b.*baz') - self.assertRegexpMatches(self._ResolveName(func2_block, 'foo'), + self.assertRegex(self._ResolveName(func2_block, 'foo'), r'CheckLocal\b.*foo') - self.assertRegexpMatches(self._ResolveName(func2_block, 'bar'), + self.assertRegex(self._ResolveName(func2_block, 'bar'), r'CheckLocal\b.*bar') - self.assertRegexpMatches(self._ResolveName(func2_block, 'baz'), + self.assertRegex(self._ResolveName(func2_block, 'baz'), r'ResolveGlobal\b.*baz') - self.assertRegexpMatches(self._ResolveName(class1_block, 'foo'), + self.assertRegex(self._ResolveName(class1_block, 'foo'), r'ResolveClass\(.*, nil, .*foo') - self.assertRegexpMatches(self._ResolveName(class2_block, 'foo'), + self.assertRegex(self._ResolveName(class2_block, 'foo'), r'ResolveClass\(.*, µfoo, .*foo') - self.assertRegexpMatches(self._ResolveName(keyword_block, 'case'), + self.assertRegex(self._ResolveName(keyword_block, 'case'), r'CheckLocal\b.*µcase, "case"') def _ResolveName(self, b, name): @@ -97,42 +97,42 @@ class BlockVisitorTest(unittest.TestCase): def testAssignSingle(self): visitor = block.BlockVisitor() visitor.visit(_ParseStmt('foo = 3')) - self.assertEqual(visitor.vars.keys(), ['foo']) - self.assertRegexpMatches(visitor.vars['foo'].init_expr, r'UnboundLocal') + self.assertEqual(list(visitor.vars.keys()), ['foo']) + self.assertRegex(visitor.vars['foo'].init_expr, r'UnboundLocal') def testAssignMultiple(self): visitor = block.BlockVisitor() visitor.visit(_ParseStmt('foo = bar = 123')) self.assertEqual(sorted(visitor.vars.keys()), ['bar', 'foo']) - self.assertRegexpMatches(visitor.vars['foo'].init_expr, r'UnboundLocal') - self.assertRegexpMatches(visitor.vars['bar'].init_expr, r'UnboundLocal') + self.assertRegex(visitor.vars['foo'].init_expr, r'UnboundLocal') + self.assertRegex(visitor.vars['bar'].init_expr, r'UnboundLocal') def testAssignTuple(self): visitor = block.BlockVisitor() visitor.visit(_ParseStmt('foo, bar = "a", "b"')) self.assertEqual(sorted(visitor.vars.keys()), ['bar', 'foo']) - self.assertRegexpMatches(visitor.vars['foo'].init_expr, r'UnboundLocal') - self.assertRegexpMatches(visitor.vars['bar'].init_expr, r'UnboundLocal') + self.assertRegex(visitor.vars['foo'].init_expr, r'UnboundLocal') + self.assertRegex(visitor.vars['bar'].init_expr, r'UnboundLocal') def testAssignNested(self): visitor = block.BlockVisitor() visitor.visit(_ParseStmt('foo, (bar, baz) = "a", ("b", "c")')) self.assertEqual(sorted(visitor.vars.keys()), ['bar', 'baz', 'foo']) - self.assertRegexpMatches(visitor.vars['foo'].init_expr, r'UnboundLocal') - self.assertRegexpMatches(visitor.vars['bar'].init_expr, r'UnboundLocal') - self.assertRegexpMatches(visitor.vars['baz'].init_expr, r'UnboundLocal') + self.assertRegex(visitor.vars['foo'].init_expr, r'UnboundLocal') + self.assertRegex(visitor.vars['bar'].init_expr, r'UnboundLocal') + self.assertRegex(visitor.vars['baz'].init_expr, r'UnboundLocal') def testAugAssignSingle(self): visitor = block.BlockVisitor() visitor.visit(_ParseStmt('foo += 3')) - self.assertEqual(visitor.vars.keys(), ['foo']) - self.assertRegexpMatches(visitor.vars['foo'].init_expr, r'UnboundLocal') + self.assertEqual(list(visitor.vars.keys()), ['foo']) + self.assertRegex(visitor.vars['foo'].init_expr, r'UnboundLocal') def testVisitClassDef(self): visitor = block.BlockVisitor() visitor.visit(_ParseStmt('class Foo(object): pass')) - self.assertEqual(visitor.vars.keys(), ['Foo']) - self.assertRegexpMatches(visitor.vars['Foo'].init_expr, r'UnboundLocal') + self.assertEqual(list(visitor.vars.keys()), ['Foo']) + self.assertRegex(visitor.vars['Foo'].init_expr, r'UnboundLocal') def testExceptHandler(self): visitor = block.BlockVisitor() @@ -144,34 +144,34 @@ def testExceptHandler(self): except TypeError as bar: pass"""))) self.assertEqual(sorted(visitor.vars.keys()), ['bar', 'foo']) - self.assertRegexpMatches(visitor.vars['foo'].init_expr, r'UnboundLocal') - self.assertRegexpMatches(visitor.vars['bar'].init_expr, r'UnboundLocal') + self.assertRegex(visitor.vars['foo'].init_expr, r'UnboundLocal') + self.assertRegex(visitor.vars['bar'].init_expr, r'UnboundLocal') def testFor(self): visitor = block.BlockVisitor() visitor.visit(_ParseStmt('for i in foo: pass')) - self.assertEqual(visitor.vars.keys(), ['i']) - self.assertRegexpMatches(visitor.vars['i'].init_expr, r'UnboundLocal') + self.assertEqual(list(visitor.vars.keys()), ['i']) + self.assertRegex(visitor.vars['i'].init_expr, r'UnboundLocal') def testFunctionDef(self): visitor = block.BlockVisitor() visitor.visit(_ParseStmt('def foo(): pass')) - self.assertEqual(visitor.vars.keys(), ['foo']) - self.assertRegexpMatches(visitor.vars['foo'].init_expr, r'UnboundLocal') + self.assertEqual(list(visitor.vars.keys()), ['foo']) + self.assertRegex(visitor.vars['foo'].init_expr, r'UnboundLocal') def testImport(self): visitor = block.BlockVisitor() visitor.visit(_ParseStmt('import foo.bar, baz')) self.assertEqual(sorted(visitor.vars.keys()), ['baz', 'foo']) - self.assertRegexpMatches(visitor.vars['foo'].init_expr, r'UnboundLocal') - self.assertRegexpMatches(visitor.vars['baz'].init_expr, r'UnboundLocal') + self.assertRegex(visitor.vars['foo'].init_expr, r'UnboundLocal') + self.assertRegex(visitor.vars['baz'].init_expr, r'UnboundLocal') def testImportFrom(self): visitor = block.BlockVisitor() visitor.visit(_ParseStmt('from foo.bar import baz, qux')) self.assertEqual(sorted(visitor.vars.keys()), ['baz', 'qux']) - self.assertRegexpMatches(visitor.vars['baz'].init_expr, r'UnboundLocal') - self.assertRegexpMatches(visitor.vars['qux'].init_expr, r'UnboundLocal') + self.assertRegex(visitor.vars['baz'].init_expr, r'UnboundLocal') + self.assertRegex(visitor.vars['qux'].init_expr, r'UnboundLocal') def testGlobal(self): visitor = block.BlockVisitor() @@ -183,13 +183,13 @@ def testGlobal(self): def testGlobalIsParam(self): visitor = block.BlockVisitor() visitor.vars['foo'] = block.Var('foo', block.Var.TYPE_PARAM, arg_index=0) - self.assertRaisesRegexp(util.ParseError, 'is parameter and global', + self.assertRaisesRegex(util.ParseError, 'is parameter and global', visitor.visit, _ParseStmt('global foo')) def testGlobalUsedPriorToDeclaration(self): node = pythonparser.parse('foo = 42\nglobal foo') visitor = block.BlockVisitor() - self.assertRaisesRegexp(util.ParseError, 'used prior to global declaration', + self.assertRaisesRegex(util.ParseError, 'used prior to global declaration', visitor.generic_visit, node) @@ -202,14 +202,14 @@ def testArgs(self): self.assertIn('baz', visitor.vars) self.assertIn('args', visitor.vars) self.assertIn('kwargs', visitor.vars) - self.assertRegexpMatches(visitor.vars['bar'].init_expr, r'Args\[0\]') - self.assertRegexpMatches(visitor.vars['baz'].init_expr, r'Args\[1\]') - self.assertRegexpMatches(visitor.vars['args'].init_expr, r'Args\[2\]') - self.assertRegexpMatches(visitor.vars['kwargs'].init_expr, r'Args\[3\]') + self.assertRegex(visitor.vars['bar'].init_expr, r'Args\[0\]') + self.assertRegex(visitor.vars['baz'].init_expr, r'Args\[1\]') + self.assertRegex(visitor.vars['args'].init_expr, r'Args\[2\]') + self.assertRegex(visitor.vars['kwargs'].init_expr, r'Args\[3\]') def testArgsDuplicate(self): func = _ParseStmt('def foo(bar, baz, bar=None): pass') - self.assertRaisesRegexp(util.ParseError, 'duplicate argument', + self.assertRaisesRegex(util.ParseError, 'duplicate argument', block.FunctionBlockVisitor, func) def testYield(self): @@ -222,7 +222,7 @@ def testYieldExpr(self): visitor.visit(_ParseStmt('foo = (yield)')) self.assertTrue(visitor.is_generator) self.assertEqual(sorted(visitor.vars.keys()), ['foo']) - self.assertRegexpMatches(visitor.vars['foo'].init_expr, r'UnboundLocal') + self.assertRegex(visitor.vars['foo'].init_expr, r'UnboundLocal') def _MakeModuleBlock(): diff --git a/grumpy-tools-src/grumpy_tools/compiler/expr.py b/grumpy-tools-src/grumpy_tools/compiler/expr.py index 1cc08d10..fb7af554 100644 --- a/grumpy-tools-src/grumpy_tools/compiler/expr.py +++ b/grumpy-tools-src/grumpy_tools/compiler/expr.py @@ -16,18 +16,16 @@ """Classes representing generated expressions.""" -from __future__ import unicode_literals + import abc from grumpy_tools.compiler import util -class GeneratedExpr(object): +class GeneratedExpr(object, metaclass=abc.ABCMeta): """GeneratedExpr is a generated Go expression in transcompiled output.""" - __metaclass__ = abc.ABCMeta - def __enter__(self): return self diff --git a/grumpy-tools-src/grumpy_tools/compiler/expr_visitor.py b/grumpy-tools-src/grumpy_tools/compiler/expr_visitor.py index 1432f6a3..6b28dcdd 100644 --- a/grumpy-tools-src/grumpy_tools/compiler/expr_visitor.py +++ b/grumpy-tools-src/grumpy_tools/compiler/expr_visitor.py @@ -16,7 +16,7 @@ """Visitor class for traversing Python expressions.""" -from __future__ import unicode_literals + import contextlib import textwrap @@ -289,7 +289,7 @@ def visit_Name(self, node): def visit_Num(self, node): if isinstance(node.n, int): expr_str = 'NewInt({})'.format(node.n) - elif isinstance(node.n, long): + elif isinstance(node.n, int): a = abs(node.n) gobytes = '' while a: @@ -331,7 +331,7 @@ def visit_Subscript(self, node): return result def visit_Str(self, node): - if isinstance(node.s, unicode): + if isinstance(node.s, str): expr_str = 'πg.NewUnicode({}).ToObject()'.format( util.go_str(node.s.encode('utf-8'))) else: diff --git a/grumpy-tools-src/grumpy_tools/compiler/expr_visitor_test.py b/grumpy-tools-src/grumpy_tools/compiler/expr_visitor_test.py index bed8278f..32bd505f 100644 --- a/grumpy-tools-src/grumpy_tools/compiler/expr_visitor_test.py +++ b/grumpy-tools-src/grumpy_tools/compiler/expr_visitor_test.py @@ -16,7 +16,7 @@ """Tests for ExprVisitor.""" -from __future__ import unicode_literals + import subprocess import textwrap diff --git a/grumpy-tools-src/grumpy_tools/compiler/imputil.py b/grumpy-tools-src/grumpy_tools/compiler/imputil.py index cebb5298..ac879f21 100644 --- a/grumpy-tools-src/grumpy_tools/compiler/imputil.py +++ b/grumpy-tools-src/grumpy_tools/compiler/imputil.py @@ -17,7 +17,7 @@ """Functionality for importing modules in Grumpy.""" -from __future__ import unicode_literals + import collections import functools @@ -225,7 +225,7 @@ def calc(modname, script): package_dir, filename = os.path.split(imp.script) if filename == '__init__.py': package_dir = os.path.dirname(package_dir) - for i in xrange(len(parts) - 1, 0, -1): + for i in range(len(parts) - 1, 0, -1): modname = '.'.join(parts[:i]) script = os.path.join(package_dir, '__init__.py') calc(modname, script) diff --git a/grumpy-tools-src/grumpy_tools/compiler/imputil_test.py b/grumpy-tools-src/grumpy_tools/compiler/imputil_test.py index c3cd6aa6..8482f86f 100644 --- a/grumpy-tools-src/grumpy_tools/compiler/imputil_test.py +++ b/grumpy-tools-src/grumpy_tools/compiler/imputil_test.py @@ -16,7 +16,7 @@ """Tests ImportVisitor and related classes.""" -from __future__ import unicode_literals + import copy import os @@ -260,7 +260,7 @@ def _assert_imports_equal(self, want, got): [imp.__dict__ for imp in got]) def _materialize_tree(self, dirname, spec): - for name, sub_spec in spec.iteritems(): + for name, sub_spec in spec.items(): if name.endswith('/'): subdir = os.path.join(dirname, name[:-1]) os.mkdir(subdir) @@ -303,7 +303,7 @@ def testImportFromFutureParseError(self): source, want_regexp = tc mod = pythonparser.parse(source) node = mod.body[0] - self.assertRaisesRegexp(util.ParseError, want_regexp, + self.assertRaisesRegex(util.ParseError, want_regexp, imputil._make_future_features, node) # pylint: disable=protected-access @@ -343,12 +343,12 @@ def testFutureFeatures(self): def testUnimplementedFutureRaises(self): mod = pythonparser.parse('from __future__ import division') msg = 'future feature division not yet implemented by grumpy' - self.assertRaisesRegexp(util.ParseError, msg, + self.assertRaisesRegex(util.ParseError, msg, imputil.parse_future_features, mod) def testUndefinedFutureRaises(self): mod = pythonparser.parse('from __future__ import foo') - self.assertRaisesRegexp( + self.assertRaisesRegex( util.ParseError, 'future feature foo is not defined', imputil.parse_future_features, mod) diff --git a/grumpy-tools-src/grumpy_tools/compiler/shard_test.py b/grumpy-tools-src/grumpy_tools/compiler/shard_test.py index 97d2943d..9b7debfe 100644 --- a/grumpy-tools-src/grumpy_tools/compiler/shard_test.py +++ b/grumpy-tools-src/grumpy_tools/compiler/shard_test.py @@ -14,7 +14,7 @@ """Wrapper for unit tests that loads a subset of all test methods.""" -from __future__ import unicode_literals + import argparse import random diff --git a/grumpy-tools-src/grumpy_tools/compiler/stmt.py b/grumpy-tools-src/grumpy_tools/compiler/stmt.py index c02f2664..815f3fd6 100644 --- a/grumpy-tools-src/grumpy_tools/compiler/stmt.py +++ b/grumpy-tools-src/grumpy_tools/compiler/stmt.py @@ -16,7 +16,7 @@ """Visitor class for traversing Python statements.""" -from __future__ import unicode_literals + import string import textwrap @@ -104,7 +104,7 @@ def visit_ClassDef(self, node): block_visitor = block.BlockVisitor() for child in node.body: block_visitor.visit(child) - global_vars = {v.name for v in block_visitor.vars.values() + global_vars = {v.name for v in list(block_visitor.vars.values()) if v.type == block.Var.TYPE_GLOBAL} # Visit all the statements inside body of the class definition. body_visitor = StatementVisitor(block.ClassBlock( @@ -537,7 +537,7 @@ def visit_function_inline(self, node): filename=util.go_str(self.block.root.filename), args=func_args.expr, flags=' | '.join(flags) if flags else 0) with self.writer.indent_block(): - for var in func_block.vars.values(): + for var in list(func_block.vars.values()): if var.type != block.Var.TYPE_GLOBAL: fmt = 'var {0} *πg.Object = {1}; _ = {0}' self.writer.write(fmt.format( diff --git a/grumpy-tools-src/grumpy_tools/compiler/stmt_test.py b/grumpy-tools-src/grumpy_tools/compiler/stmt_test.py index aa766823..4d017f0d 100644 --- a/grumpy-tools-src/grumpy_tools/compiler/stmt_test.py +++ b/grumpy-tools-src/grumpy_tools/compiler/stmt_test.py @@ -16,7 +16,7 @@ """Tests for StatementVisitor.""" -from __future__ import unicode_literals + import re import subprocess @@ -154,7 +154,7 @@ def foo(): foo()"""))) def testDeleteNonexistentLocal(self): - self.assertRaisesRegexp( + self.assertRaisesRegex( util.ParseError, 'cannot delete nonexistent local', _ParseAndVisit, 'def foo():\n del bar') @@ -208,12 +208,12 @@ def testForElse(self): print 'bar'"""))) def testForElseBreakNotNested(self): - self.assertRaisesRegexp( + self.assertRaisesRegex( util.ParseError, "'continue' not in loop", _ParseAndVisit, 'for i in (1,):\n pass\nelse:\n continue') def testForElseContinueNotNested(self): - self.assertRaisesRegexp( + self.assertRaisesRegex( util.ParseError, "'continue' not in loop", _ParseAndVisit, 'for i in (1,):\n pass\nelse:\n continue') @@ -251,7 +251,7 @@ def gen(): print list(gen())"""))) def testFunctionDefGeneratorReturnValue(self): - self.assertRaisesRegexp( + self.assertRaisesRegex( util.ParseError, 'returning a value in a generator function', _ParseAndVisit, 'def foo():\n yield 1\n return 2') @@ -299,7 +299,7 @@ def testImport(self): def testImportFutureLateRaises(self): regexp = 'from __future__ imports must occur at the beginning of the file' - self.assertRaisesRegexp(util.ImportError, regexp, _ParseAndVisit, + self.assertRaisesRegex(util.ImportError, regexp, _ParseAndVisit, 'foo = bar\nfrom __future__ import print_function') def testFutureUnicodeLiterals(self): @@ -335,9 +335,9 @@ def testImportNativeType(self): def testImportWildcardMemberRaises(self): regexp = 'wildcard member import is not implemented' - self.assertRaisesRegexp(util.ImportError, regexp, _ParseAndVisit, + self.assertRaisesRegex(util.ImportError, regexp, _ParseAndVisit, 'from foo import *') - self.assertRaisesRegexp(util.ImportError, regexp, _ParseAndVisit, + self.assertRaisesRegex(util.ImportError, regexp, _ParseAndVisit, 'from "__go__/foo" import *') def testPrintStatement(self): @@ -505,13 +505,13 @@ def testWriteExceptDispatcherBareExcept(self): 'exc', 'tb', handlers), [1, 2]) expected = re.compile(r'ResolveGlobal\(.*foo.*\bIsInstance\(.*' r'goto Label1.*goto Label2', re.DOTALL) - self.assertRegexpMatches(visitor.writer.getvalue(), expected) + self.assertRegex(visitor.writer.getvalue(), expected) def testWriteExceptDispatcherBareExceptionNotLast(self): visitor = stmt.StatementVisitor(_MakeModuleBlock()) handlers = [ast.ExceptHandler(type=None), ast.ExceptHandler(type=ast.Name(id='foo'))] - self.assertRaisesRegexp(util.ParseError, r"default 'except:' must be last", + self.assertRaisesRegex(util.ParseError, r"default 'except:' must be last", visitor._write_except_dispatcher, # pylint: disable=protected-access 'exc', 'tb', handlers) @@ -525,7 +525,7 @@ def testWriteExceptDispatcherMultipleExcept(self): r'ResolveGlobal\(.*foo.*\bif .*\bIsInstance\(.*\{.*goto Label1.*' r'ResolveGlobal\(.*bar.*\bif .*\bIsInstance\(.*\{.*goto Label2.*' r'\bRaise\(exc\.ToObject\(\), nil, tb\.ToObject\(\)\)', re.DOTALL) - self.assertRegexpMatches(visitor.writer.getvalue(), expected) + self.assertRegex(visitor.writer.getvalue(), expected) def _MakeModuleBlock(): diff --git a/grumpy-tools-src/grumpy_tools/compiler/util_test.py b/grumpy-tools-src/grumpy_tools/compiler/util_test.py index a94999da..a6d73703 100644 --- a/grumpy-tools-src/grumpy_tools/compiler/util_test.py +++ b/grumpy-tools-src/grumpy_tools/compiler/util_test.py @@ -16,7 +16,7 @@ """Tests Writer and other utils.""" -from __future__ import unicode_literals + import unittest diff --git a/grumpy-tools-src/grumpy_tools/pep_support/pep3147pycache.py b/grumpy-tools-src/grumpy_tools/pep_support/pep3147pycache.py index 349541ab..941b444a 100644 --- a/grumpy-tools-src/grumpy_tools/pep_support/pep3147pycache.py +++ b/grumpy-tools-src/grumpy_tools/pep_support/pep3147pycache.py @@ -1,5 +1,5 @@ # coding: utf-8 -from __future__ import unicode_literals + import os import sys @@ -174,7 +174,7 @@ def make_transpiled_module_folders(script_path, module_name): 'transpiled_base_folder': get_transpiled_base_folder(script_path, module_name), 'transpiled_module_folder': get_transpiled_module_folder(script_path, module_name), } - for role, folder in needed_folders.items(): + for role, folder in list(needed_folders.items()): if os.path.isfile(folder): # 1. Need a folder. Remove the file os.unlink(folder) if not os.path.exists(folder): # 2. Create the needed folder diff --git a/grumpy-tools-src/grumpy_tools/vendor/pythonparser/__init__.py b/grumpy-tools-src/grumpy_tools/vendor/pythonparser/__init__.py index a501b376..5ba8d2d2 100644 --- a/grumpy-tools-src/grumpy_tools/vendor/pythonparser/__init__.py +++ b/grumpy-tools-src/grumpy_tools/vendor/pythonparser/__init__.py @@ -1,4 +1,4 @@ -from __future__ import absolute_import, division, print_function, unicode_literals + import sys from . import source as pythonparser_source, lexer as pythonparser_lexer, parser as pythonparser_parser, diagnostic as pythonparser_diagnostic diff --git a/grumpy-tools-src/grumpy_tools/vendor/pythonparser/algorithm.py b/grumpy-tools-src/grumpy_tools/vendor/pythonparser/algorithm.py index d9bed74a..036a11e7 100644 --- a/grumpy-tools-src/grumpy_tools/vendor/pythonparser/algorithm.py +++ b/grumpy-tools-src/grumpy_tools/vendor/pythonparser/algorithm.py @@ -3,7 +3,7 @@ algorithms that operate on abstract syntax trees. """ -from __future__ import absolute_import, division, print_function, unicode_literals + from . import ast class Visitor: @@ -78,7 +78,7 @@ def _visit_one(self, node): def visit(self, obj): """Visit a node or a list of nodes. Other values are ignored""" if isinstance(obj, list): - return list(filter(lambda x: x is not None, map(self.visit, obj))) + return list([x for x in map(self.visit, obj) if x is not None]) elif isinstance(obj, ast.AST): return self._visit_one(obj) else: diff --git a/grumpy-tools-src/grumpy_tools/vendor/pythonparser/ast.py b/grumpy-tools-src/grumpy_tools/vendor/pythonparser/ast.py index 8b93ab0e..5ba0b9c0 100644 --- a/grumpy-tools-src/grumpy_tools/vendor/pythonparser/ast.py +++ b/grumpy-tools-src/grumpy_tools/vendor/pythonparser/ast.py @@ -23,7 +23,7 @@ :class:`arg` in ``vararg`` and ``kwarg`` slots. """ -from __future__ import absolute_import, division, print_function, unicode_literals + # Location mixins @@ -53,8 +53,7 @@ def value(name): return repr(loc) except: return "(!!!MISSING!!!)" - fields = ", ".join(map(lambda name: "%s=%s" % (name, value(name)), - self._reprfields())) + fields = ", ".join(["%s=%s" % (name, value(name)) for name in self._reprfields()]) return "%s(%s)" % (self.__class__.__name__, fields) @property diff --git a/grumpy-tools-src/grumpy_tools/vendor/pythonparser/diagnostic.py b/grumpy-tools-src/grumpy_tools/vendor/pythonparser/diagnostic.py index 45eb3b4e..6f6b2379 100644 --- a/grumpy-tools-src/grumpy_tools/vendor/pythonparser/diagnostic.py +++ b/grumpy-tools-src/grumpy_tools/vendor/pythonparser/diagnostic.py @@ -3,7 +3,7 @@ and presentation of diagnostic messages. """ -from __future__ import absolute_import, division, print_function, unicode_literals + from functools import reduce from contextlib import contextmanager import sys, re @@ -48,8 +48,7 @@ def __init__(self, level, reason, arguments, location, if notes is None: notes = [] - if len(set(map(lambda x: x.source_buffer, - [location] + highlights))) > 1: + if len(set([x.source_buffer for x in [location] + highlights])) > 1: raise ValueError("location and highlights must refer to the same source buffer") self.level, self.reason, self.arguments = \ diff --git a/grumpy-tools-src/grumpy_tools/vendor/pythonparser/lexer.py b/grumpy-tools-src/grumpy_tools/vendor/pythonparser/lexer.py index d578b885..ff55cfb3 100644 --- a/grumpy-tools-src/grumpy_tools/vendor/pythonparser/lexer.py +++ b/grumpy-tools-src/grumpy_tools/vendor/pythonparser/lexer.py @@ -2,14 +2,14 @@ The :mod:`lexer` module concerns itself with tokenizing Python source. """ -from __future__ import absolute_import, division, print_function, unicode_literals + from . import source, diagnostic import re import unicodedata import sys if sys.version_info[0] == 3: - unichr = chr + chr = chr byte = lambda x: bytes([x]) long = int else: @@ -329,7 +329,7 @@ def _refill(self, eof_token): if sys.version_info > (3,) or not match.group(13): int_type = int else: - int_type = long + int_type = int if match.group(5) is not None: # floating point or complex literal if match.group(6) is None: @@ -482,14 +482,14 @@ def _replace_escape_unicode(self, range, value): elif chr == "v": chunks.append("\v") elif match.group(2) is not None: # oct - chunks.append(unichr(int(match.group(2), 8))) + chunks.append(chr(int(match.group(2), 8))) elif match.group(3) is not None: # hex - chunks.append(unichr(int(match.group(3), 16))) + chunks.append(chr(int(match.group(3), 16))) elif match.group(4) is not None: # unicode-16 - chunks.append(unichr(int(match.group(4), 16))) + chunks.append(chr(int(match.group(4), 16))) elif match.group(5) is not None: # unicode-32 try: - chunks.append(unichr(int(match.group(5), 16))) + chunks.append(chr(int(match.group(5), 16))) except ValueError: error = diagnostic.Diagnostic( "error", "unicode character out of range", {}, @@ -609,4 +609,4 @@ def __iter__(self): return self def __next__(self): - return self.next() + return next(self) diff --git a/grumpy-tools-src/grumpy_tools/vendor/pythonparser/parser.py b/grumpy-tools-src/grumpy_tools/vendor/pythonparser/parser.py index 13995c5e..26c211b5 100644 --- a/grumpy-tools-src/grumpy_tools/vendor/pythonparser/parser.py +++ b/grumpy-tools-src/grumpy_tools/vendor/pythonparser/parser.py @@ -4,7 +4,7 @@ The :mod:`parser` module concerns itself with parsing Python source. """ -from __future__ import absolute_import, division, print_function, unicode_literals + from functools import reduce from . import source, diagnostic, lexer, ast @@ -189,7 +189,7 @@ def Alt(*inner_rules, **kwargs): value of that rule, or None if no rules were satisfied. """ loc = kwargs.get("loc", None) - expected = lambda parser: reduce(list.__add__, map(lambda x: x.expected(parser), inner_rules)) + expected = lambda parser: reduce(list.__add__, [x.expected(parser) for x in inner_rules]) if loc is not None: @llrule(loc, expected, cases=len(inner_rules)) def rule(parser): @@ -314,7 +314,7 @@ def Oper(klass, *kinds, **kwargs): an instance of ``klass`` with ``loc`` encompassing the entire sequence or None if the first token is not of ``kinds[0]``. """ - @action(Seq(*map(Loc, kinds)), loc=kwargs.get("loc", None)) + @action(Seq(*list(map(Loc, kinds))), loc=kwargs.get("loc", None)) def rule(parser, *tokens): return klass(loc=tokens[0].join(tokens[-1])) return rule @@ -577,8 +577,8 @@ def decorator(self, at_loc, idents, call_opt, newline_loc): @action(Seq(Rule("decorators"), Alt(Rule("classdef"), Rule("funcdef")))) def decorated(self, decorators, classfuncdef): """decorated: decorators (classdef | funcdef)""" - classfuncdef.at_locs = list(map(lambda x: x[0], decorators)) - classfuncdef.decorator_list = list(map(lambda x: x[1], decorators)) + classfuncdef.at_locs = list([x[0] for x in decorators]) + classfuncdef.decorator_list = list([x[1] for x in decorators]) classfuncdef.loc = classfuncdef.loc.join(decorators[0][0]) return classfuncdef @@ -844,8 +844,8 @@ def expr_stmt_2(self, augassign, rhs_expr): @action(Star(Seq(Loc("="), Alt(Rule("yield_expr"), Rule("expr_stmt_1"))))) def expr_stmt_3(self, seq): if len(seq) > 0: - return ast.Assign(targets=list(map(lambda x: x[1], seq[:-1])), value=seq[-1][1], - op_locs=list(map(lambda x: x[0], seq))) + return ast.Assign(targets=list([x[1] for x in seq[:-1]]), value=seq[-1][1], + op_locs=list([x[0] for x in seq])) else: return None @@ -1123,13 +1123,13 @@ def str_as_name(self, string, as_name_opt): def dotted_name(self, idents): """dotted_name: NAME ('.' NAME)*""" return idents[0].loc.join(idents[-1].loc), \ - ".".join(list(map(lambda x: x.value, idents))) + ".".join(list([x.value for x in idents])) @action(Seq(Loc("global"), List(Tok("ident"), ",", trailing=False))) def global_stmt(self, global_loc, names): """global_stmt: 'global' NAME (',' NAME)*""" - return ast.Global(names=list(map(lambda x: x.value, names)), - name_locs=list(map(lambda x: x.loc, names)), + return ast.Global(names=list([x.value for x in names]), + name_locs=list([x.loc for x in names]), keyword_loc=global_loc, loc=global_loc.join(names[-1].loc)) @action(Seq(Loc("exec"), Rule("expr"), @@ -1151,8 +1151,8 @@ def exec_stmt(self, exec_loc, body, in_opt): @action(Seq(Loc("nonlocal"), List(Tok("ident"), ",", trailing=False))) def nonlocal_stmt(self, nonlocal_loc, names): """(3.0-) nonlocal_stmt: 'nonlocal' NAME (',' NAME)*""" - return ast.Nonlocal(names=list(map(lambda x: x.value, names)), - name_locs=list(map(lambda x: x.loc, names)), + return ast.Nonlocal(names=list([x.value for x in names]), + name_locs=list([x.loc for x in names]), keyword_loc=nonlocal_loc, loc=nonlocal_loc.join(names[-1].loc)) @action(Seq(Loc("assert"), Rule("test"), Opt(SeqN(1, Tok(","), Rule("test"))))) @@ -1408,9 +1408,9 @@ def or_test(self, lhs, rhs): """or_test: and_test ('or' and_test)*""" if len(rhs) > 0: return ast.BoolOp(op=ast.Or(), - values=[lhs] + list(map(lambda x: x[1], rhs)), + values=[lhs] + list([x[1] for x in rhs]), loc=lhs.loc.join(rhs[-1][1].loc), - op_locs=list(map(lambda x: x[0], rhs))) + op_locs=list([x[0] for x in rhs])) else: return lhs @@ -1419,9 +1419,9 @@ def and_test(self, lhs, rhs): """and_test: not_test ('and' not_test)*""" if len(rhs) > 0: return ast.BoolOp(op=ast.And(), - values=[lhs] + list(map(lambda x: x[1], rhs)), + values=[lhs] + list([x[1] for x in rhs]), loc=lhs.loc.join(rhs[-1][1].loc), - op_locs=list(map(lambda x: x[0], rhs))) + op_locs=list([x[0] for x in rhs])) else: return lhs @@ -1445,8 +1445,8 @@ def comparison(self, lhs, rhs): (3.2-) comparison: expr (comp_op expr)* """ if len(rhs) > 0: - return ast.Compare(left=lhs, ops=list(map(lambda x: x[0], rhs)), - comparators=list(map(lambda x: x[1], rhs)), + return ast.Compare(left=lhs, ops=list([x[0] for x in rhs]), + comparators=list([x[1] for x in rhs]), loc=lhs.loc.join(rhs[-1][1].loc)) else: return lhs @@ -1747,9 +1747,9 @@ def testlist(self, exprs): @action(List(Seq(Rule("test"), Loc(":"), Rule("test")), ",", trailing=True)) def dictmaker(self, elts): """(2.6) dictmaker: test ':' test (',' test ':' test)* [',']""" - return ast.Dict(keys=list(map(lambda x: x[0], elts)), - values=list(map(lambda x: x[2], elts)), - colon_locs=list(map(lambda x: x[1], elts)), + return ast.Dict(keys=list([x[0] for x in elts]), + values=list([x[2] for x in elts]), + colon_locs=list([x[1] for x in elts]), loc=None) dictorsetmaker_1 = Seq(Rule("test"), Loc(":"), Rule("test")) @@ -1760,9 +1760,9 @@ def dictmaker(self, elts): def dictorsetmaker_2(self, first, elts): if isinstance(elts, commalist): elts.insert(0, first) - return ast.Dict(keys=list(map(lambda x: x[0], elts)), - values=list(map(lambda x: x[2], elts)), - colon_locs=list(map(lambda x: x[1], elts)), + return ast.Dict(keys=list([x[0] for x in elts]), + values=list([x[2] for x in elts]), + colon_locs=list([x[1] for x in elts]), loc=None) else: return ast.DictComp(key=first[0], value=first[2], generators=elts([]), diff --git a/grumpy-tools-src/grumpy_tools/vendor/pythonparser/source.py b/grumpy-tools-src/grumpy_tools/vendor/pythonparser/source.py index 5603e91c..67b3bb24 100644 --- a/grumpy-tools-src/grumpy_tools/vendor/pythonparser/source.py +++ b/grumpy-tools-src/grumpy_tools/vendor/pythonparser/source.py @@ -5,7 +5,7 @@ location information and original source from a range. """ -from __future__ import absolute_import, division, print_function, unicode_literals + import bisect import re diff --git a/grumpy-tools-src/tests/havingmainpkg/__main__.py b/grumpy-tools-src/tests/havingmainpkg/__main__.py index fae4cabc..6b7403b5 100644 --- a/grumpy-tools-src/tests/havingmainpkg/__main__.py +++ b/grumpy-tools-src/tests/havingmainpkg/__main__.py @@ -1,4 +1,4 @@ -from __future__ import print_function + def main(): From 9da8b88d0eda5ffe084f1dade926b4d624bcf327 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=87a=C4=9F=C4=B1l?= <1615150+cgl@users.noreply.github.com> Date: Tue, 9 Oct 2018 09:40:29 +0100 Subject: [PATCH 4/4] fix conflict with io library and io var --- grumpy-tools-src/grumpy_tools/compiler/util.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/grumpy-tools-src/grumpy_tools/compiler/util.py b/grumpy-tools-src/grumpy_tools/compiler/util.py index c8e0a860..77864ab5 100644 --- a/grumpy-tools-src/grumpy_tools/compiler/util.py +++ b/grumpy-tools-src/grumpy_tools/compiler/util.py @@ -139,17 +139,17 @@ def dedent(self, n=1): def go_str(value): """Returns value as a valid Go string literal.""" - io = io.StringIO() - io.write('"') + output = io.StringIO() + output.write('"') for c in value: if c in _ESCAPES: - io.write(_ESCAPES[c]) + output.write(_ESCAPES[c]) elif c in _SIMPLE_CHARS: - io.write(c) + output.write(c) else: - io.write(r'\x{:02x}'.format(ord(c))) - io.write('"') - return io.getvalue() + output.write(r'\x{:02x}'.format(ord(c))) + output.write('"') + return output.getvalue() def adjust_local_name(name):