Commits

Philip Jenvey  committed c1aa74c

2to3 most of lib_pypy except _ctypes/numpypy/pyrepl

  • Participants
  • Parent commits 4d32af2
  • Branches py3k

Comments (0)

Files changed (39)

File lib_pypy/__init__.py

 # This __init__.py shows up in PyPy's app-level standard library.
 # Let's try to prevent that confusion...
 if __name__ != 'lib_pypy':
-    raise ImportError, '__init__'
+    raise ImportError('__init__')

File lib_pypy/_collections.py

 
 import operator
 try:
-    from thread import get_ident as _thread_ident
+    from _thread import get_ident as _thread_ident
 except ImportError:
     def _thread_ident():
         return -1
         self._gen = itergen(deq.state, giveup)
 
     def __next__(self):
-        res =  self._gen.next()
+        res = next(self._gen)
         self.counter -= 1
         return res
 
 
            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()))
 

File lib_pypy/_csv.py

                                 (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 kwargs.values())):
                 return dialect
 
         self = object.__new__(cls)
 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)
     def __iter__(self):
         return self
 
-    def next(self):
+    def __next__(self):
         self._parse_reset()
         while True:
             try:
-                line = self.input_iter.next()
+                line = next(self.input_iter)
             except StopIteration:
                 # End of input OR exception
                 if len(self.field) > 0:
     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

File lib_pypy/_marshal.py

 
 import types
 from _codecs import utf_8_decode, utf_8_encode
+import sys
 
 try: from __pypy__ import builtinify
 except ImportError: builtinify = lambda f: f
                 if func:
                     break
             else:
-                raise ValueError, "unmarshallable object"
+                raise ValueError("unmarshallable object")
             func(self, x)
 
     def w_long64(self, x):
 
     def dump_none(self, x):
         self._write(TYPE_NONE)
-    dispatch[types.NoneType] = dump_none
+    dispatch[type(None)] = dump_none
 
     def dump_bool(self, x):
         if x:
 
     def dump_stopiter(self, x):
         if x is not StopIteration:
-            raise ValueError, "unmarshallable object"
+            raise ValueError("unmarshallable object")
         self._write(TYPE_STOPITER)
     dispatch[type(StopIteration)] = dump_stopiter
 
         self._write(TYPE_ELLIPSIS)
     
     try:
-        dispatch[types.EllipsisType] = dump_ellipsis
+        dispatch[type(Ellipsis)] = dump_ellipsis
     except NameError:
         pass
 
         else:
             self._write(TYPE_INT)
             self.w_long(x)
-    dispatch[types.IntType] = dump_int
+    dispatch[int] = dump_int
 
     def dump_long(self, x):
         self._write(TYPE_LONG)
         self.w_long(len(digits) * sign)
         for d in digits:
             self.w_short(d)
-    dispatch[types.LongType] = dump_long
+    dispatch[int] = dump_long
 
     def dump_float(self, x):
         write = self._write
         write(TYPE_FLOAT)
-        s = `x`
+        s = repr(x)
         write(chr(len(s)))
         write(s)
-    dispatch[types.FloatType] = dump_float
+    dispatch[float] = dump_float
 
     def dump_complex(self, x):
         write = self._write
         write(TYPE_COMPLEX)
-        s = `x.real`
+        s = repr(x.real)
         write(chr(len(s)))
         write(s)
-        s = `x.imag`
+        s = repr(x.imag)
         write(chr(len(s)))
         write(s)
     try:
-        dispatch[types.ComplexType] = dump_complex
+        dispatch[complex] = dump_complex
     except NameError:
         pass
 
         self._write(TYPE_STRING)
         self.w_long(len(x))
         self._write(x)
-    dispatch[types.StringType] = dump_string
+    dispatch[bytes] = dump_string
 
     def dump_unicode(self, x):
         self._write(TYPE_UNICODE)
         s, len_s = utf_8_encode(x)
         self.w_long(len_s)
         self._write(s)
-    dispatch[types.UnicodeType] = dump_unicode
+    dispatch[str] = dump_unicode
 
     def dump_tuple(self, x):
         self._write(TYPE_TUPLE)
         self.w_long(len(x))
         for item in x:
             self.dump(item)
-    dispatch[types.TupleType] = dump_tuple
+    dispatch[tuple] = dump_tuple
 
     def dump_list(self, x):
         self._write(TYPE_LIST)
         self.w_long(len(x))
         for item in x:
             self.dump(item)
-    dispatch[types.ListType] = dump_list
+    dispatch[list] = dump_list
 
     def dump_dict(self, x):
         self._write(TYPE_DICT)
             self.dump(key)
             self.dump(value)
         self._write(TYPE_NULL)
-    dispatch[types.DictionaryType] = dump_dict
+    dispatch[dict] = dump_dict
 
     def dump_code(self, x):
         self._write(TYPE_CODE)
         try:
             return self.dispatch[c](self)
         except KeyError:
-            raise ValueError, "bad marshal code: %c (%d)" % (c, ord(c))
+            raise ValueError("bad marshal code: %c (%d)" % (c, ord(c)))
 
     def r_short(self):
         lo = ord(self._read(1))
         d = ord(s[3])
         x = a | (b<<8) | (c<<16) | (d<<24)
         if d & 0x80 and x > 0:
-            x = -((1L<<32) - x)
+            x = -((1<<32) - x)
             return int(x)
         else:
             return x
         b = ord(self._read(1))
         c = ord(self._read(1))
         d = ord(self._read(1))
-        e = long(ord(self._read(1)))
-        f = long(ord(self._read(1)))
-        g = long(ord(self._read(1)))
-        h = long(ord(self._read(1)))
+        e = int(ord(self._read(1)))
+        f = int(ord(self._read(1)))
+        g = int(ord(self._read(1)))
+        h = int(ord(self._read(1)))
         x = a | (b<<8) | (c<<16) | (d<<24)
         x = x | (e<<32) | (f<<40) | (g<<48) | (h<<56)
         if h & 0x80 and x > 0:
-            x = -((1L<<64) - x)
+            x = -((1<<64) - x)
         return x
 
     def load_null(self):
         if size < 0:
             sign = -1
             size = -size
-        x = 0L
+        x = 0
         for i in range(size):
             d = self.r_short()
-            x = x | (d<<(i*15L))
+            x = x | (d<<(i*15))
         return x * sign
     dispatch[TYPE_LONG] = load_long
 
 
     def load_interned(self):
         n = self.r_long()
-        ret = intern(self._read(n))
+        ret = sys.intern(self._read(n))
         self._stringtable.append(ret)
         return ret
     dispatch[TYPE_INTERNED] = load_interned
     self.bufpos += 4
     x = a | (b<<8) | (c<<16) | (d<<24)
     if d & 0x80 and x > 0:
-        x = -((1L<<32) - x)
+        x = -((1<<32) - x)
         return int(x)
     else:
         return x
     b = ord(_read1(self))
     c = ord(_read1(self))
     d = ord(_read1(self))
-    e = long(ord(_read1(self)))
-    f = long(ord(_read1(self)))
-    g = long(ord(_read1(self)))
-    h = long(ord(_read1(self)))
+    e = int(ord(_read1(self)))
+    f = int(ord(_read1(self)))
+    g = int(ord(_read1(self)))
+    h = int(ord(_read1(self)))
     x = a | (b<<8) | (c<<16) | (d<<24)
     x = x | (e<<32) | (f<<40) | (g<<48) | (h<<56)
     if h & 0x80 and x > 0:
-        x = -((1L<<64) - x)
+        x = -((1<<64) - x)
     return x
 
 _load_dispatch = {}
             self.bufpos += 1
             return _load_dispatch[c](self)
         except KeyError:
-            raise ValueError, "bad marshal code: %c (%d)" % (c, ord(c))
+            raise ValueError("bad marshal code: %c (%d)" % (c, ord(c)))
         except IndexError:
             raise EOFError
 
         if size < 0:
             sign = -1
             size = -size
-        x = 0L
+        x = 0
         for i in range(size):
             d = _r_short(self)
-            x = x | (d<<(i*15L))
+            x = x | (d<<(i*15))
         return x * sign
     dispatch[TYPE_LONG] = load_long
 
 
     def load_interned(self):
         n = _r_long(self)
-        ret = intern(_read(self, n))
+        ret = sys.intern(_read(self, n))
         self._stringtable.append(ret)
         return ret
     dispatch[TYPE_INTERNED] = load_interned

File lib_pypy/_md5.py

         the hashed string.
         """
 
-        leninBuf = long(len(inBuf))
+        leninBuf = int(len(inBuf))
 
         # Compute number of bytes mod 64.
         index = (self.count[0] >> 3) & 0x3F

File lib_pypy/_pypy_interact.py

 if __name__ == '__main__':    # for testing
     import os
     if os.getenv('PYTHONSTARTUP'):
-        execfile(os.getenv('PYTHONSTARTUP'))
+        exec(compile(open(os.getenv('PYTHONSTARTUP')).read(), os.getenv('PYTHONSTARTUP'), 'exec'))
     interactive_console()

File lib_pypy/_pypy_wait.py

+from resource import _struct_rusage, struct_rusage
 from ctypes import CDLL, c_int, POINTER, byref
 from ctypes.util import find_library
-from resource import _struct_rusage, struct_rusage
 
 __all__ = ["wait3", "wait4"]
 

File lib_pypy/_scproxy.py

     length = (ffi.CFStringGetLength(value) * 4) + 1
     buff = create_string_buffer(length)
     ffi.CFStringGetCString(value, buff, length * 4, kCFStringEncodingUTF8)
-    return unicode(buff.value, 'utf8')
+    return str(buff.value, 'utf8')
 
 def cfnum_to_int32(num):
     result_ptr = pointer(c_int32(0))
                     if host:
                         if cfportnum:
                             port = cfnum_to_int32(cfportnum)
-                            v = u'http://%s:%d' % (host, port)
+                            v = 'http://%s:%d' % (host, port)
                         else:
-                            v = u'http://%s' % (host,)
+                            v = 'http://%s' % (host,)
                         result[proto.lower()] = v
         return result
     finally:

File lib_pypy/_sha256.py

     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'][:]
 def getbuf(s):
     if isinstance(s, str):
         return s
-    elif isinstance(s, unicode):
+    elif isinstance(s, str):
         return str(s)
     else:
         return buffer(s)

File lib_pypy/_sqlite3.py

 # SQLite version information
 sqlite_version = sqlite.sqlite3_libversion()
 
-class Error(StandardError):
+class Error(Exception):
     pass
 
-class Warning(StandardError):
+class Warning(Exception):
     pass
 
 class InterfaceError(Error):
     return factory(database, **kwargs)
 
 def unicode_text_factory(x):
-    return unicode(x, 'utf-8')
+    return str(x, 'utf-8')
 
 
 class StatementCache(object):
 
     def __call__(self, sql):
         self._check_closed()
-        if not isinstance(sql, (str, unicode)):
+        if not isinstance(sql, str):
             raise Warning("SQL is of wrong type. Must be string or unicode.")
         statement = self.statement_cache.get(sql, self.row_factory)
         return statement
     def _set_isolation_level(self, val):
         if val is None:
             self.commit()
-        if isinstance(val, unicode):
+        if isinstance(val, str):
             val = str(val)
         self._isolation_level = val
     isolation_level = property(_get_isolation_level, _set_isolation_level)
         return CursorLock(self)
 
     def execute(self, sql, params=None):
-        if type(sql) is unicode:
+        if type(sql) is str:
             sql = sql.encode("utf-8")
 
         with self._check_and_lock():
         return self
 
     def executemany(self, sql, many_params):
-        if type(sql) is unicode:
+        if type(sql) is str:
             sql = sql.encode("utf-8")
 
         with self._check_and_lock():
     def executescript(self, sql):
         self._description = None
         self.reset = False
-        if type(sql) is unicode:
+        if type(sql) is str:
             sql = sql.encode("utf-8")
         self._check_closed()
         statement = c_void_p()
 
     def _build_row_cast_map(self):
         self.row_cast_map = []
-        for i in xrange(sqlite.sqlite3_column_count(self.statement)):
+        for i in range(sqlite.sqlite3_column_count(self.statement)):
             converter = None
 
             if self.con.detect_types & PARSE_COLNAMES:
             self.row_cast_map.append(converter)
 
     def _check_decodable(self, param):
-        if self.con.text_factory in (unicode, OptimizedUnicode, unicode_text_factory):
+        if self.con.text_factory in (str, OptimizedUnicode, unicode_text_factory):
             for c in param:
                 if ord(c) & 0x80 != 0:
                     raise self.con.ProgrammingError(
 
         if param is None:
             sqlite.sqlite3_bind_null(self.statement, idx)
-        elif type(param) in (bool, int, long):
+        elif type(param) in (bool, int, int):
             if -2147483648 <= param <= 2147483647:
                 sqlite.sqlite3_bind_int(self.statement, idx, param)
             else:
         elif isinstance(param, str):
             self._check_decodable(param)
             sqlite.sqlite3_bind_text(self.statement, idx, param, len(param), SQLITE_TRANSIENT)
-        elif isinstance(param, unicode):
+        elif isinstance(param, str):
             param = param.encode("utf-8")
             sqlite.sqlite3_bind_text(self.statement, idx, param, len(param), SQLITE_TRANSIENT)
         elif type(param) is buffer:
     def _readahead(self, cursor):
         self.column_count = sqlite.sqlite3_column_count(self.statement)
         row = []
-        for i in xrange(self.column_count):
+        for i in range(self.column_count):
             typ = sqlite.sqlite3_column_type(self.statement, i)
 
             converter = self.row_cast_map[i]
             if converter is None:
                 if typ == SQLITE_INTEGER:
                     val = sqlite.sqlite3_column_int64(self.statement, i)
-                    if -sys.maxint-1 <= val <= sys.maxint:
+                    if -sys.maxsize-1 <= val <= sys.maxsize:
                         val = int(val)
                 elif typ == SQLITE_FLOAT:
                     val = sqlite.sqlite3_column_double(self.statement, i)
         if self.kind == DML:
             return None
         desc = []
-        for i in xrange(sqlite.sqlite3_column_count(self.statement)):
+        for i in range(sqlite.sqlite3_column_count(self.statement)):
             name = sqlite.sqlite3_column_name(self.statement, i).split("[")[0].strip()
             desc.append((name, None, None, None, None, None, None))
         return desc
         typ = sqlite.sqlite3_value_type(params[i])
         if typ == SQLITE_INTEGER:
             val = sqlite.sqlite3_value_int64(params[i])
-            if -sys.maxint-1 <= val <= sys.maxint:
+            if -sys.maxsize-1 <= val <= sys.maxsize:
                 val = int(val)
         elif typ == SQLITE_FLOAT:
             val = sqlite.sqlite3_value_double(params[i])
         elif typ == SQLITE_TEXT:
             val = sqlite.sqlite3_value_text(params[i])
             # XXX changed from con.text_factory
-            val = unicode(val, 'utf-8')
+            val = str(val, 'utf-8')
         else:
             raise NotImplementedError
         _params.append(val)
 def _convert_result(con, val):
     if val is None:
         sqlite.sqlite3_result_null(con)
-    elif isinstance(val, (bool, int, long)):
+    elif isinstance(val, (bool, int)):
         sqlite.sqlite3_result_int64(con, int(val))
     elif isinstance(val, str):
         # XXX ignoring unicode issue
         sqlite.sqlite3_result_text(con, val, len(val), SQLITE_TRANSIENT)
-    elif isinstance(val, unicode):
+    elif isinstance(val, str):
         val = val.encode('utf-8')
         sqlite.sqlite3_result_text(con, val, len(val), SQLITE_TRANSIENT)
     elif isinstance(val, float):
 
 def OptimizedUnicode(s):
     try:
-        val = unicode(s, "ascii").encode("ascii")
+        val = str(s, "ascii").encode("ascii")
     except UnicodeDecodeError:
-        val = unicode(s, "utf-8")
+        val = str(s, "utf-8")
     return val

File lib_pypy/_subprocess.py

 
     if env is not None:
         envbuf = ""
-        for k, v in env.iteritems():
+        for k, v in env.items():
             envbuf += "%s=%s\0" % (k, v)
         envbuf += '\0'
     else:

File lib_pypy/cPickle.py

 # One-liner implementation of cPickle
 #
 
+import marshal
+import struct
+import sys
 from pickle import Pickler, dump, dumps, PickleError, PicklingError, UnpicklingError, _EmptyClass
 from pickle import __doc__, __version__, format_version, compatible_formats
 from types import *
-from copy_reg import dispatch_table
-from copy_reg import _extension_registry, _inverted_registry, _extension_cache
-import marshal, struct, sys
+from copyreg import dispatch_table
+from copyreg import _extension_registry, _inverted_registry, _extension_cache
 
 try: from __pypy__ import builtinify
 except ImportError: builtinify = lambda f: f
     def load_proto(self):
         proto = ord(self.read(1))
         if not 0 <= proto <= 2:
-            raise ValueError, "unsupported pickle protocol: %d" % proto
+            raise ValueError("unsupported pickle protocol: %d" % proto)
     dispatch[PROTO] = load_proto
 
     def load_persid(self):
             try:
                 val = int(data)
             except ValueError:
-                val = long(data)
+                val = int(data)
         self.append(val)
     dispatch[INT] = load_int
 
     dispatch[BININT2] = load_binint2
 
     def load_long(self):
-        self.append(long(self.readline()[:-1], 0))
+        self.append(int(self.readline()[:-1], 0))
     dispatch[LONG] = load_long
 
     def load_long1(self):
     def load_string(self):
         rep = self.readline()
         if len(rep) < 3:
-            raise ValueError, "insecure string pickle"
+            raise ValueError("insecure string pickle")
         if rep[0] == "'" == rep[-2]:
             rep = rep[1:-2]
         elif rep[0] == '"' == rep[-2]:
             rep = rep[1:-2]
         else:
-            raise ValueError, "insecure string pickle"
+            raise ValueError("insecure string pickle")
         self.append(rep.decode("string-escape"))
     dispatch[STRING] = load_string
 
     dispatch[BINSTRING] = load_binstring
 
     def load_unicode(self):
-        self.append(unicode(self.readline()[:-1],'raw-unicode-escape'))
+        self.append(str(self.readline()[:-1],'raw-unicode-escape'))
     dispatch[UNICODE] = load_unicode
 
     def load_binunicode(self):
         L = mloads('i' + self.read(4))
-        self.append(unicode(self.read(L),'utf-8'))
+        self.append(str(self.read(L),'utf-8'))
     dispatch[BINUNICODE] = load_binunicode
 
     def load_short_binstring(self):
         if not instantiated:
             try:
                 value = klass(*args)
-            except TypeError, err:
-                raise TypeError, "in constructor for %s: %s" % (
-                    klass.__name__, str(err)), sys.exc_info()[2]
+            except TypeError as err:
+                raise TypeError("in constructor for %s: %s" % (
+                    klass.__name__, str(err))).with_traceback(sys.exc_info()[2])
         self.append(value)
 
     def load_inst(self):
             try:
                 d = inst.__dict__
                 try:
-                    for k, v in state.iteritems():
-                        d[intern(k)] = v
+                    for k, v in state.items():
+                        d[sys.intern(k)] = v
                 # keys in state don't have to be strings
                 # don't blow up, but don't go out of our way
                 except TypeError:
 
     nbytes = len(data)
     if nbytes == 0:
-        return 0L
+        return 0
     ind = nbytes - 1
     while ind and ord(data[ind]) == 0:
         ind -= 1
         if ord(data[ind]):
             n += ord(data[ind])
     if ord(data[nbytes - 1]) >= 128:
-        n -= 1L << (nbytes << 3)
+        n -= 1 << (nbytes << 3)
     return n
 
 def load(f):

File lib_pypy/dbm.py

 lib.DBM_INSERT = 0
 lib.DBM_REPLACE = 1
 
-def open(filename, flag='r', mode=0666):
+def open(filename, flag='r', mode=0o666):
     "open a DBM database"
     if not isinstance(filename, str):
         raise TypeError("expected string")

File lib_pypy/disassembler.py

     if type(x) is types.InstanceType:
         x = x.__class__
     if hasattr(x, 'im_func'):
-        x = x.im_func
+        x = x.__func__
     if hasattr(x, 'func_code'):
-        x = x.func_code
+        x = x.__code__
     if hasattr(x, '__dict__'):
         xxx
-        items = x.__dict__.items()
-        items.sort()
+        sorted(x.__dict__.items())
         for name, x1 in items:
             if type(x1) in (types.MethodType,
                             types.FunctionType,
                             types.CodeType,
-                            types.ClassType):
-                print "Disassembly of %s:" % name
+                            type):
+                print("Disassembly of %s:" % name)
                 try:
                     dis(x1)
                 except TypeError as msg:
-                    print "Sorry:", msg
-                print
+                    print("Sorry:", msg)
+                print()
     elif hasattr(x, 'co_code'):
         return disassemble(x)
     elif isinstance(x, str):
         return disassemble_string(x)
     else:
-        raise TypeError, \
-              "don't know how to disassemble %s objects" % \
-              type(x).__name__
+        raise TypeError("don't know how to disassemble %s objects" % \
+              type(x).__name__)
 
 def distb(tb=None):
     """Disassemble a traceback (default: last traceback)."""
         try:
             tb = sys.last_traceback
         except AttributeError:
-            raise RuntimeError, "no last traceback to disassemble"
+            raise RuntimeError("no last traceback to disassemble")
         while tb.tb_next: tb = tb.tb_next
     disassemble(tb.tb_frame.f_code, tb.tb_lasti)
 
             extended_arg = 0
             i = i+2
             if op == EXTENDED_ARG:
-                extended_arg = oparg*65536L
+                extended_arg = oparg*65536
             if op in hasconst:
                 opargstr = repr(co.co_consts[oparg])
             elif op in hasname:
         op = ord(c)
         if i == lasti:
             xxx
-            print '-->',
+            print('-->', end=' ')
         else:
             xxx
-            print '   ',
+            print('   ', end=' ')
         if i in labels:
             xxx
-            print '>>',
+            print('>>', end=' ')
         else:
             xxx
-            print '  ',
+            print('  ', end=' ')
         xxxx
-        print repr(i).rjust(4),
-        print opname[op].ljust(15),
+        print(repr(i).rjust(4), end=' ')
+        print(opname[op].ljust(15), end=' ')
         i = i+1
         if op >= HAVE_ARGUMENT:
             oparg = ord(code[i]) + ord(code[i+1])*256
             i = i+2
             xxx
-            print repr(oparg).rjust(5),
+            print(repr(oparg).rjust(5), end=' ')
             if op in hasconst:
                 if constants:
                     xxx
-                    print '(' + repr(constants[oparg]) + ')',
+                    print('(' + repr(constants[oparg]) + ')', end=' ')
                 else:
                     xxx
-                    print '(%d)'%oparg,
+                    print('(%d)'%oparg, end=' ')
             elif op in hasname:
                 if names is not None:
                     xxx
-                    print '(' + names[oparg] + ')',
+                    print('(' + names[oparg] + ')', end=' ')
                 else:
                     xxx
-                    print '(%d)'%oparg,
+                    print('(%d)'%oparg, end=' ')
             elif op in hasjrel:
                 xxx
-                print '(to ' + repr(i + oparg) + ')',
+                print('(to ' + repr(i + oparg) + ')', end=' ')
             elif op in haslocal:
                 if varnames:
                     xxx
-                    print '(' + varnames[oparg] + ')',
+                    print('(' + varnames[oparg] + ')', end=' ')
                 else:
                     xxx
-                    print '(%d)' % oparg,
+                    print('(%d)' % oparg, end=' ')
             elif op in hascompare:
                 xxx
-                print '(' + cmp_op[oparg] + ')',
+                print('(' + cmp_op[oparg] + ')', end=' ')
         xxx
-        print
+        print()
 
 disco = disassemble                     # XXX For backwards compatibility
 

File lib_pypy/greenlet.py

 # Internal stuff
 
 try:
-    from thread import _local
+    from _thread import _local
 except ImportError:
     class _local(object):    # assume no threads
         pass

File lib_pypy/identity_dict.py

 
     def copy(self):
         d = type(self)()
-        d.update(self.iteritems())
+        d.update(self.items())
         assert len(d) == len(self)
         return d
 
 
     def copy(self):
         d = type(self)()
-        d.update(self.iteritems())
+        d.update(self.items())
         assert len(d) == len(self)
         return d
 

File lib_pypy/itertools.py

             key = lambda x: x
         self.keyfunc = key
         self.it = iter(iterable)
-        self.tgtkey = self.currkey = self.currvalue = xrange(0)
+        self.tgtkey = self.currkey = self.currvalue = range(0)
 
     def __iter__(self):
         return self
     def __init__(self, obj, times=None):
         self._obj = obj
         if times is not None:
-            xrange(times) # Raise a TypeError
+            range(times) # Raise a TypeError
             if times < 0:
                 times = 0
         self._times = times
     if isinstance(iterable, TeeObject):
         # a,b = tee(range(10)) ; c,d = tee(a) ; self.assert_(a is c)
         return tuple([iterable] +
-        [TeeObject(tee_data=iterable.tee_data) for i in xrange(n-1)])
+        [TeeObject(tee_data=iterable.tee_data) for i in range(n - 1)])
     tee_data = TeeData(iter(iterable))
-    return tuple([TeeObject(tee_data=tee_data) for i in xrange(n)])
+    return tuple([TeeObject(tee_data=tee_data) for i in range(n)])

File lib_pypy/pwd.py

             yield self.pw_dir
             yield self.pw_shell
 
-class struct_passwd:
+class struct_passwd(metaclass=structseqtype):
     """
     pwd.struct_passwd: Results from getpw*() routines.
 
       (pw_name,pw_passwd,pw_uid,pw_gid,pw_gecos,pw_dir,pw_shell)
     or via the object attributes as named in the above tuple.
     """
-    __metaclass__ = structseqtype
     name = "pwd.struct_passwd"
     pw_name = structseqfield(0)
     pw_passwd = structseqfield(1)
     from os import getuid
     uid = getuid()
     pw = getpwuid(uid)
-    print("uid %s: %s" % (pw.pw_uid, pw))
+    print(("uid %s: %s" % (pw.pw_uid, pw)))
     name = pw.pw_name
-    print("name %r: %s" % (name, getpwnam(name)))
+    print(("name %r: %s" % (name, getpwnam(name))))
     print("All:")
     for pw in getpwall():
         print(pw)

File lib_pypy/pypy_test/inprogress_test_binascii_extra.py

-from __future__ import absolute_import
 from lib_pypy import binascii
 
 def test_uu():

File lib_pypy/pypy_test/test_collections.py

-from __future__ import absolute_import
 from lib_pypy import _collections as collections
 import py
 
 
         d = collections.deque(range(100))
         d.reverse()
-        assert list(d) == range(99, -1, -1)
+        assert list(d) == list(range(99, -1, -1))
 
     def test_subclass_with_kwargs(self):
         class SubclassWithKwargs(collections.deque):

File lib_pypy/pypy_test/test_coroutine.py

-from __future__ import absolute_import
 from py.test import skip, raises
 
 try:
     from stackless import coroutine, CoroutineExit
-except ImportError, e:
+except ImportError as e:
     skip('cannot import stackless: %s' % (e,))
 
 
     def test_is_zombie(self):
         co = coroutine()
         def f():
-            print 'in coro'
+            print('in coro')
         assert not co.is_zombie
         co.bind(f)
         assert not co.is_zombie
             def __del__(self):
                 res.append(self.is_zombie)
         def f():
-            print 'in coro'
+            print('in coro')
         co = MyCoroutine()
         co.bind(f)
         co.switch()
                 res.append(self.is_zombie)
         main = coroutine.getcurrent()
         def f():
-            print 'in coro'
+            print('in coro')
             main.switch()
         co = MyCoroutine()
         co.bind(f)

File lib_pypy/pypy_test/test_datetime.py

-from __future__ import absolute_import
 import py
 
 from lib_pypy import datetime
 
 def test_repr():
-    print datetime
+    print(datetime)
     expected = "datetime.datetime(1, 2, 3, 0, 0)"
     assert repr(datetime.datetime(1,2,3)) == expected
 

File lib_pypy/pypy_test/test_dbm_extra.py

-from __future__ import absolute_import
 import py
 from pypy.tool.udir import udir
 try:
     from lib_pypy import dbm
-except ImportError, e:
+except ImportError as e:
     py.test.skip(e)
 
 def test_get():

File lib_pypy/pypy_test/test_defaultdict.py

 # defaultdict Tests
 # from CPython2.5
-from __future__ import absolute_import
 import py
 import sys
 if sys.version_info < (2, 5):

File lib_pypy/pypy_test/test_deque_extra.py

 # Deque Tests
-from __future__ import absolute_import
 import py
 
 
     def test_deque_iter(self):
         it = iter(self.d)
         py.test.raises(TypeError, len, it)
-        assert it.next() == 0
+        assert next(it) == 0
         self.d.pop()
-        py.test.raises(RuntimeError, it.next)
+        py.test.raises(RuntimeError, next, it)
 
     def test_deque_reversed(self):
         it = reversed(self.d)
         py.test.raises(TypeError, len, it)
-        assert it.next() == n-1
-        assert it.next() == n-2
+        assert next(it) == n-1
+        assert next(it) == n-2
         self.d.pop()
-        py.test.raises(RuntimeError, it.next)
+        py.test.raises(RuntimeError, next, it)
 
     def test_deque_remove(self):
         d = self.d

File lib_pypy/pypy_test/test_grp_extra.py

-from __future__ import absolute_import
 import py
 try:
     from lib_pypy import grp

File lib_pypy/pypy_test/test_itertools.py

 
     def test_compress_diff_len(self):
         it = itertools.compress(['a'], [])
-        raises(StopIteration, it.next)
+        raises(StopIteration, next, it)
 
     def test_product(self):
         l = [1, 2]

File lib_pypy/pypy_test/test_marshal_extra.py

-from __future__ import absolute_import
 import py
 import sys
 import marshal as cpy_marshal
     StopIteration,
     Ellipsis,
     42,
-    sys.maxint,
+    sys.maxsize,
     -1.25,
     2+5j,
-    42L,
-    -1234567890123456789012345678901234567890L,
+    42,
+    -1234567890123456789012345678901234567890,
     hello,   # not interned
     "hello",
     (),
     [3, 4],
     {},
     {5: 6, 7: 8},
-    func.func_code,
-    scopefunc.func_code,
-    u'hello',
+    func.__code__,
+    scopefunc.__code__,
+    'hello',
     ]
 
 try:
         yield dump_to_cpython, case
 
 def dumps_and_reload(case):
-    print 'dump_and_reload', `case`
+    print('dump_and_reload', repr(case))
     s = marshal.dumps(case)
     obj = marshal.loads(s)
     assert obj == case
 
 def loads_from_cpython(case):
-    print 'load_from_cpython', `case`
+    print('load_from_cpython', repr(case))
     try:
         s = cpy_marshal.dumps(case, *cpy_dump_version)
     except ValueError:
     assert obj == case
 
 def dumps_to_cpython(case):
-    print 'dump_to_cpython', `case`
+    print('dump_to_cpython', repr(case))
     try:
         cpy_marshal.dumps(case, *cpy_dump_version)
     except ValueError:

File lib_pypy/pypy_test/test_md5_extra.py

 160 sec. per MB of data on a 233 MHz Intel Pentium CPU.
 """
 
-from __future__ import absolute_import
 import md5                              # CPython's implementation in C.
 from lib_pypy import _md5 as pymd5  
 
 def formatHex(str):
     "Print a string's HEX code in groups of two digits."
 
-    d = map(None, str)
+    d = list(str)
     d = map(ord, d)
-    d = map(lambda x:"%02x" % x, d)
+    d = ["%02x" % x for x in d]
     return ' '.join(d)
 
 
 def printDiff(message, d1, d2, expectedResult=None):
     "Print different outputs for same message."
     
-    print "Message: '%s'" % message
-    print "Message length: %d" % len(message)
+    print("Message: '%s'" % message)
+    print("Message length: %d" % len(message))
     if expectedResult:
-        print "%-48s (expected)" % format(expectedResult)
-    print "%-48s (Std. lib. MD5)" % formatHex(d1)
-    print "%-48s (Pure Python MD5)" % formatHex(d2)
-    print
+        print("%-48s (expected)" % format(expectedResult))
+    print("%-48s (Std. lib. MD5)" % formatHex(d1))
+    print("%-48s (Pure Python MD5)" % formatHex(d2))
+    print()
 
 
 # The real comparison function.
            "57edf4a22be3c955ac49da2e2107b67a"),
         )
 
-        for i in xrange(len(cases)):
+        for i in range(len(cases)):
             res = compareImp(cases[i][0])
             if res is not None:
                 d1, d2 = res
           "123456789 123456789 123456789 12345678",
          )
 
-        for i in xrange(len(cases)):
+        for i in range(len(cases)):
             res = compareImp(cases[i][0])
             if res is not None:
                 d1, d2 = res
 ##          (2**20*'a',),  ## 1 MB, takes about 160 sec. on a 233 Mhz Pentium.
          )
 
-        for i in xrange(len(cases)):
+        for i in range(len(cases)):
             res = compareImp(cases[i][0])
             if res is not None:
                 d1, d2 = res
         m2c = m2.copy()
 
         # Update and compare...
-        for i in xrange(len(cases)):
+        for i in range(len(cases)):
             message = cases[i][0]
 
             m1c.update(message)

File lib_pypy/pypy_test/test_os_wait.py

 # Generates the resource cache
-from __future__ import absolute_import
 from lib_pypy.ctypes_config_cache import rebuild
 rebuild.rebuild_one('resource.ctc.py')
 

File lib_pypy/pypy_test/test_resource.py

-from __future__ import absolute_import
 from lib_pypy.ctypes_config_cache import rebuild
 rebuild.rebuild_one('resource.ctc.py')
 
         if i < 2:
             expected_type = float
         else:
-            expected_type = (int, long)
+            expected_type = int
         assert isinstance(x[i], expected_type)

File lib_pypy/pypy_test/test_sha_extra.py

 # use the three examples from Federal Information Processing Standards
 # Publication 180-1, Secure Hash Standard,  1995 April 17
 # http://www.itl.nist.gov/div897/pubs/fip180-1.htm
-from __future__ import absolute_import
 from lib_pypy import _sha as pysha
 
 class TestSHA: 

File lib_pypy/pypy_test/test_stackless.py

 2. CPython (with the stackless_new module in the path
 3. pypy-c
 """
-from __future__ import absolute_import
 from py.test import skip
 try:
     import stackless
 except ImportError:
     try:
         from lib_pypy import stackless
-    except ImportError, e:
+    except ImportError as e:
         skip('cannot import stackless: %s' % (e,))
 
 SHOW_STRANGE = False
 
 def dprint(txt):
     if SHOW_STRANGE:
-        print txt
+        print(txt)
 
 class Test_Stackless:
 
     def test_send_counter(self):
         import random
 
-        numbers = range(20)
+        numbers = list(range(20))
         random.shuffle(numbers)
 
         def counter(n, ch):
-            for i in xrange(n):
+            for i in range(n):
                 stackless.schedule()
             ch.send(n)
 
     def test_receive_counter(self):
         import random
 
-        numbers = range(20)
+        numbers = list(range(20))
         random.shuffle(numbers)
 
         rlist = []
         def counter(n, ch):
-            for i in xrange(n):
+            for i in range(n):
                 stackless.schedule()
             ch.receive()
             rlist.append(n)
         try:
             stackless.run()
         # cheating, can't test for ZeroDivisionError
-        except Exception, e:
+        except Exception as e:
             rlist.append('E')
         stackless.schedule()
         stackless.schedule()
         def exp_recv(chan):
             try:
                 val = chan.receive()
-            except Exception, exp:
+            except Exception as exp:
                 assert exp.__class__ is Exception
                 assert str(exp) == 'test'
 

File lib_pypy/pypy_test/test_stackless_pickling.py

-from __future__ import absolute_import
 from py.test import skip
 try:
     import stackless
 except ImportError:
     try:
         from lib_pypy import stackless as stackless
-    except ImportError, e:
+    except ImportError as e:
         skip('cannot import stackless: %s' % (e,))
 
 
     def test_pickle_main_coroutine(self):
         import stackless, pickle
         s = pickle.dumps(stackless.coroutine.getcurrent())
-        print s
+        print(s)
         c = pickle.loads(s)
         assert c is stackless.coroutine.getcurrent()
 
         mod = new.module('mod')
         mod.output = output
 
-        exec """from stackless import schedule
+        exec("""from stackless import schedule
         
 def aCallable(name):
     output.append(('b', name))
     schedule()
     output.append(('a', name))
-""" in mod.__dict__
+""", mod.__dict__)
         import sys
         sys.modules['mod'] = mod
         aCallable = mod.aCallable

File lib_pypy/pypy_test/test_structseq.py

-from __future__ import absolute_import
 import py
 from lib_pypy._structseq import structseqfield, structseqtype
 
 
-class mydata:
-    __metaclass__ = structseqtype
-
+class mydata(metaclass=structseqtype):
     st_mode  = structseqfield(0, "protection bits")
     st_ino   = structseqfield(1)
     st_dev   = structseqfield(2)
     assert mydata.n_unnamed_fields == 0
 
 def test_mydata():
-    x = mydata(range(100, 111))
+    x = mydata(list(range(100, 111)))
     assert x.n_sequence_fields == type(x).n_sequence_fields == 10
     assert x.n_fields == type(x).n_fields == 14
     assert x.st_mode  == 100
     assert x.st_ctime == 109    # copied by the default=lambda...
     assert x.st_rdev  == 110
     assert len(x)     == 10
-    assert list(x)    == range(100, 110)
+    assert list(x)    == list(range(100, 110))
     assert x + (5,)   == tuple(range(100, 110)) + (5,)
     assert x[4:12:2]  == (104, 106, 108)
     assert 104 in x
     assert 110 not in x
 
 def test_default_None():
-    x = mydata(range(100, 110))
+    x = mydata(list(range(100, 110)))
     assert x.st_rdev is None
 
 def test_constructor():
-    x = mydata(range(100, 111), {'st_mtime': 12.25})
+    x = mydata(list(range(100, 111)), {'st_mtime': 12.25})
     assert x[8] == 108
     assert x.st_mtime == 12.25
 
 def test_compare_like_tuple():
-    x = mydata(range(100, 111))
-    y = mydata(range(100, 110) + [555])
+    x = mydata(list(range(100, 111)))
+    y = mydata(list(range(100, 110)) + [555])
     assert x == tuple(range(100, 110))
     assert x == y    # blame CPython
     assert hash(x) == hash(y) == hash(tuple(range(100, 110)))
 
 def test_pickle():
     import pickle
-    x = mydata(range(100, 111))
+    x = mydata(list(range(100, 111)))
     s = pickle.dumps(x)
     y = pickle.loads(s)
     assert x == y
     assert x.st_rdev == y.st_rdev == 110
 
 def test_readonly():
-    x = mydata(range(100, 113))
+    x = mydata(list(range(100, 113)))
     py.test.raises((TypeError, AttributeError), "x.st_mode = 1")
     py.test.raises((TypeError, AttributeError), "x.st_mtime = 1")
     py.test.raises((TypeError, AttributeError), "x.st_rdev = 1")
 
 def test_no_extra_assignments():
-    x = mydata(range(100, 113))
+    x = mydata(list(range(100, 113)))
     py.test.raises((TypeError, AttributeError), "x.some_random_attribute = 1")

File lib_pypy/pypy_test/test_syslog.py

-from __future__ import absolute_import
 # XXX very minimal test
 
 from lib_pypy.ctypes_config_cache import rebuild

File lib_pypy/resource.py

 _getrusage.restype = c_int
 
 
-class struct_rusage:
-    __metaclass__ = _structseq.structseqtype
-
+class struct_rusage(metaclass=_structseq.structseqtype):
     ru_utime = _structseq.structseqfield(0)
     ru_stime = _structseq.structseqfield(1)
     ru_maxrss = _structseq.structseqfield(2)

File lib_pypy/stackless.py

 
 
 try:
-    from thread import _local
+    from _thread import _local
 except ImportError:
     class _local(object):    # assume no threads
         pass
         self.traceback = exp_traceback
 
     def raise_(self):
-        raise self.type, self.value, self.traceback
+        raise self.type(self.value).with_traceback(self.traceback)
 
 #
 #
 
     def insert(self):
         if self.blocked:
-            raise RuntimeError, "You cannot run a blocked tasklet"
+            raise RuntimeError("You cannot run a blocked tasklet")
             if not self.alive:
-                raise RuntimeError, "You cannot run an unbound(dead) tasklet"
+                raise RuntimeError("You cannot run an unbound(dead) tasklet")
         _scheduler_append(self)
 
     def remove(self):
         if self.blocked:
-            raise RuntimeError, "You cannot remove a blocked tasklet."
+            raise RuntimeError("You cannot remove a blocked tasklet.")
         if self is getcurrent():
-            raise RuntimeError, "The current tasklet cannot be removed."
+            raise RuntimeError("The current tasklet cannot be removed.")
             # not sure if I will revive this  " Use t=tasklet().capture()"
         _scheduler_remove(self)
 
     _main_tasklet = coroutine.getcurrent()
     _main_tasklet.__class__ = tasklet         # XXX HAAAAAAAAAAAAAAAAAAAAACK
     _last_task = _main_tasklet
-    tasklet._init.im_func(_main_tasklet, label='main')
+    tasklet._init.__func__(_main_tasklet, label='main')
     _squeue = deque()
     _scheduler_append(_main_tasklet)
 

File lib_pypy/tputil.py

         res = objattr(*self.args, **self.kwargs) 
         if self.opname == "__getattribute__": 
             if (isinstance(res, MethodType) and
-                res.im_self is self.instance):
-                res = MethodType(res.im_func, self.proxyobj, res.im_class)
+                res.__self__ is self.instance):
+                res = MethodType(res.__func__, self.proxyobj, res.__self__.__class__)
         if res is self.obj: 
             res = self.proxyobj
         return res