--- twisted/plugin.py (original)
+++ twisted/plugin.py (refactored)
@@ -20,7 +20,7 @@
     Determine which 'pickle' API module to use.
     """
     try:
-        import cPickle
+        import pickle
         return cPickle
     except ImportError:
         import pickle
@@ -102,7 +102,7 @@
 def _generateCacheEntry(provider):
     dropin = CachedDropin(provider.__name__,
                           provider.__doc__)
-    for k, v in provider.__dict__.iteritems():
+    for k, v in provider.__dict__.items():
         plugin = IPlugin(v, None)
         if plugin is not None:
             cachedPlugin = CachedPlugin(dropin, k, v.__doc__, list(providedBy(plugin)))
@@ -144,7 +144,7 @@
             buckets[fpp] = []
         bucket = buckets[fpp]
         bucket.append(plugmod)
-    for pseudoPackagePath, bucket in buckets.iteritems():
+    for pseudoPackagePath, bucket in buckets.items():
         dropinPath = pseudoPackagePath.child('dropin.cache')
         try:
             lastCached = dropinPath.getModificationTime()
@@ -170,7 +170,7 @@
                     entry = _generateCacheEntry(provider)
                     dropinDotCache[pluginKey] = entry
         # Make sure that the cache doesn't contain any stale plugins.
-        for pluginKey in dropinDotCache.keys():
+        for pluginKey in list(dropinDotCache.keys()):
             if pluginKey not in existingKeys:
                 del dropinDotCache[pluginKey]
                 needsWrite = True
@@ -198,7 +198,7 @@
     if package is None:
         import twisted.plugins as package
     allDropins = getCache(package)
-    for dropin in allDropins.itervalues():
+    for dropin in allDropins.values():
         for plugin in dropin.plugins:
             try:
                 adapted = interface(plugin, None)
--- twisted/application/app.py (original)
+++ twisted/application/app.py (refactored)
@@ -63,7 +63,7 @@
         """
         try:
             import profile
-        except ImportError, e:
+        except ImportError as e:
             self._reportImportError("profile", e)
 
         p = profile.Profile()
@@ -91,7 +91,7 @@
         """
         try:
             import hotshot.stats
-        except (ImportError, SystemExit), e:
+        except (ImportError, SystemExit) as e:
             # Certain versions of Debian (and Debian derivatives) raise
             # SystemExit when importing hotshot if the "non-free" profiler
             # module is not installed.  Someone eventually recognized this
@@ -142,7 +142,7 @@
         """
         try:
             import cProfile, pstats
-        except ImportError, e:
+        except ImportError as e:
             self._reportImportError("cProfile", e)
 
         p = cProfile.Profile()
@@ -293,7 +293,7 @@
         return 1
 
     def help_stop(self):
-        print """stop - Continue execution, then cleanly shutdown the twisted reactor."""
+        print("""stop - Continue execution, then cleanly shutdown the twisted reactor.""")
 
     def set_quit(self):
         os._exit(0)
@@ -504,7 +504,7 @@
         log.msg("Loading %s..." % filename)
         application = service.loadApplication(filename, style, passphrase)
         log.msg("Loaded.")
-    except Exception, e:
+    except Exception as e:
         s = "Failed to load application: %s" % e
         if isinstance(e, KeyError) and e.args[0] == "application":
             s += """
@@ -569,7 +569,7 @@
                    "See the list of available reactors with "
                    "--help-reactors" % (shortName,))
             raise usage.UsageError(msg)
-        except Exception, e:
+        except Exception as e:
             msg = ("The specified reactor cannot be used, failed with error: "
                    "%s.\nSee the list of available reactors with "
                    "--help-reactors" % (e,))
@@ -687,9 +687,9 @@
     config = ServerOptions()
     try:
         config.parseOptions()
-    except usage.error, ue:
-        print config
-        print "%s: %s" % (sys.argv[0], ue)
+    except usage.error as ue:
+        print(config)
+        print("%s: %s" % (sys.argv[0], ue))
     else:
         runApp(config)
 
--- twisted/application/service.py (original)
+++ twisted/application/service.py (refactored)
@@ -168,7 +168,7 @@
 
     def __getstate__(self):
         dict = self.__dict__.copy()
-        if dict.has_key("running"):
+        if "running" in dict:
             del dict['running']
         return dict
 
@@ -294,7 +294,7 @@
 
     def addService(self, service):
         if service.name is not None:
-            if self.namedServices.has_key(service.name):
+            if service.name in self.namedServices:
                 raise RuntimeError("cannot have two services with same name"
                                    " '%s'" % service.name)
             self.namedServices[service.name] = service
--- twisted/application/strports.py (original)
+++ twisted/application/strports.py (refactored)
@@ -34,7 +34,7 @@
 
 Maintainer: Moshe Zadka
 """
-from __future__ import generators
+
 
 def _parseTCP(factory, port, interface="", backlog=50):
     return (int(port), factory), {'interface': interface,
@@ -66,7 +66,7 @@
           "unix": _parseUNIX,
           "ssl": _parseSSL}
 
-_OP, _STRING = range(2)
+_OP, _STRING = list(range(2))
 def _tokenize(description):
     current = ''
     ops = ':='
@@ -79,7 +79,7 @@
             current = ''
             ops = nextOps[n]
         elif n=='\\':
-            current += description.next()
+            current += next(description)
         else:
             current += n
     yield _STRING, current
--- twisted/conch/avatar.py (original)
+++ twisted/conch/avatar.py (refactored)
@@ -1,6 +1,6 @@
 # -*- test-case-name: twisted.conch.test.test_conch -*-
-from interfaces import IConchUser
-from error import ConchError
+from .interfaces import IConchUser
+from .error import ConchError
 from ssh.connection import OPEN_UNKNOWN_CHANNEL_TYPE
 from twisted.python import log
 from zope import interface
--- twisted/conch/checkers.py (original)
+++ twisted/conch/checkers.py (refactored)
@@ -146,7 +146,7 @@
                 continue
             try:
                 lines = open(filename)
-            except IOError, e:
+            except IOError as e:
                 if e.errno == errno.EACCES:
                     lines = runAsEffectiveUser(ouid, ogid, open, filename)
                 else:
@@ -177,7 +177,7 @@
     successfulCredentials = {}
 
     def get_credentialInterfaces(self):
-        return self.checkers.keys()
+        return list(self.checkers.keys())
 
     credentialInterfaces = property(get_credentialInterfaces)
 
--- twisted/conch/manhole.py (original)
+++ twisted/conch/manhole.py (refactored)
@@ -13,7 +13,7 @@
 @author: Jp Calderone
 """
 
-import code, sys, StringIO, tokenize
+import code, sys, io, tokenize
 
 from twisted.conch import recvline
 
@@ -276,7 +276,7 @@
     """
     w = VT102Writer()
     p = TokenPrinter(w.write).printtoken
-    s = StringIO.StringIO(source)
+    s = io.StringIO(source)
 
     tokenize.tokenize(s.readline, p)
 
--- twisted/conch/recvline.py (original)
+++ twisted/conch/recvline.py (refactored)
@@ -58,7 +58,7 @@
                   'HOME', 'INSERT', 'DELETE', 'END', 'PGUP', 'PGDN',
                   'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9',
                   'F10', 'F11', 'F12'):
-        exec '%s = object()' % (keyID,)
+        exec('%s = object()' % (keyID,))
 
     TAB = '\t'
     BACKSPACE = '\x7f'
@@ -68,12 +68,12 @@
         self.transports = transports
 
     for method in insults.ITerminalTransport:
-        exec """\
+        exec("""\
 def %s(self, *a, **kw):
     for tpt in self.transports:
         result = tpt.%s(*a, **kw)
     return result
-""" % (method, method)
+""" % (method, method))
 
 class LocalTerminalBufferMixin(object):
     """A mixin for RecvLine subclasses which records the state of the terminal.
--- twisted/conch/telnet.py (original)
+++ twisted/conch/telnet.py (refactored)
@@ -514,7 +514,7 @@
 
 
     def connectionLost(self, reason):
-        for state in self.options.values():
+        for state in list(self.options.values()):
             if state.us.onResult is not None:
                 d = state.us.onResult
                 state.us.onResult = None
@@ -904,7 +904,7 @@
             getattr(self, 'linemode_' + self.linemodeSubcommands[linemodeSubcommand])(bytes[1:])
 
     def linemode_SLC(self, bytes):
-        chunks = zip(*[iter(bytes)]*3)
+        chunks = list(zip(*[iter(bytes)]*3))
         for slcFunction, slcValue, slcWhat in chunks:
             # Later, we should parse stuff.
             'SLC', ord(slcFunction), ord(slcValue), ord(slcWhat)
--- twisted/conch/unix.py (original)
+++ twisted/conch/unix.py (refactored)
@@ -9,15 +9,15 @@
 from ssh.filetransfer import FXF_READ, FXF_WRITE, FXF_APPEND, FXF_CREAT, FXF_TRUNC, FXF_EXCL
 from twisted.conch.ls import lsLine
 
-from avatar import ConchUser
-from error import ConchError
-from interfaces import ISession, ISFTPServer, ISFTPFile
+from .avatar import ConchUser
+from .error import ConchError
+from .interfaces import ISession, ISFTPServer, ISFTPFile
 
 import struct, os, time, socket
 import fcntl, tty
 import pwd, grp
 import pty
-import ttymodes
+from . import ttymodes
 
 try:
     import utmp
@@ -93,7 +93,7 @@
 
     def logout(self):
         # remove all listeners
-        for listener in self.listeners.itervalues():
+        for listener in self.listeners.values():
             self._runAsUser(listener.stopListening)
         log.msg('avatar %s logging out (%i)' % (self.username, len(self.listeners)))
 
@@ -237,7 +237,7 @@
         pty = self.pty
         attr = tty.tcgetattr(pty.fileno())
         for mode, modeValue in self.modes:
-            if not ttymodes.TTYMODES.has_key(mode): continue
+            if mode not in ttymodes.TTYMODES: continue
             ttyMode = ttymodes.TTYMODES[mode]
             if len(ttyMode) == 2: # flag
                 flag, ttyAttr = ttyMode
@@ -303,11 +303,11 @@
         NOTE: this function assumes it runs as the logged-in user:
         i.e. under _runAsUser()
         """
-        if attrs.has_key("uid") and attrs.has_key("gid"):
+        if "uid" in attrs and "gid" in attrs:
             os.chown(path, attrs["uid"], attrs["gid"])
-        if attrs.has_key("permissions"):
+        if "permissions" in attrs:
             os.chmod(path, attrs["permissions"])
-        if attrs.has_key("atime") and attrs.has_key("mtime"):
+        if "atime" in attrs and "mtime" in attrs:
             os.utime(path, (attrs["atime"], attrs["mtime"]))
 
     def _getAttrs(self, s):
@@ -399,11 +399,11 @@
             openFlags |= os.O_TRUNC
         if flags & FXF_EXCL == FXF_EXCL:
             openFlags |= os.O_EXCL
-        if attrs.has_key("permissions"):
+        if "permissions" in attrs:
             mode = attrs["permissions"]
             del attrs["permissions"]
         else:
-            mode = 0777
+            mode = 0o777
         fd = server.avatar._runAsUser(os.open, filename, openFlags, mode)
         if attrs:
             server.avatar._runAsUser(server._setAttrs, filename, attrs)
@@ -438,7 +438,7 @@
     def __iter__(self):
         return self
 
-    def next(self):
+    def __next__(self):
         try:
             f = self.files.pop(0)
         except IndexError:
--- twisted/conch/client/default.py (original)
+++ twisted/conch/client/default.py (refactored)
@@ -86,14 +86,14 @@
     retVal = 0
 
     if not options['known-hosts'] and not os.path.exists(os.path.expanduser('~/.ssh/')):
-        print 'Creating ~/.ssh directory...'
+        print('Creating ~/.ssh directory...')
         os.mkdir(os.path.expanduser('~/.ssh'))
     kh_file = options['known-hosts'] or '~/.ssh/known_hosts'
     try:
         known_hosts = open(os.path.expanduser(kh_file))
     except IOError:
         return 0
-    for line in known_hosts.xreadlines():
+    for line in known_hosts:
         split = line.split()
         if len(split) < 3:
             continue
@@ -154,7 +154,7 @@
             sys.stdout,sys.stdin=oldout,oldin
             return p
         except (KeyboardInterrupt, IOError):
-            print
+            print()
             raise ConchError('PEBKAC')
 
     def getPassword(self, prompt = None):
@@ -200,7 +200,7 @@
             return None
         try:
             return defer.succeed(keys.getPrivateKeyObject(file))
-        except keys.BadKeyError, e:
+        except keys.BadKeyError as e:
             if e.args[0] == 'encrypted key with no passphrase':
                 for i in range(3):
                     prompt = "Enter passphrase for key '%s': " % \
@@ -213,7 +213,7 @@
                 return defer.fail(ConchError('bad password'))
             raise
         except KeyboardInterrupt:
-            print
+            print()
             reactor.stop()
 
     def getGenericAnswers(self, name, instruction, prompts):
@@ -222,12 +222,12 @@
             oldout, oldin = sys.stdout, sys.stdin
             sys.stdin = sys.stdout = open('/dev/tty','r+')
             if name:
-                print name
+                print(name)
             if instruction:
-                print instruction
+                print(instruction)
             for prompt, echo in prompts:
                 if echo:
-                    responses.append(raw_input(prompt))
+                    responses.append(input(prompt))
                 else:
                     responses.append(getpass.getpass(prompt))
         finally: 
--- twisted/conch/client/direct.py (original)
+++ twisted/conch/client/direct.py (refactored)
@@ -83,7 +83,7 @@
     def receiveDebug(self, alwaysDisplay, message, lang):
         log.msg('Received Debug Message: %s' % message)
         if alwaysDisplay: # XXX what should happen here?
-            print message
+            print(message)
 
 
     def verifyHostKey(self, pubKey, fingerprint):
@@ -102,7 +102,7 @@
                 filename = os.path.expanduser("~/.conch-%s-%s-%i" % (user, peer.host, peer.port))
                 u = unix.SSHUnixServerFactory(service)
                 try:
-                    self.unixServer = reactor.listenUNIX(filename, u, mode=0600, wantPID=1)
+                    self.unixServer = reactor.listenUNIX(filename, u, mode=0o600, wantPID=1)
                 except:
                     if self.factory.d is not None:
                         d, self.factory.d = self.factory.d, None
--- twisted/conch/client/options.py (original)
+++ twisted/conch/client/options.py (refactored)
@@ -5,7 +5,7 @@
 from twisted.conch.ssh.transport import SSHClientTransport, SSHCiphers
 from twisted.python import usage
 
-import connect
+from . import connect
 
 import sys
 
@@ -38,13 +38,13 @@
     zsh_mutuallyExclusive = [("agent", "noagent")]
     zsh_actions = {"user":"_users",
                    "ciphers":"_values -s , 'ciphers to choose from' %s" %
-                       " ".join(SSHCiphers.cipherMap.keys()),
+                       " ".join(list(SSHCiphers.cipherMap.keys())),
                    "macs":"_values -s , 'macs to choose from' %s" %
-                       " ".join(SSHCiphers.macMap.keys()),
+                       " ".join(list(SSHCiphers.macMap.keys())),
                    "host-key-algorithms":"_values -s , 'host key algorithms to choose from' %s" %
                        " ".join(SSHClientTransport.supportedPublicKeys),
                    "connection-usage":"_values -s , 'connection types to choose from' %s" %
-                       " ".join(connect.connectTypes.keys()),
+                       " ".join(list(connect.connectTypes.keys())),
                    #"user-authentications":"_values -s , 'user authentication types to choose from' %s" %
                    #    " ".join(???),
                    }
@@ -65,7 +65,7 @@
         "Select encryption algorithms"
         ciphers = ciphers.split(',')
         for cipher in ciphers:
-            if not SSHCiphers.cipherMap.has_key(cipher):
+            if cipher not in SSHCiphers.cipherMap:
                 sys.exit("Unknown cipher type '%s'" % cipher)
         self['ciphers'] = ciphers
 
@@ -74,7 +74,7 @@
         "Specify MAC algorithms"
         macs = macs.split(',')
         for mac in macs:
-            if not SSHCiphers.macMap.has_key(mac):
+            if mac not in SSHCiphers.macMap:
                 sys.exit("Unknown mac type '%s'" % mac)
         self['macs'] = macs
 
@@ -92,7 +92,7 @@
 
     def opt_connection_usage(self, conns):
         conns = conns.split(',')
-        connTypes = connect.connectTypes.keys()
+        connTypes = list(connect.connectTypes.keys())
         for conn in conns:
             if conn not in connTypes:
                 sys.exit("Unknown connection type '%s'" % conn)
--- twisted/conch/client/unix.py (original)
+++ twisted/conch/client/unix.py (refactored)
@@ -50,7 +50,7 @@
         except:
             connector.stopConnecting()
             return
-        if stat.S_IMODE(filestats[0]) != 0600:
+        if stat.S_IMODE(filestats[0]) != 0o600:
             log.msg("socket mode is not 0600: %s" % oct(stat.S_IMODE(stats[0])))
         elif filestats[4] != os.getuid():
             log.msg("socket not owned by us: %s" % stats[4])
@@ -273,7 +273,7 @@
         self.conn = conn
 
     def connectionLost(self, reason):
-        for channel in self.conn.channels.values():
+        for channel in list(self.conn.channels.values()):
             if isinstance(channel, SSHUnixChannel) and channel.unix == self:
                 log.msg('forcibly closing %s' % channel)
                 try:
@@ -282,7 +282,7 @@
                     pass
 
     def haveChannel(self, channelID):
-        return self.conn.channels.has_key(channelID)
+        return channelID in self.conn.channels
 
     def getChannel(self, channelID):
         channel = self.conn.channels[channelID]
--- twisted/conch/insults/client.py (original)
+++ twisted/conch/insults/client.py (refactored)
@@ -124,7 +124,7 @@
             elif command[0] == 'attributes':
                 redraw += '\x1b[%sm' % ';'.join(map(str, command[1]))
             else:
-                print command
+                print(command)
         self.commandQueue = []
         self.transport.write(redraw)
 
--- twisted/conch/insults/helper.py (original)
+++ twisted/conch/insults/helper.py (refactored)
@@ -19,7 +19,7 @@
 
 FOREGROUND = 30
 BACKGROUND = 40
-BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, N_COLORS = range(9)
+BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, N_COLORS = list(range(9))
 
 class CharacterAttribute:
     """Represents the attributes of a single character.
@@ -98,7 +98,7 @@
                   'HOME', 'INSERT', 'DELETE', 'END', 'PGUP', 'PGDN',
                   'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9',
                   'F10', 'F11', 'F12'):
-        exec '%s = object()' % (keyID,)
+        exec('%s = object()' % (keyID,))
 
     TAB = '\t'
     BACKSPACE = '\x7f'
@@ -158,7 +158,7 @@
             self.x += 1
 
     def _emptyLine(self, width):
-        return [(self.void, self._currentCharacterAttributes()) for i in xrange(width)]
+        return [(self.void, self._currentCharacterAttributes()) for i in range(width)]
 
     def _scrollDown(self):
         self.y += 1
@@ -332,7 +332,7 @@
         self.lines[self.y][:self.x + 1] = self._emptyLine(self.x + 1)
 
     def eraseDisplay(self):
-        self.lines = [self._emptyLine(self.width) for i in xrange(self.height)]
+        self.lines = [self._emptyLine(self.width) for i in range(self.height)]
 
     def eraseToDisplayEnd(self):
         self.eraseToLineEnd()
@@ -382,7 +382,7 @@
         self.eraseDisplay()
 
     def unhandledControlSequence(self, buf):
-        print 'Could not handle', repr(buf)
+        print('Could not handle', repr(buf))
 
     def __str__(self):
         lines = []
--- twisted/conch/insults/insults.py (original)
+++ twisted/conch/insults/insults.py (refactored)
@@ -938,13 +938,13 @@
                             ('B', 'Down'),
                             ('C', 'Forward'),
                             ('D', 'Backward')):
-            exec ch + " = _makeSimple(ch, fName)"
+            exec(ch + " = _makeSimple(ch, fName)")
         del _makeSimple
 
         def h(self, proto, handler, buf):
             # XXX - Handle '?' to introduce ANSI-Compatible private modes.
             try:
-                modes = map(int, buf.split(';'))
+                modes = list(map(int, buf.split(';')))
             except ValueError:
                 handler.unhandledControlSequence('\x1b[' + buf + 'h')
             else:
@@ -953,7 +953,7 @@
         def l(self, proto, handler, buf):
             # XXX - Handle '?' to introduce ANSI-Compatible private modes.
             try:
-                modes = map(int, buf.split(';'))
+                modes = list(map(int, buf.split(';')))
             except ValueError:
                 handler.unhandledControlSequence('\x1b[' + buf + 'l')
             else:
--- twisted/conch/insults/window.py (original)
+++ twisted/conch/insults/window.py (refactored)
@@ -261,7 +261,7 @@
 
 
 class _Box(ContainerWidget):
-    TOP, CENTER, BOTTOM = range(3)
+    TOP, CENTER, BOTTOM = list(range(3))
 
     def __init__(self, gravity=CENTER):
         ContainerWidget.__init__(self)
@@ -359,7 +359,7 @@
         for n, ch in enumerate(self.children):
             boxes[n % len(boxes)].addChild(ch)
         h = HBox()
-        map(h.addChild, boxes)
+        list(map(h.addChild, boxes))
         h.render(width, height, terminal)
 
 
@@ -386,10 +386,12 @@
         if self.y >= height:
             self.y = height - 1
 
-    def __getitem__(self, (x, y)):
+    def __getitem__(self, xxx_todo_changeme):
+        (x, y) = xxx_todo_changeme
         return self.contents[(self._width * y) + x]
 
-    def __setitem__(self, (x, y), value):
+    def __setitem__(self, xxx_todo_changeme1, value):
+        (x, y) = xxx_todo_changeme1
         self.contents[(self._width * y) + x] = value
 
     def clear(self):
@@ -409,33 +411,35 @@
 def horizontalLine(terminal, y, left, right):
     terminal.selectCharacterSet(insults.CS_DRAWING, insults.G0)
     terminal.cursorPosition(left, y)
-    terminal.write(chr(0161) * (right - left))
+    terminal.write(chr(0o161) * (right - left))
     terminal.selectCharacterSet(insults.CS_US, insults.G0)
 
 def verticalLine(terminal, x, top, bottom):
     terminal.selectCharacterSet(insults.CS_DRAWING, insults.G0)
-    for n in xrange(top, bottom):
+    for n in range(top, bottom):
         terminal.cursorPosition(x, n)
-        terminal.write(chr(0170))
+        terminal.write(chr(0o170))
     terminal.selectCharacterSet(insults.CS_US, insults.G0)
 
 
-def rectangle(terminal, (top, left), (width, height)):
+def rectangle(terminal, xxx_todo_changeme2, xxx_todo_changeme3):
+    (top, left) = xxx_todo_changeme2
+    (width, height) = xxx_todo_changeme3
     terminal.selectCharacterSet(insults.CS_DRAWING, insults.G0)
 
     terminal.cursorPosition(top, left)
-    terminal.write(chr(0154))
-    terminal.write(chr(0161) * (width - 2))
-    terminal.write(chr(0153))
+    terminal.write(chr(0o154))
+    terminal.write(chr(0o161) * (width - 2))
+    terminal.write(chr(0o153))
     for n in range(height - 2):
         terminal.cursorPosition(left, top + n + 1)
-        terminal.write(chr(0170))
+        terminal.write(chr(0o170))
         terminal.cursorForward(width - 2)
-        terminal.write(chr(0170))
+        terminal.write(chr(0o170))
     terminal.cursorPosition(0, top + height - 1)
-    terminal.write(chr(0155))
-    terminal.write(chr(0161) * (width - 2))
-    terminal.write(chr(0152))
+    terminal.write(chr(0o155))
+    terminal.write(chr(0o161) * (width - 2))
+    terminal.write(chr(0o152))
 
     terminal.selectCharacterSet(insults.CS_US, insults.G0)
 
@@ -584,7 +588,7 @@
         raise YieldFocus()
 
 class TextOutputArea(TextOutput):
-    WRAP, TRUNCATE = range(2)
+    WRAP, TRUNCATE = list(range(2))
 
     def __init__(self, size=None, longLines=WRAP):
         TextOutput.__init__(self, size)
@@ -687,10 +691,10 @@
     def func_RIGHT_ARROW(self, modifier):
         self.bigger()
 
-    _left = u'\N{BLACK LEFT-POINTING TRIANGLE}'
-    _right = u'\N{BLACK RIGHT-POINTING TRIANGLE}'
-    _bar = u'\N{LIGHT SHADE}'
-    _slider = u'\N{DARK SHADE}'
+    _left = '\N{BLACK LEFT-POINTING TRIANGLE}'
+    _right = '\N{BLACK RIGHT-POINTING TRIANGLE}'
+    _bar = '\N{LIGHT SHADE}'
+    _slider = '\N{DARK SHADE}'
     def render(self, width, height, terminal):
         terminal.cursorPosition(0, 0)
         n = width - 3
@@ -710,15 +714,15 @@
     def func_DOWN_ARROW(self, modifier):
         self.bigger()
 
-    _up = u'\N{BLACK UP-POINTING TRIANGLE}'
-    _down = u'\N{BLACK DOWN-POINTING TRIANGLE}'
-    _bar = u'\N{LIGHT SHADE}'
-    _slider = u'\N{DARK SHADE}'
+    _up = '\N{BLACK UP-POINTING TRIANGLE}'
+    _down = '\N{BLACK DOWN-POINTING TRIANGLE}'
+    _bar = '\N{LIGHT SHADE}'
+    _slider = '\N{DARK SHADE}'
     def render(self, width, height, terminal):
         terminal.cursorPosition(0, 0)
         knob = int(self.percent * (height - 2))
         terminal.write(self._up.encode('utf-8'))
-        for i in xrange(1, height - 1):
+        for i in range(1, height - 1):
             terminal.cursorPosition(0, i)
             if i != (knob + 1):
                 terminal.write(self._bar.encode('utf-8'))
@@ -797,7 +801,7 @@
         self.onSelect = onSelect
         self.minVisible = minVisible
         if minVisible is not None:
-            self._width = max(map(len, self.sequence))
+            self._width = max(list(map(len, self.sequence)))
 
     def sizeHint(self):
         if self.minVisible is not None:
--- twisted/conch/openssh_compat/factory.py (original)
+++ twisted/conch/openssh_compat/factory.py (refactored)
@@ -35,7 +35,7 @@
                         os.path.join(self.dataRoot, filename))
                     t = common.getNS(k.blob())[0]
                     ks[t] = k
-                except Exception, e:
+                except Exception as e:
                     log.msg('bad public key file %s: %s' % (filename, e))
         return ks
 
@@ -50,7 +50,7 @@
                 fullPath = os.path.join(self.dataRoot, filename)
                 try:
                     key = keys.Key.fromFile(fullPath)
-                except IOError, e:
+                except IOError as e:
                     if e.errno == errno.EACCES:
                         # Not allowed, let's switch to root
                         key = runAsEffectiveUser(0, 0, keys.Key.fromFile, fullPath)
@@ -58,7 +58,7 @@
                         privateKeys[keyType] = key
                     else:
                         raise
-                except Exception, e:
+                except Exception as e:
                     log.msg('bad private key file %s: %s' % (filename, e))
                 else:
                     keyType = keys.objectType(key.keyObject)
--- twisted/conch/openssh_compat/primes.py (original)
+++ twisted/conch/openssh_compat/primes.py (refactored)
@@ -18,9 +18,9 @@
             continue
         tim, typ, tst, tri, size, gen, mod = l.split()
         size = int(size) + 1
-        gen = long(gen)
-        mod = long(mod, 16)
-        if not primes.has_key(size):
+        gen = int(gen)
+        mod = int(mod, 16)
+        if size not in primes:
             primes[size] = []
         primes[size].append((gen, mod))
     return primes
--- twisted/conch/scripts/cftp.py (original)
+++ twisted/conch/scripts/cftp.py (refactored)
@@ -58,8 +58,8 @@
     options = ClientOptions()
     try:
         options.parseOptions(args)
-    except usage.UsageError, u:
-        print 'ERROR: %s' % u
+    except usage.UsageError as u:
+        print('ERROR: %s' % u)
         sys.exit(1)
     if options['log']:
         realout = sys.stdout
@@ -107,7 +107,7 @@
         s = f.value.value
     else:
         s = str(f)
-    print s
+    print(s)
     #exitStatus = "conch: exiting with error %s" % f
     try:
         reactor.stop()
@@ -493,9 +493,7 @@
     def cmd_LN(self, rest):
         linkpath, rest = self._getFilename(rest)
         targetpath, rest = self._getFilename(rest)
-        linkpath, targetpath = map(
-                lambda x: os.path.join(self.currentDirectory, x),
-                (linkpath, targetpath))
+        linkpath, targetpath = [os.path.join(self.currentDirectory, x) for x in (linkpath, targetpath)]
         return self.client.makeLink(linkpath, targetpath).addCallback(_ignore)
 
     def cmd_LS(self, rest):
@@ -560,9 +558,7 @@
     def cmd_RENAME(self, rest):
         oldpath, rest = self._getFilename(rest)
         newpath, rest = self._getFilename(rest)
-        oldpath, newpath = map (
-                lambda x: os.path.join(self.currentDirectory, x),
-                (oldpath, newpath))
+        oldpath, newpath = [os.path.join(self.currentDirectory, x) for x in (oldpath, newpath)]
         return self.client.renameFile(oldpath, newpath).addCallback(_ignore)
 
     def cmd_EXIT(self, ignored):
@@ -612,7 +608,7 @@
 
     def cmd_EXEC(self, rest):
         shell = pwd.getpwnam(getpass.getuser())[6]
-        print repr(rest)
+        print(repr(rest))
         if rest:
             cmds = ['-c', rest]
             return utils.getProcessOutput(shell, cmds, errortoo=1)
@@ -667,11 +663,11 @@
     def _abbrevSize(self, size):
         # from http://mail.python.org/pipermail/python-list/1999-December/018395.html
         _abbrevs = [
-            (1<<50L, 'PB'),
-            (1<<40L, 'TB'), 
-            (1<<30L, 'GB'), 
-            (1<<20L, 'MB'), 
-            (1<<10L, 'kb'),
+            (1<<50, 'PB'),
+            (1<<40, 'TB'), 
+            (1<<30, 'GB'), 
+            (1<<20, 'MB'), 
+            (1<<10, 'kb'),
             (1, '')
             ]
 
@@ -726,12 +722,12 @@
                     elif c == '\\': # quoted character
                         del line[i]
                         if line[i] not in '\'"\\':
-                            raise IndexError, "bad quote: \\%s" % line[i]
+                            raise IndexError("bad quote: \\%s" % line[i])
                         ret.append(line[i])
                     else:
                         ret.append(line[i])
             except IndexError:
-                raise IndexError, "unterminated quote"
+                raise IndexError("unterminated quote")
         ret = line.split(None, 1)
         if len(ret) == 1:
             return ret[0], ''
--- twisted/conch/scripts/ckeygen.py (original)
+++ twisted/conch/scripts/ckeygen.py (refactored)
@@ -45,8 +45,8 @@
     options = GeneralOptions()
     try:
         options.parseOptions(sys.argv[1:])
-    except usage.UsageError, u:
-        print 'ERROR: %s' % u
+    except usage.UsageError as u:
+        print('ERROR: %s' % u)
         options.opt_help()
         sys.exit(1)
     log.discardLogs()
@@ -78,13 +78,13 @@
 
 def generateRSAkey(options):
     from Crypto.PublicKey import RSA
-    print 'Generating public/private rsa key pair.'
+    print('Generating public/private rsa key pair.')
     key = RSA.generate(int(options['bits']), randbytes.secureRandom)
     _saveKey(key, options)
 
 def generateDSAkey(options):
     from Crypto.PublicKey import DSA
-    print 'Generating public/private dsa key pair.'
+    print('Generating public/private dsa key pair.')
     key = DSA.generate(int(options['bits']), randbytes.secureRandom)
     _saveKey(key, options)
 
@@ -92,27 +92,27 @@
 def printFingerprint(options):
     if not options['filename']:
         filename = os.path.expanduser('~/.ssh/id_rsa')
-        options['filename'] = raw_input('Enter file in which the key is (%s): ' % filename)
+        options['filename'] = input('Enter file in which the key is (%s): ' % filename)
     if os.path.exists(options['filename']+'.pub'):
         options['filename'] += '.pub'
     try:
         key = keys.Key.fromFile(options['filename'])
         obj = key.keyObject
         string = key.blob()
-        print '%s %s %s' % (
+        print('%s %s %s' % (
             obj.size() + 1,
             key.fingerprint(),
-            os.path.basename(options['filename']))
+            os.path.basename(options['filename'])))
     except:
         sys.exit('bad key')
 
 def changePassPhrase(options):
     if not options['filename']:
         filename = os.path.expanduser('~/.ssh/id_rsa')
-        options['filename'] = raw_input('Enter file in which the key is (%s): ' % filename)
+        options['filename'] = input('Enter file in which the key is (%s): ' % filename)
     try:
         key = keys.getPrivateKeyObject(options['filename'])
-    except keys.BadKeyError, e:
+    except keys.BadKeyError as e:
         if e.args[0] != 'encrypted key with no passphrase':
             raise
         else:
@@ -125,36 +125,36 @@
             p2 = getpass.getpass('Enter same passphrase again: ')
             if p1 == p2:
                 break
-            print 'Passphrases do not match.  Try again.'
+            print('Passphrases do not match.  Try again.')
         options['newpass'] = p1
     open(options['filename'], 'w').write(
     keys.makePrivateKeyString(key, passphrase=options['newpass']))
-    print 'Your identification has been saved with the new passphrase.'
+    print('Your identification has been saved with the new passphrase.')
 
 def displayPublicKey(options):
     if not options['filename']:
         filename = os.path.expanduser('~/.ssh/id_rsa')
-        options['filename'] = raw_input('Enter file in which the key is (%s): ' % filename)
+        options['filename'] = input('Enter file in which the key is (%s): ' % filename)
     try:
         key = keys.getPrivateKeyObject(options['filename'])
-    except keys.BadKeyError, e:
+    except keys.BadKeyError as e:
         if e.args[0] != 'encrypted key with no passphrase':
             raise
         else:
             if not options['pass']:
                 options['pass'] = getpass.getpass('Enter passphrase: ')
             key = keys.getPrivateKeyObject(options['filename'], passphrase = options['pass'])
-    print keys.makePublicKeyString(key)
+    print(keys.makePublicKeyString(key))
 
 def _saveKey(key, options):
     if not options['filename']:
         kind = keys.objectType(key)
         kind = {'ssh-rsa':'rsa','ssh-dss':'dsa'}[kind]
         filename = os.path.expanduser('~/.ssh/id_%s'%kind)
-        options['filename'] = raw_input('Enter file in which to save the key (%s): '%filename).strip() or filename
+        options['filename'] = input('Enter file in which to save the key (%s): '%filename).strip() or filename
     if os.path.exists(options['filename']):
-        print '%s already exists.' % options['filename']
-        yn = raw_input('Overwrite (y/n)? ')
+        print('%s already exists.' % options['filename'])
+        yn = input('Overwrite (y/n)? ')
         if yn[0].lower() != 'y':
             sys.exit()
     if not options['pass']:
@@ -163,7 +163,7 @@
             p2 = getpass.getpass('Enter same passphrase again: ')
             if p1 == p2:
                 break
-            print 'Passphrases do not match.  Try again.'
+            print('Passphrases do not match.  Try again.')
         options['pass'] = p1
 
     keyObj = keys.Key(key)
@@ -176,10 +176,10 @@
     filepath.FilePath(options['filename'] + '.pub').setContent(
         keyObj.public().toString('openssh', comment))
 
-    print 'Your identification has been saved in %s' % options['filename']
-    print 'Your public key has been saved in %s.pub' % options['filename']
-    print 'The key fingerprint is:'
-    print keyObj.fingerprint()
+    print('Your identification has been saved in %s' % options['filename'])
+    print('Your public key has been saved in %s.pub' % options['filename'])
+    print('The key fingerprint is:')
+    print(keyObj.fingerprint())
 
 if __name__ == '__main__':
     run()
--- twisted/conch/scripts/conch.py (original)
+++ twisted/conch/scripts/conch.py (refactored)
@@ -100,8 +100,8 @@
     options = ClientOptions()
     try:
         options.parseOptions(args)
-    except usage.UsageError, u:
-        print 'ERROR: %s' % u
+    except usage.UsageError as u:
+        print('ERROR: %s' % u)
         options.opt_help()
         sys.exit(1)
     if options['log']:
@@ -137,7 +137,7 @@
         if (options['command'] and options['tty']) or not options['notty']:
             signal.signal(signal.SIGWINCH, signal.SIG_DFL)
     if sys.stdout.isatty() and not options['command']:
-        print 'Connection to %s closed.' % options['host']
+        print('Connection to %s closed.' % options['host'])
     sys.exit(exitStatus)
 
 def handleError():
@@ -209,7 +209,7 @@
         for i in range(3):
             try:
                 os.close(i)
-            except OSError, e:
+            except OSError as e:
                 import errno
                 if e.errno != errno.EBADF:
                     raise
@@ -303,7 +303,7 @@
         remoteHP, origHP = forwarding.unpackOpen_forwarded_tcpip(data)
         log.msg(self.remoteForwards)
         log.msg(remoteHP)
-        if self.remoteForwards.has_key(remoteHP[1]):
+        if remoteHP[1] in self.remoteForwards:
             connectHP = self.remoteForwards[remoteHP[1]]
             log.msg('connect forwarding %s' % (connectHP,))
             return SSHConnectForwardingChannel(connectHP,
@@ -405,7 +405,7 @@
                 return
             elif char == '#': # display connections
                 self.stdio.write('\r\nThe following connections are open:\r\n')
-                channels = self.conn.channels.keys()
+                channels = list(self.conn.channels.keys())
                 channels.sort()
                 for channelId in channels:
                     self.stdio.write('  #%i %s\r\n' % (channelId, str(self.conn.channels[channelId])))
@@ -448,7 +448,7 @@
             for i in range(3):
                 try:
                     os.close(i)
-                except OSError, e:
+                except OSError as e:
                     import errno
                     if e.errno != errno.EBADF:
                         raise
--- twisted/conch/scripts/tkconch.py (original)
+++ twisted/conch/scripts/tkconch.py (refactored)
@@ -8,9 +8,9 @@
 """ Implementation module for the `tkconch` command.
 """
 
-from __future__ import nested_scopes
-
-import Tkinter, tkFileDialog, tkFont, tkMessageBox, string
+
+
+import tkinter, tkFileDialog, tkFont, tkMessageBox, string
 from twisted.conch.ui import tkvt100
 from twisted.conch.ssh import transport, userauth, connection, common, keys
 from twisted.conch.ssh import session, forwarding, channel
@@ -20,66 +20,66 @@
 
 import os, sys, getpass, struct, base64, signal
 
-class TkConchMenu(Tkinter.Frame):
+class TkConchMenu(tkinter.Frame):
     def __init__(self, *args, **params):
         ## Standard heading: initialization
-        apply(Tkinter.Frame.__init__, (self,) + args, params)
+        tkinter.Frame.__init__(*(self,) + args, **params)
 
         self.master.title('TkConch')
-        self.localRemoteVar = Tkinter.StringVar()
+        self.localRemoteVar = tkinter.StringVar()
         self.localRemoteVar.set('local')
 
-        Tkinter.Label(self, anchor='w', justify='left', text='Hostname').grid(column=1, row=1, sticky='w')
-        self.host = Tkinter.Entry(self)
+        tkinter.Label(self, anchor='w', justify='left', text='Hostname').grid(column=1, row=1, sticky='w')
+        self.host = tkinter.Entry(self)
         self.host.grid(column=2, columnspan=2, row=1, sticky='nesw')
 
-        Tkinter.Label(self, anchor='w', justify='left', text='Port').grid(column=1, row=2, sticky='w')
-        self.port = Tkinter.Entry(self)
+        tkinter.Label(self, anchor='w', justify='left', text='Port').grid(column=1, row=2, sticky='w')
+        self.port = tkinter.Entry(self)
         self.port.grid(column=2, columnspan=2, row=2, sticky='nesw')
 
-        Tkinter.Label(self, anchor='w', justify='left', text='Username').grid(column=1, row=3, sticky='w')
-        self.user = Tkinter.Entry(self)
+        tkinter.Label(self, anchor='w', justify='left', text='Username').grid(column=1, row=3, sticky='w')
+        self.user = tkinter.Entry(self)
         self.user.grid(column=2, columnspan=2, row=3, sticky='nesw')
 
-        Tkinter.Label(self, anchor='w', justify='left', text='Command').grid(column=1, row=4, sticky='w')
-        self.command = Tkinter.Entry(self)
+        tkinter.Label(self, anchor='w', justify='left', text='Command').grid(column=1, row=4, sticky='w')
+        self.command = tkinter.Entry(self)
         self.command.grid(column=2, columnspan=2, row=4, sticky='nesw')
 
-        Tkinter.Label(self, anchor='w', justify='left', text='Identity').grid(column=1, row=5, sticky='w')
-        self.identity = Tkinter.Entry(self)
+        tkinter.Label(self, anchor='w', justify='left', text='Identity').grid(column=1, row=5, sticky='w')
+        self.identity = tkinter.Entry(self)
         self.identity.grid(column=2, row=5, sticky='nesw')
-        Tkinter.Button(self, command=self.getIdentityFile, text='Browse').grid(column=3, row=5, sticky='nesw')
-
-        Tkinter.Label(self, text='Port Forwarding').grid(column=1, row=6, sticky='w')
-        self.forwards = Tkinter.Listbox(self, height=0, width=0)
+        tkinter.Button(self, command=self.getIdentityFile, text='Browse').grid(column=3, row=5, sticky='nesw')
+
+        tkinter.Label(self, text='Port Forwarding').grid(column=1, row=6, sticky='w')
+        self.forwards = tkinter.Listbox(self, height=0, width=0)
         self.forwards.grid(column=2, columnspan=2, row=6, sticky='nesw')
-        Tkinter.Button(self, text='Add', command=self.addForward).grid(column=1, row=7)
-        Tkinter.Button(self, text='Remove', command=self.removeForward).grid(column=1, row=8)
-        self.forwardPort = Tkinter.Entry(self)
+        tkinter.Button(self, text='Add', command=self.addForward).grid(column=1, row=7)
+        tkinter.Button(self, text='Remove', command=self.removeForward).grid(column=1, row=8)
+        self.forwardPort = tkinter.Entry(self)
         self.forwardPort.grid(column=2, row=7, sticky='nesw')
-        Tkinter.Label(self, text='Port').grid(column=3, row=7, sticky='nesw')
-        self.forwardHost = Tkinter.Entry(self)
+        tkinter.Label(self, text='Port').grid(column=3, row=7, sticky='nesw')
+        self.forwardHost = tkinter.Entry(self)
         self.forwardHost.grid(column=2, row=8, sticky='nesw')
-        Tkinter.Label(self, text='Host').grid(column=3, row=8, sticky='nesw')
-        self.localForward = Tkinter.Radiobutton(self, text='Local', variable=self.localRemoteVar, value='local')
+        tkinter.Label(self, text='Host').grid(column=3, row=8, sticky='nesw')
+        self.localForward = tkinter.Radiobutton(self, text='Local', variable=self.localRemoteVar, value='local')
         self.localForward.grid(column=2, row=9)
-        self.remoteForward = Tkinter.Radiobutton(self, text='Remote', variable=self.localRemoteVar, value='remote')
+        self.remoteForward = tkinter.Radiobutton(self, text='Remote', variable=self.localRemoteVar, value='remote')
         self.remoteForward.grid(column=3, row=9)
 
-        Tkinter.Label(self, text='Advanced Options').grid(column=1, columnspan=3, row=10, sticky='nesw')
-
-        Tkinter.Label(self, anchor='w', justify='left', text='Cipher').grid(column=1, row=11, sticky='w')
-        self.cipher = Tkinter.Entry(self, name='cipher')
+        tkinter.Label(self, text='Advanced Options').grid(column=1, columnspan=3, row=10, sticky='nesw')
+
+        tkinter.Label(self, anchor='w', justify='left', text='Cipher').grid(column=1, row=11, sticky='w')
+        self.cipher = tkinter.Entry(self, name='cipher')
         self.cipher.grid(column=2, columnspan=2, row=11, sticky='nesw')
 
-        Tkinter.Label(self, anchor='w', justify='left', text='MAC').grid(column=1, row=12, sticky='w')
-        self.mac = Tkinter.Entry(self, name='mac')
+        tkinter.Label(self, anchor='w', justify='left', text='MAC').grid(column=1, row=12, sticky='w')
+        self.mac = tkinter.Entry(self, name='mac')
         self.mac.grid(column=2, columnspan=2, row=12, sticky='nesw')
 
-        Tkinter.Label(self, anchor='w', justify='left', text='Escape Char').grid(column=1, row=13, sticky='w')
-        self.escape = Tkinter.Entry(self, name='escape')
+        tkinter.Label(self, anchor='w', justify='left', text='Escape Char').grid(column=1, row=13, sticky='w')
+        self.escape = tkinter.Entry(self, name='escape')
         self.escape.grid(column=2, columnspan=2, row=13, sticky='nesw')
-        Tkinter.Button(self, text='Connect!', command=self.doConnect).grid(column=1, columnspan=3, row=14, sticky='nesw')
+        tkinter.Button(self, text='Connect!', command=self.doConnect).grid(column=1, columnspan=3, row=14, sticky='nesw')
 
         # Resize behavior(s)
         self.grid_rowconfigure(6, weight=1, minsize=64)
@@ -91,18 +91,18 @@
     def getIdentityFile(self):
         r = tkFileDialog.askopenfilename()
         if r:
-            self.identity.delete(0, Tkinter.END)
-            self.identity.insert(Tkinter.END, r)
+            self.identity.delete(0, tkinter.END)
+            self.identity.insert(tkinter.END, r)
 
     def addForward(self):
         port = self.forwardPort.get()
-        self.forwardPort.delete(0, Tkinter.END)
+        self.forwardPort.delete(0, tkinter.END)
         host = self.forwardHost.get()
-        self.forwardHost.delete(0, Tkinter.END)
+        self.forwardHost.delete(0, tkinter.END)
         if self.localRemoteVar.get() == 'local':
-            self.forwards.insert(Tkinter.END, 'L:%s:%s' % (port, host))
-        else:
-            self.forwards.insert(Tkinter.END, 'R:%s:%s' % (port, host))
+            self.forwards.insert(tkinter.END, 'L:%s:%s' % (port, host))
+        else:
+            self.forwards.insert(tkinter.END, 'R:%s:%s' % (port, host))
 
     def removeForward(self):
         cur = self.forwards.curselection()
@@ -146,7 +146,7 @@
         if self.identity.get():
             options.identitys.append(self.identity.get())
 
-        for line in self.forwards.get(0,Tkinter.END):
+        for line in self.forwards.get(0,tkinter.END):
             if line[0]=='L':
                 options.opt_localforward(line[2:])
             else:
@@ -291,30 +291,30 @@
                 args[i:i+2] = [] # suck on it scp
         except ValueError:
             pass
-    root = Tkinter.Tk()
+    root = tkinter.Tk()
     root.withdraw()
-    top = Tkinter.Toplevel()
+    top = tkinter.Toplevel()
     menu = TkConchMenu(top)
-    menu.pack(side=Tkinter.TOP, fill=Tkinter.BOTH, expand=1)
+    menu.pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)
     options = GeneralOptions()
     try:
         options.parseOptions(args)
-    except usage.UsageError, u:
-        print 'ERROR: %s' % u
+    except usage.UsageError as u:
+        print('ERROR: %s' % u)
         options.opt_help()
         sys.exit(1)
-    for k,v in options.items():
+    for k,v in list(options.items()):
         if v and hasattr(menu, k):
-            getattr(menu,k).insert(Tkinter.END, v)
+            getattr(menu,k).insert(tkinter.END, v)
     for (p, (rh, rp)) in options.localForwards:
-        menu.forwards.insert(Tkinter.END, 'L:%s:%s:%s' % (p, rh, rp))
+        menu.forwards.insert(tkinter.END, 'L:%s:%s:%s' % (p, rh, rp))
     options.localForwards = []
     for (p, (rh, rp)) in options.remoteForwards:
-        menu.forwards.insert(Tkinter.END, 'R:%s:%s:%s' % (p, rh, rp))
+        menu.forwards.insert(tkinter.END, 'R:%s:%s:%s' % (p, rh, rp))
     options.remoteForwards = []
     frame = tkvt100.VT100Frame(root, callback=None)
     root.geometry('%dx%d'%(tkvt100.fontWidth*frame.width+3, tkvt100.fontHeight*frame.height+3))
-    frame.pack(side = Tkinter.TOP)
+    frame.pack(side = tkinter.TOP)
     tksupport.install(root)
     root.withdraw()
     if (options['host'] and options['user']) or '@' in options['host']:
@@ -440,7 +440,7 @@
             return None
         try:
             return defer.succeed(keys.getPrivateKeyObject(file))
-        except keys.BadKeyError, e:
+        except keys.BadKeyError as e:
             if e.args[0] == 'encrypted key with no password':
                 prompt = "Enter passphrase for key '%s': " % \
                        self.usedFiles[-1]
@@ -542,7 +542,7 @@
 
     def dataReceived(self, data):
         if options['ansilog']:
-            print repr(data)
+            print(repr(data))
         frame.write(data)
 
     def extReceived(self, t, data):
--- twisted/conch/ssh/agent.py (original)
+++ twisted/conch/ssh/agent.py (refactored)
@@ -175,7 +175,7 @@
         resp = []
 
         resp.append(struct.pack('!L', numKeys))
-        for key, comment in self.factory.keys.itervalues():
+        for key, comment in self.factory.keys.values():
             resp.append(NS(key.blob())) # yes, wrapped in an NS
             resp.append(NS(comment))
         self.sendResponse(AGENT_IDENTITIES_ANSWER, ''.join(resp))
@@ -282,7 +282,7 @@
 AGENTC_REMOVE_ALL_IDENTITIES    = 19
 
 messages = {}
-for name, value in locals().copy().items():
+for name, value in list(locals().copy().items()):
     if name[:7] == 'AGENTC_':
         messages[value] = name[7:] # doesn't handle doubles
 
--- twisted/conch/ssh/asn1.py (original)
+++ twisted/conch/ssh/asn1.py (refactored)
@@ -43,7 +43,7 @@
         if type(part) in (type(()), type([])):
             partData = pack(part)
             partType = SEQUENCE|0x20
-        elif type(part) in (type(1), type(1L)):
+        elif type(part) in (type(1), type(1)):
             partData = number.long_to_bytes(part)
             if ord(partData[0])&(0x80):
                 partData = '\x00' + partData
--- twisted/conch/ssh/channel.py (original)
+++ twisted/conch/ssh/channel.py (refactored)
@@ -196,7 +196,7 @@
             top = self.remoteWindowLeft
         rmp = self.remoteMaxPacket
         write = self.conn.sendData
-        r = range(0, top, rmp)
+        r = list(range(0, top, rmp))
         for offset in r:
             write(self, data[offset: offset+rmp])
         self.remoteWindowLeft -= top
--- twisted/conch/ssh/common.py (original)
+++ twisted/conch/ssh/common.py (refactored)
@@ -100,7 +100,7 @@
     c = 0
     for i in range(count):
         length = struct.unpack('!L', data[c:c+4])[0]
-        mp.append(long(gmpy.mpz(data[c + 4:c + 4 + length][::-1] + '\x00', 256)))
+        mp.append(int(gmpy.mpz(data[c + 4:c + 4 + length][::-1] + '\x00', 256)))
         c += length + 4
     return tuple(mp) + (data[c:],)
 
--- twisted/conch/ssh/connection.py (original)
+++ twisted/conch/ssh/connection.py (refactored)
@@ -56,7 +56,7 @@
             self.transport.avatar.conn = self
 
     def serviceStopped(self):
-        map(self.channelClosed, self.channels.values())
+        list(map(self.channelClosed, list(self.channels.values())))
 
     # packet methods
     def ssh_GLOBAL_REQUEST(self, packet):
@@ -127,7 +127,7 @@
                     channel.localWindowSize,
                     channel.localMaxPacket)+channel.specificData)
             log.callWithLogger(channel, channel.channelOpen, packet)
-        except Exception, e:
+        except Exception as e:
             log.msg('channel open failed')
             log.err(e)
             if isinstance(e, error.ConchError):
@@ -602,7 +602,7 @@
 EXTENDED_DATA_STDERR = 1
 
 messages = {}
-for name, value in locals().copy().items():
+for name, value in list(locals().copy().items()):
     if name[:4] == 'MSG_':
         messages[value] = name # doesn't handle doubles
 
--- twisted/conch/ssh/factory.py (original)
+++ twisted/conch/ssh/factory.py (refactored)
@@ -40,7 +40,7 @@
             log.msg('INSECURE: unable to disable core dumps.')
         if not hasattr(self,'publicKeys'):
             self.publicKeys = self.getPublicKeys()
-        for keyType, value in self.publicKeys.items():
+        for keyType, value in list(self.publicKeys.items()):
             if isinstance(value, str):
                 warnings.warn("Returning a mapping from strings to "
                         "strings from getPublicKeys()/publicKeys (in %s) "
@@ -51,7 +51,7 @@
                 self.publicKeys[keyType] = keys.Key.fromString(value)
         if not hasattr(self,'privateKeys'):
             self.privateKeys = self.getPrivateKeys()
-        for keyType, value in self.privateKeys.items():
+        for keyType, value in list(self.privateKeys.items()):
             if not isinstance(value, keys.Key):
                 warnings.warn("Returning a mapping from strings to "
                         "PyCrypto key objects from "
@@ -68,7 +68,7 @@
 
     def buildProtocol(self, addr):
         t = protocol.Factory.buildProtocol(self, addr)
-        t.supportedPublicKeys = self.privateKeys.keys()
+        t.supportedPublicKeys = list(self.privateKeys.keys())
         if not self.primes:
             log.msg('disabling diffie-hellman-group-exchange because we '
                     'cannot find moduli file')
@@ -114,7 +114,7 @@
         @type bits: C{int}
         @rtype:     C{tuple}
         """
-        primesKeys = self.primes.keys()
+        primesKeys = list(self.primes.keys())
         primesKeys.sort(lambda x, y: cmp(abs(x - bits), abs(y - bits)))
         realBits = primesKeys[0]
         return random.choice(self.primes[realBits])
--- twisted/conch/ssh/filetransfer.py (original)
+++ twisted/conch/ssh/filetransfer.py (refactored)
@@ -9,7 +9,7 @@
 from twisted.internet import defer, protocol
 from twisted.python import failure, log
 
-from common import NS, getNS
+from .common import NS, getNS
 from twisted.conch.interfaces import ISFTPServer, ISFTPFile
 
 from zope import interface
@@ -82,7 +82,7 @@
         if flags & FILEXFER_ATTR_EXTENDED == FILEXFER_ATTR_EXTENDED:
             extended_count ,= struct.unpack('!L', data[:4])
             data = data[4:]
-            for i in xrange(extended_count):
+            for i in range(extended_count):
                 extended_type, data = getNS(data)
                 extended_data, data = getNS(data)
                 attrs['ext_%s' % extended_type] = extended_data
@@ -134,7 +134,7 @@
             ext[ext_name] = ext_data
         our_ext = self.client.gotVersion(version, ext)
         our_ext_data = ""
-        for (k,v) in our_ext.items():
+        for (k,v) in list(our_ext.items()):
             our_ext_data += NS(k) + NS(v)
         self.sendPacket(FXP_VERSION, struct.pack('!L', self.version) + \
                                      our_ext_data)
@@ -154,7 +154,7 @@
     def _cbOpenFile(self, fileObj, requestId):
         fileId = str(hash(fileObj))
         if fileId in self.openFiles:
-            raise KeyError, 'id already open'
+            raise KeyError('id already open')
         self.openFiles[fileId] = fileObj
         self.sendPacket(FXP_HANDLE, requestId + NS(fileId))
 
@@ -268,7 +268,7 @@
     def _cbOpenDirectory(self, dirObj, requestId):
         handle = str(hash(dirObj))
         if handle in self.openDirs:
-            raise KeyError, "already opened this directory"
+            raise KeyError("already opened this directory")
         self.openDirs[handle] = [dirObj, iter(dirObj)]
         self.sendPacket(FXP_HANDLE, requestId + NS(handle))
 
@@ -288,7 +288,7 @@
     def _scanDirectory(self, dirIter, f):
         while len(f) < 250:
             try:
-                info = dirIter.next()
+                info = next(dirIter)
             except StopIteration:
                 if not f:
                     raise EOFError
@@ -455,10 +455,10 @@
         """
         Clean all opened files and directories.
         """
-        for fileObj in self.openFiles.values():
+        for fileObj in list(self.openFiles.values()):
             fileObj.close()
         self.openFiles = {}
-        for (dirObj, dirIter) in self.openDirs.values():
+        for (dirObj, dirIter) in list(self.openDirs.values()):
             dirObj.close()
         self.openDirs = {}
 
@@ -479,7 +479,7 @@
 
     def connectionMade(self):
         data = struct.pack('!L', max(self.versions))
-        for k,v in self.extData.itervalues():
+        for k,v in self.extData.values():
             data += NS(k) + NS(v)
         self.sendPacket(FXP_INIT, data)
 
@@ -806,7 +806,7 @@
     def __iter__(self):
         return self
 
-    def next(self):
+    def __next__(self):
         if self.filesCache:
             return self.filesCache.pop(0)
         d = self.read()
@@ -870,7 +870,7 @@
 FILEXFER_ATTR_OWNERGROUP  = FILEXFER_ATTR_UIDGID
 FILEXFER_ATTR_PERMISSIONS = 0x00000004
 FILEXFER_ATTR_ACMODTIME   = 0x00000008
-FILEXFER_ATTR_EXTENDED    = 0x80000000L
+FILEXFER_ATTR_EXTENDED    = 0x80000000
 
 FILEXFER_TYPE_REGULAR        = 1
 FILEXFER_TYPE_DIRECTORY      = 2
@@ -906,7 +906,7 @@
 
 # initialize FileTransferBase.packetTypes:
 g = globals()
-for name in g.keys():
+for name in list(g.keys()):
     if name.startswith('FXP_'):
         value = g[name]
         FileTransferBase.packetTypes[value] = name[4:]
--- twisted/conch/ssh/forwarding.py (original)
+++ twisted/conch/ssh/forwarding.py (refactored)
@@ -130,9 +130,11 @@
             self.channel = None
 
 
-def packOpen_direct_tcpip((connHost, connPort), (origHost, origPort)):
+def packOpen_direct_tcpip(xxx_todo_changeme, xxx_todo_changeme1):
     """Pack the data suitable for sending in a CHANNEL_OPEN packet.
     """
+    (connHost, connPort) = xxx_todo_changeme
+    (origHost, origPort) = xxx_todo_changeme1
     conn = common.NS(connHost) + struct.pack('>L', connPort)
     orig = common.NS(origHost) + struct.pack('>L', origPort)
     return conn + orig
@@ -150,7 +152,8 @@
 
 unpackOpen_forwarded_tcpip = unpackOpen_direct_tcpip
     
-def packGlobal_tcpip_forward((host, port)):
+def packGlobal_tcpip_forward(xxx_todo_changeme2):
+    (host, port) = xxx_todo_changeme2
     return common.NS(host) + struct.pack('>L', port)
 
 def unpackGlobal_tcpip_forward(data):
--- twisted/conch/ssh/keys.py (original)
+++ twisted/conch/ssh/keys.py (refactored)
@@ -78,7 +78,7 @@
         method = getattr(Class, '_fromString_%s' % type.upper(), None)
         if method is None:
             raise BadKeyError('no _fromString method for %s' % type)
-        if method.func_code.co_argcount == 2: # no passphrase
+        if method.__code__.co_argcount == 2: # no passphrase
             if passphrase:
                 raise BadKeyError('key not encrypted')
             return method(data)
@@ -216,8 +216,8 @@
             keyData = base64.decodestring(''.join(lines[1:-1]))
         try:
             decodedKey = asn1.parse(keyData)
-        except Exception, e:
-            raise BadKeyError, 'something wrong with decode'
+        except Exception as e:
+            raise BadKeyError('something wrong with decode')
         if kind == 'RSA':
             if len(decodedKey) == 2: # alternate RSA key
                 decodedKey = decodedKey[0]
@@ -393,7 +393,7 @@
         lines = ['<%s %s (%s bits)' % (self.type(),
             self.isPublic() and 'Public Key' or 'Private Key',
             self.keyObject.size())]
-        for k, v in self.data().items():
+        for k, v in list(self.data().items()):
             lines.append('attr %s:' % k)
             by = common.MP(v)[4:]
             while by:
@@ -561,7 +561,7 @@
         method = getattr(self, '_toString_%s' % type.upper(), None)
         if method is None:
             raise BadKeyError('unknown type: %s' % type)
-        if method.func_code.co_argcount == 2:
+        if method.__code__.co_argcount == 2:
             return method(extra)
         else:
             return method()
@@ -708,8 +708,8 @@
             digest = pkcs1Digest(data, self.keyObject.size() / 8)
         elif self.type() == 'DSA':
             signature = common.getNS(signature)[0]
-            numbers = [Util.number.bytes_to_long(n) for n in signature[:20],
-                    signature[20:]]
+            numbers = [Util.number.bytes_to_long(n) for n in (signature[:20],
+                    signature[20:])]
             digest = sha1(data).digest()
         return self.keyObject.verify(digest, numbers)
 
--- twisted/conch/ssh/session.py (original)
+++ twisted/conch/ssh/session.py (refactored)
@@ -229,11 +229,12 @@
     modes = [(ord(modes[i]), struct.unpack('>L', modes[i+1: i+5])[0]) for i in range(0, len(modes)-1, 5)]
     return term, winSize, modes
 
-def packRequest_pty_req(term, (rows, cols, xpixel, ypixel), modes):
+def packRequest_pty_req(term, xxx_todo_changeme, modes):
     """Pack a pty-req request so that it is suitable for sending.
 
     NOTE: modes must be packed before being sent here.
     """
+    (rows, cols, xpixel, ypixel) = xxx_todo_changeme
     termPacked = common.NS(term)
     winSizePacked = struct.pack('>4L', cols, rows, xpixel, ypixel)
     modesPacked = common.NS(modes) # depend on the client packing modes
@@ -247,9 +248,10 @@
     cols, rows, xpixel, ypixel = struct.unpack('>4L', data)
     return rows, cols, xpixel, ypixel
 
-def packRequest_window_change((rows, cols, xpixel, ypixel)):
+def packRequest_window_change(xxx_todo_changeme1):
     """Pack a window-change request so that it is suitable for sending.
     """
+    (rows, cols, xpixel, ypixel) = xxx_todo_changeme1
     return struct.pack('>4L', cols, rows, xpixel, ypixel)
 
-import connection
+from . import connection
--- twisted/conch/ssh/transport.py (original)
+++ twisted/conch/ssh/transport.py (refactored)
@@ -393,7 +393,7 @@
             self.sendDisconnect(DISCONNECT_KEY_EXCHANGE_FAILED,
                                 "couldn't match all kex parts")
             return
-        if None in self.nextEncryptions.__dict__.values():
+        if None in list(self.nextEncryptions.__dict__.values()):
             self.sendDisconnect(DISCONNECT_KEY_EXCHANGE_FAILED,
                                 "couldn't match all kex parts")
             return
@@ -990,8 +990,7 @@
         pubKey, packet = getNS(packet)
         f, packet = getMP(packet)
         signature, packet = getNS(packet)
-        fingerprint = ':'.join(map(lambda c: '%02x'%ord(c),
-            md5(pubKey).digest()))
+        fingerprint = ':'.join(['%02x'%ord(c) for c in md5(pubKey).digest()])
         d = self.verifyHostKey(pubKey, fingerprint)
         d.addCallback(self._continueGEX_REPLY, pubKey, f, signature)
         d.addErrback(
@@ -1353,12 +1352,12 @@
 
 
 # Diffie-Hellman primes from Oakley Group 2 [RFC 2409]
-DH_PRIME = long('17976931348623159077083915679378745319786029604875601170644'
+DH_PRIME = int('17976931348623159077083915679378745319786029604875601170644'
 '442368419718021615851936894783379586492554150218056548598050364644054819923'
 '910005079287700335581663922955313623907650873575991482257486257500742530207'
 '744771258955095793777842444242661733472762929938766870920560605027081084290'
 '7692932019128194467627007L')
-DH_GENERATOR = 2L
+DH_GENERATOR = 2
 
 
 
@@ -1399,6 +1398,6 @@
 
 
 messages = {}
-for name, value in globals().items():
+for name, value in list(globals().items()):
     if name.startswith('MSG_'):
         messages[value] = name
--- twisted/conch/ssh/userauth.py (original)
+++ twisted/conch/ssh/userauth.py (refactored)
@@ -15,7 +15,7 @@
 from twisted.cred import credentials
 from twisted.internet import defer, reactor
 from twisted.python import failure, log
-from common import NS, getNS, MP
+from .common import NS, getNS, MP
 import keys, transport, service
 
 class SSHUserAuthServer(service.SSHService):
@@ -94,7 +94,8 @@
         d.addErrback(self._ebBadAuth)
         return d
 
-    def _cbFinishedAuth(self, (interface, avatar, logout)):
+    def _cbFinishedAuth(self, xxx_todo_changeme):
+        (interface, avatar, logout) = xxx_todo_changeme
         self.transport.avatar = avatar
         self.transport.logoutFunction = logout
         service = self.transport.factory.getService(self.transport,
@@ -429,7 +430,7 @@
 MSG_USERAUTH_PK_OK            = 60
 
 messages = {}
-import userauth
+from . import userauth
 for v in dir(userauth):
     if v[:4]=='MSG_':
         messages[getattr(userauth,v)] = v # doesn't handle doubles
--- twisted/conch/test/keydata.py (original)
+++ twisted/conch/test/keydata.py (refactored)
@@ -6,32 +6,32 @@
 Data used by test_keys as well as others.
 """
 RSAData = {
-        'n':long('1062486685755247411169438309495398947372127791189432809481'
+        'n':int('1062486685755247411169438309495398947372127791189432809481'
             '382072971106157632182084539383569281493520117634129557550415277'
             '516685881326038852354459895734875625093273594925884531272867425'
             '864910490065695876046999646807138717162833156501L'),
-        'e':35L,
-        'd':long('6678487739032983727350755088256793383481946116047863373882'
+        'e':35,
+        'd':int('6678487739032983727350755088256793383481946116047863373882'
             '973030104095847973715959961839578340816412167985957218887914482'
             '713602371850869127033494910375212470664166001439410214474266799'
             '85974425203903884190893469297150446322896587555L'),
-        'q':long('3395694744258061291019136154000709371890447462086362702627'
+        'q':int('3395694744258061291019136154000709371890447462086362702627'
             '9704149412726577280741108645721676968699696898960891593323L'),
-        'p':long('3128922844292337321766351031842562691837301298995834258844'
+        'p':int('3128922844292337321766351031842562691837301298995834258844'
             '4720539204069737532863831050930719431498338835415515173887L')}
 
 DSAData = {
-        'y':long('2300663509295750360093768159135720439490120577534296730713'
+        'y':int('2300663509295750360093768159135720439490120577534296730713'
             '348508834878775464483169644934425336771277908527130096489120714'
             '610188630979820723924744291603865L'),
-        'g':long('4451569990409370769930903934104221766858515498655655091803'
+        'g':int('4451569990409370769930903934104221766858515498655655091803'
             '866645719060300558655677517139568505649468378587802312867198352'
             '1161998270001677664063945776405L'),
-        'p':long('7067311773048598659694590252855127633397024017439939353776'
+        'p':int('7067311773048598659694590252855127633397024017439939353776'
             '608320410518694001356789646664502838652272205440894335303988504'
             '978724817717069039110940675621677L'),
-        'q':1184501645189849666738820838619601267690550087703L,
-        'x':863951293559205482820041244219051653999559962819L}
+        'q':1184501645189849666738820838619601267690550087703,
+        'x':863951293559205482820041244219051653999559962819}
 
 publicRSA_openssh = ("ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAGEArzJx8OYOnJmzf4tfBE"
 "vLi8DVPrJ3/c9k2I/Az64fxjHf9imyRJbixtQhlH9lfNjUIx+4LmrJH5QNRsFporcHDKOTwTTYL"
--- twisted/conch/test/test_channel.py (original)
+++ twisted/conch/test/test_channel.py (refactored)
@@ -249,7 +249,7 @@
         Test that writeSequence is equivalent to write(''.join(sequece)).
         """
         self.channel.addWindowBytes(20)
-        self.channel.writeSequence(map(str, range(10)))
+        self.channel.writeSequence(list(map(str, list(range(10)))))
         self.assertEquals(self.conn.data[self.channel], ['0123456789'])
 
     def test_loseConnection(self):
--- twisted/conch/test/test_checkers.py (original)
+++ twisted/conch/test/test_checkers.py (refactored)
@@ -93,11 +93,11 @@
         keyFile.setContent(self.content)
         # Fake permission error by changing the mode
         keyFile.chmod(0000)
-        self.addCleanup(keyFile.chmod, 0777)
+        self.addCleanup(keyFile.chmod, 0o777)
         # And restore the right mode when seteuid is called
         savedSeteuid = os.seteuid
         def seteuid(euid):
-            keyFile.chmod(0777)
+            keyFile.chmod(0o777)
             return savedSeteuid(euid)
         self.patch(os, "seteuid", seteuid)
         user = UsernamePassword("user", "password")
--- twisted/conch/test/test_ckeygen.py (original)
+++ twisted/conch/test/test_ckeygen.py (refactored)
@@ -6,7 +6,7 @@
 """
 
 import sys
-from StringIO import StringIO
+from io import StringIO
 
 from twisted.python.filepath import FilePath
 from twisted.trial.unittest import TestCase
--- twisted/conch/test/test_conch.py (original)
+++ twisted/conch/test/test_conch.py (refactored)
@@ -270,7 +270,7 @@
             remoteHP, origHP = forwarding.unpackOpen_forwarded_tcpip(data)
             log.msg(self.remoteForwards)
             log.msg(remoteHP)
-            if self.remoteForwards.has_key(remoteHP[1]):
+            if remoteHP[1] in self.remoteForwards:
                 connectHP = self.remoteForwards[remoteHP[1]]
                 log.msg('connect forwarding %s' % (connectHP,))
                 return forwarding.SSHConnectForwardingChannel(connectHP,
--- twisted/conch/test/test_filetransfer.py (original)
+++ twisted/conch/test/test_filetransfer.py (refactored)
@@ -98,7 +98,7 @@
         f = file(os.path.join(self.testDir, 'testfile1'),'w')
         f.write('a'*10+'b'*10)
         f.write(file('/dev/urandom').read(1024*64)) # random data
-        os.chmod(os.path.join(self.testDir, 'testfile1'), 0644)
+        os.chmod(os.path.join(self.testDir, 'testfile1'), 0o644)
         file(os.path.join(self.testDir, 'testRemoveFile'), 'w').write('a')
         file(os.path.join(self.testDir, 'testRenameFile'), 'w').write('a')
         file(os.path.join(self.testDir, '.testHiddenFile'), 'w').write('a')
@@ -390,7 +390,7 @@
             def append(f):
                 files.append(f)
                 return openDir
-            d = defer.maybeDeferred(openDir.next)
+            d = defer.maybeDeferred(openDir.__next__)
             self._emptyBuffers()
             d.addCallback(append)
             d.addCallback(_getFiles)
@@ -670,8 +670,8 @@
             for line in excerpt.splitlines():
                 m = re.match('^\s*#define SSH_([A-Z_]+)\s+([0-9x]*)\s*$', line)
                 if m:
-                    constants[m.group(1)] = long(m.group(2), 0)
+                    constants[m.group(1)] = int(m.group(2), 0)
         self.assertTrue(
             len(constants) > 0, "No constants found (the test must be buggy).")
-        for k, v in constants.items():
+        for k, v in list(constants.items()):
             self.assertEqual(v, getattr(filetransfer, k))
--- twisted/conch/test/test_insults.py (original)
+++ twisted/conch/test/test_insults.py (refactored)
@@ -90,7 +90,7 @@
     protocolFactory = None
 
     for word, n in [('Pairs', 2), ('Triples', 3), ('Quads', 4), ('Quints', 5), ('Sexes', 6)]:
-        exec _byteGroupingTestTemplate % {'groupName': word, 'bytesPer': n}
+        exec(_byteGroupingTestTemplate % {'groupName': word, 'bytesPer': n})
     del word, n
 
     def verifyResults(self, transport, proto, parser):
--- twisted/conch/test/test_keys.py (original)
+++ twisted/conch/test/test_keys.py (refactored)
@@ -168,7 +168,7 @@
         were generated in _testKey; just check that they were created
         correctly.
         """
-        for k in data.keys():
+        for k in list(data.keys()):
             self.assertEquals(getattr(privObj, k), data[k])
         for k in pubObj.keydata:
             if hasattr(pubObj, k): # public key objects don't have all the
@@ -458,8 +458,8 @@
         skip = "cannot run w/o PyCrypto"
 
     def setUp(self):
-        self.rsaObj = Crypto.PublicKey.RSA.construct((1L, 2L, 3L, 4L, 5L))
-        self.dsaObj = Crypto.PublicKey.DSA.construct((1L, 2L, 3L, 4L, 5L))
+        self.rsaObj = Crypto.PublicKey.RSA.construct((1, 2, 3, 4, 5))
+        self.dsaObj = Crypto.PublicKey.DSA.construct((1, 2, 3, 4, 5))
         self.rsaSignature = ('\x00\x00\x00\x07ssh-rsa\x00'
             '\x00\x00`N\xac\xb4@qK\xa0(\xc3\xf2h \xd3\xdd\xee6Np\x9d_'
             '\xb0>\xe3\x0c(L\x9d{\txUd|!\xf6m\x9c\xd3\x93\x842\x7fU'
@@ -523,14 +523,14 @@
         publicKey = keys.Key.fromString(public)
         self.assertTrue(publicKey.isPublic())
         self.assertEquals(publicKey.type(), type)
-        for k, v in publicKey.data().items():
+        for k, v in list(publicKey.data().items()):
             self.assertEquals(data[k], v)
 
     def _testPrivateFromString(self, private, type, data):
         privateKey = keys.Key.fromString(private)
         self.assertFalse(privateKey.isPublic())
         self.assertEquals(privateKey.type(), type)
-        for k, v in data.items():
+        for k, v in list(data.items()):
             self.assertEquals(privateKey.data()[k], v)
 
     def test_fromOpenSSH(self):
@@ -604,7 +604,7 @@
         """
         Test that the PublicKey object is initialized correctly.
         """
-        obj = Crypto.PublicKey.RSA.construct((1L, 2L))
+        obj = Crypto.PublicKey.RSA.construct((1, 2))
         key = keys.Key(obj)
         self.assertEquals(key.keyObject, obj)
 
@@ -614,7 +614,7 @@
         """
         rsa1 = keys.Key(self.rsaObj)
         rsa2 = keys.Key(self.rsaObj)
-        rsa3 = keys.Key(Crypto.PublicKey.RSA.construct((1L, 2L)))
+        rsa3 = keys.Key(Crypto.PublicKey.RSA.construct((1, 2)))
         dsa = keys.Key(self.dsaObj)
         self.assertTrue(rsa1 == rsa2)
         self.assertFalse(rsa1 == rsa3)
@@ -628,7 +628,7 @@
         """
         rsa1 = keys.Key(self.rsaObj)
         rsa2 = keys.Key(self.rsaObj)
-        rsa3 = keys.Key(Crypto.PublicKey.RSA.construct((1L, 2L)))
+        rsa3 = keys.Key(Crypto.PublicKey.RSA.construct((1, 2)))
         dsa = keys.Key(self.dsaObj)
         self.assertFalse(rsa1 != rsa2)
         self.assertTrue(rsa1 != rsa3)
@@ -660,9 +660,9 @@
         dsaKey = keys.Key.fromString(dsaBlob)
         badBlob = common.NS('ssh-bad')
         self.assertTrue(rsaKey.isPublic())
-        self.assertEquals(rsaKey.data(), {'e':2L, 'n':3L})
+        self.assertEquals(rsaKey.data(), {'e':2, 'n':3})
         self.assertTrue(dsaKey.isPublic())
-        self.assertEquals(dsaKey.data(), {'p':2L, 'q':3L, 'g':4L, 'y':5L})
+        self.assertEquals(dsaKey.data(), {'p':2, 'q':3, 'g':4, 'y':5})
         self.assertRaises(keys.BadKeyError,
                 keys.Key.fromString, badBlob)
 
@@ -680,9 +680,9 @@
         badBlob = common.NS('ssh-bad')
         self.assertFalse(rsaKey.isPublic())
         self.assertEqual(
-            rsaKey.data(), {'n':2L, 'e':3L, 'd':4L, 'u':5L, 'p':6L, 'q':7L})
+            rsaKey.data(), {'n':2, 'e':3, 'd':4, 'u':5, 'p':6, 'q':7})
         self.assertFalse(dsaKey.isPublic())
-        self.assertEqual(dsaKey.data(), {'p':2L, 'q':3L, 'g':4L, 'y':5L, 'x':6L})
+        self.assertEqual(dsaKey.data(), {'p':2, 'q':3, 'g':4, 'y':5, 'x':6})
         self.assertRaises(
             keys.BadKeyError, keys.Key._fromString_PRIVATE_BLOB, badBlob)
 
--- twisted/conch/test/test_openssh_compat.py (original)
+++ twisted/conch/test/test_openssh_compat.py (refactored)
@@ -61,7 +61,7 @@
         """
         keys = self.factory.getPublicKeys()
         self.assertEquals(len(keys), 1)
-        keyTypes = keys.keys()
+        keyTypes = list(keys.keys())
         self.assertEqual(keyTypes, ['ssh-rsa'])
 
 
@@ -72,7 +72,7 @@
         """
         keys = self.factory.getPrivateKeys()
         self.assertEquals(len(keys), 2)
-        keyTypes = keys.keys()
+        keyTypes = list(keys.keys())
         self.assertEqual(set(keyTypes), set(['ssh-rsa', 'ssh-dss']))
         self.assertEquals(self.mockos.seteuidCalls, [])
         self.assertEquals(self.mockos.setegidCalls, [])
@@ -86,16 +86,16 @@
         keyFile = self.keysDir.child("ssh_host_two_key")
         # Fake permission error by changing the mode
         keyFile.chmod(0000)
-        self.addCleanup(keyFile.chmod, 0777)
+        self.addCleanup(keyFile.chmod, 0o777)
         # And restore the right mode when seteuid is called
         savedSeteuid = os.seteuid
         def seteuid(euid):
-            keyFile.chmod(0777)
+            keyFile.chmod(0o777)
             return savedSeteuid(euid)
         self.patch(os, "seteuid", seteuid)
         keys = self.factory.getPrivateKeys()
         self.assertEquals(len(keys), 2)
-        keyTypes = keys.keys()
+        keyTypes = list(keys.keys())
         self.assertEqual(set(keyTypes), set(['ssh-rsa', 'ssh-dss']))
         self.assertEquals(self.mockos.seteuidCalls, [0, os.geteuid()])
         self.assertEquals(self.mockos.setegidCalls, [0, os.getegid()])
--- twisted/conch/test/test_recvline.py (original)
+++ twisted/conch/test/test_recvline.py (refactored)
@@ -518,9 +518,9 @@
         # Wait for the process protocol and test terminal to become
         # connected before proceeding.  The former should always
         # happen first, but it doesn't hurt to be safe.
-        return defer.gatherResults(filter(None, [
+        return defer.gatherResults([_f for _f in [
             processClient.onConnection,
-            testTerminal.expect(">>> ")]))
+            testTerminal.expect(">>> ")] if _f])
 
     def tearDown(self):
         # Kill the child process.  We're done with it.
--- twisted/conch/test/test_ssh.py (original)
+++ twisted/conch/test/test_ssh.py (refactored)
@@ -19,7 +19,7 @@
 from twisted.python import failure, log
 from twisted.trial import unittest
 
-from test_recvline import LoopbackRelay
+from .test_recvline import LoopbackRelay
 
 
 
@@ -74,7 +74,7 @@
 
     def logout(self):
         loggedOut = True
-        for listener in self.listeners.values():
+        for listener in list(self.listeners.values()):
             log.msg('stopListening %s' % listener)
             listener.stopListening()
 
@@ -237,10 +237,10 @@
     class UtilityTestCase(unittest.TestCase):
         def testCounter(self):
             c = transport._Counter('\x00\x00', 2)
-            for i in xrange(256 * 256):
+            for i in range(256 * 256):
                 self.assertEquals(c(), struct.pack('!H', (i + 1) % (2 ** 16)))
             # It should wrap around, too.
-            for i in xrange(256 * 256):
+            for i in range(256 * 256):
                 self.assertEquals(c(), struct.pack('!H', (i + 1) % (2 ** 16)))
 
 
@@ -277,7 +277,7 @@
 
         def buildProtocol(self, addr):
             proto = ConchTestServer()
-            proto.supportedPublicKeys = self.privateKeys.keys()
+            proto.supportedPublicKeys = list(self.privateKeys.keys())
             proto.factory = self
 
             if hasattr(self, 'expectedLoseConnection'):
--- twisted/conch/test/test_transport.py (original)
+++ twisted/conch/test/test_transport.py (refactored)
@@ -269,7 +269,7 @@
         We used to map key types to public key blobs as strings.
         """
         keys = MockFactory.getPublicKeys(self)
-        for name, key in keys.items()[:]:
+        for name, key in list(keys.items())[:]:
             keys[name] = key.blob()
         return keys
 
@@ -287,7 +287,7 @@
         We used to map key types to PyCrypto key objects.
         """
         keys = MockFactory.getPrivateKeys(self)
-        for name, key  in keys.items()[:]:
+        for name, key  in list(keys.items())[:]:
             keys[name] = key.keyObject
         return keys
 
@@ -1628,7 +1628,7 @@
         """
         ciphers = transport.SSHCiphers('A', 'B', 'C', 'D')
         iv = key = '\x00' * 16
-        for cipName, (modName, keySize, counter) in ciphers.cipherMap.items():
+        for cipName, (modName, keySize, counter) in list(ciphers.cipherMap.items()):
             cip = ciphers._getCipher(cipName, iv, key)
             if cipName == 'none':
                 self.assertIsInstance(cip, transport._DummyCipher)
@@ -1642,7 +1642,7 @@
         """
         ciphers = transport.SSHCiphers('A', 'B', 'C', 'D')
         key = '\x00' * 64
-        for macName, mac in ciphers.macMap.items():
+        for macName, mac in list(ciphers.macMap.items()):
             mod = ciphers._getMAC(macName, key)
             if macName == 'none':
                 self.assertIdentical(mac, None)
@@ -1660,7 +1660,7 @@
         Test that setKeys sets up the ciphers.
         """
         key = '\x00' * 64
-        cipherItems = transport.SSHCiphers.cipherMap.items()
+        cipherItems = list(transport.SSHCiphers.cipherMap.items())
         for cipName, (modName, keySize, counter) in cipherItems:
             encCipher = transport.SSHCiphers(cipName, 'none', 'none', 'none')
             decCipher = transport.SSHCiphers('none', cipName, 'none', 'none')
@@ -1685,7 +1685,7 @@
         Test that setKeys sets up the MACs.
         """
         key = '\x00' * 64
-        for macName, mod in transport.SSHCiphers.macMap.items():
+        for macName, mod in list(transport.SSHCiphers.macMap.items()):
             outMac = transport.SSHCiphers('none', 'none', macName, 'none')
             inMac = transport.SSHCiphers('none', 'none', 'none', macName)
             outMac.setKeys('', '', '', '', key, '')
--- twisted/conch/ui/ansi.py (original)
+++ twisted/conch/ui/ansi.py (refactored)
@@ -21,7 +21,7 @@
     # The colors to use
     COLORS = ('b', 'r', 'g', 'y', 'l', 'm', 'c', 'w')
     BOLD_COLORS = tuple([x.upper() for x in COLORS])
-    BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(len(COLORS))
+    BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = list(range(len(COLORS)))
 
     # Color names
     COLOR_NAMES = (
@@ -166,7 +166,7 @@
             str = '0'
 
         try:
-            parts = map(int, str.split(';'))
+            parts = list(map(int, str.split(';')))
         except ValueError:
             log.msg('Invalid ANSI color sequence (%d): %s' % (len(str), str))
             self.currentFG, self.currentBG = self.defaultFG, self.defaultBG
--- twisted/conch/ui/tkvt100.py (original)
+++ twisted/conch/ui/tkvt100.py (refactored)
@@ -8,8 +8,8 @@
 Maintainer: Paul Swartz
 """
 
-import Tkinter, tkFont
-import ansi
+import tkinter, tkFont
+from . import ansi
 import string
 
 ttyFont = None#tkFont.Font(family = 'Courier', size = 10)
@@ -27,20 +27,20 @@
     'L': '#0000ff', 'M': '#ff00ff', 'C': '#00ffff', 'W': '#ffffff',
 }
 
-class VT100Frame(Tkinter.Frame):
+class VT100Frame(tkinter.Frame):
     def __init__(self, *args, **kw):
         global ttyFont, fontHeight, fontWidth
         ttyFont = tkFont.Font(family = 'Courier', size = 10)
-        fontWidth, fontHeight = max(map(ttyFont.measure, string.letters+string.digits)), int(ttyFont.metrics()['linespace'])
+        fontWidth, fontHeight = max(list(map(ttyFont.measure, string.letters+string.digits))), int(ttyFont.metrics()['linespace'])
         self.width = kw.get('width', 80)
         self.height = kw.get('height', 25)
         self.callback = kw['callback']
         del kw['callback']
         kw['width'] = w = fontWidth * self.width
         kw['height'] = h = fontHeight * self.height
-        Tkinter.Frame.__init__(self, *args, **kw)
-        self.canvas = Tkinter.Canvas(bg='#000000', width=w, height=h)
-        self.canvas.pack(side=Tkinter.TOP, fill=Tkinter.BOTH, expand=1)
+        tkinter.Frame.__init__(self, *args, **kw)
+        self.canvas = tkinter.Canvas(bg='#000000', width=w, height=h)
+        self.canvas.pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)
         self.canvas.bind('<Key>', self.keyPressed)
         self.canvas.bind('<1>', lambda x: 'break')
         self.canvas.bind('<Up>', self.upPressed)
@@ -85,7 +85,7 @@
             [self.canvas.delete(item) for item in items]
         if bg:
             self.canvas.create_rectangle(canvasX, canvasY, canvasX+fontWidth-1, canvasY+fontHeight-1, fill=bg, outline=bg)
-        self.canvas.create_text(canvasX, canvasY, anchor=Tkinter.NW, font=ttyFont, text=ch, fill=fg)
+        self.canvas.create_text(canvasX, canvasY, anchor=tkinter.NW, font=ttyFont, text=ch, fill=fg)
         self.x+=1
             
     def write(self, data):
@@ -171,7 +171,7 @@
             self.x=start-1
         elif cursor[-1]=='H':
             if len(cursor)>1:
-                y,x = map(int, cursor[:-1].split(';'))
+                y,x = list(map(int, cursor[:-1].split(';')))
                 y-=1
                 x-=1
             else:
--- twisted/cred/pamauth.py (original)
+++ twisted/cred/pamauth.py (refactored)
@@ -34,7 +34,7 @@
         if done[0]:
             return done[1]
         else:
-            raise done[1].type, done[1].value
+            raise done[1].type(done[1].value)
 
     return callIntoPAM(service, user, _conv)
 
@@ -65,10 +65,10 @@
             p = getpass.getpass(message)
             resp.append((p, 0))
         elif kind == 2: # text
-            p = raw_input(message)
+            p = input(message)
             resp.append((p, 0))
         elif kind in (3,4):
-            print message
+            print(message)
             resp.append(("", 0))
         else:
             return defer.fail('foo')
--- twisted/cred/portal.py (original)
+++ twisted/cred/portal.py (refactored)
@@ -67,7 +67,7 @@
         """
         Return list of credentials interfaces that can be used to login.
         """
-        return self.checkers.keys()
+        return list(self.checkers.keys())
 
     def registerChecker(self, checker, *credentialInterfaces):
         if not credentialInterfaces:
--- twisted/cred/strcred.py (original)
+++ twisted/cred/strcred.py (refactored)
@@ -206,13 +206,13 @@
         """
         try:
             self.addChecker(makeChecker(description))
-        except UnsupportedInterfaces, e:
+        except UnsupportedInterfaces as e:
             raise usage.UsageError(
                 'Auth plugin not supported: %s' % e.args[0])
-        except InvalidAuthType, e:
+        except InvalidAuthType as e:
             raise usage.UsageError(
                 'Auth plugin not recognized: %s' % e.args[0])
-        except Exception, e:
+        except Exception as e:
             raise usage.UsageError('Unexpected error: %s' % e)
 
 
--- twisted/enterprise/adbapi.py (original)
+++ twisted/enterprise/adbapi.py (refactored)
@@ -197,7 +197,7 @@
 
         for arg in self.CP_ARGS:
             cp_arg = 'cp_%s' % arg
-            if connkw.has_key(cp_arg):
+            if cp_arg in connkw:
                 setattr(self, arg, connkw[cp_arg])
                 del connkw[cp_arg]
 
@@ -208,9 +208,9 @@
 
         # these are optional so import them here
         from twisted.python import threadpool
-        import thread
-
-        self.threadID = thread.get_ident
+        import _thread
+
+        self.threadID = _thread.get_ident
         self.threadpool = threadpool.ThreadPool(self.min, self.max)
 
         from twisted.internet import reactor
@@ -275,7 +275,7 @@
                 conn.rollback()
             except:
                 log.err(None, "Rollback failed")
-            raise excType, excValue, excTraceback
+            raise excType(excValue).with_traceback(excTraceback)
 
 
     def runInteraction(self, interaction, *args, **kw):
@@ -370,7 +370,7 @@
         self.shutdownID = None
         self.threadpool.stop()
         self.running = False
-        for conn in self.connections.values():
+        for conn in list(self.connections.values()):
             self._close(conn)
         self.connections.clear()
 
@@ -436,7 +436,7 @@
                 conn.rollback()
             except:
                 log.err(None, "Rollback failed")
-            raise excType, excValue, excTraceback
+            raise excType(excValue).with_traceback(excTraceback)
 
 
     def _runQuery(self, trans, *args, **kw):
--- twisted/enterprise/reflector.py (original)
+++ twisted/enterprise/reflector.py (refactored)
@@ -127,7 +127,7 @@
     def removeFromCache(self, rowObject):
         """NOTE: should this be recursive!??"""
         key = rowObject.getKeyTuple()
-        if self.rowCache.has_key(key):
+        if key in self.rowCache:
             del self.rowCache[key]
 
     ####### Row Operations ########
--- twisted/enterprise/util.py (original)
+++ twisted/enterprise/util.py (refactored)
@@ -92,8 +92,8 @@
                     l.append("\\%03o" % i)
             l.append("'")
             return "".join(l)
-        if not isinstance(value, types.StringType) and \
-               not isinstance(value, types.UnicodeType):
+        if not isinstance(value, bytes) and \
+               not isinstance(value, str):
             value = str(value)
         return "'%s'" % string_escaper(value)
 quote = _releasedDeprecation(quote)
--- twisted/flow/base.py (original)
+++ twisted/flow/base.py (refactored)
@@ -170,7 +170,7 @@
     def __iter__(self):
         return self
 
-    def next(self):
+    def __next__(self):
         """
         return current result
 
--- twisted/flow/controller.py (original)
+++ twisted/flow/controller.py (refactored)
@@ -12,8 +12,8 @@
 the flow stack.
 """
 
-from base import *
-from wrap import wrap
+from .base import *
+from .wrap import wrap
 from twisted.internet import defer
 
 class Block(Controller,Stage):
@@ -33,7 +33,7 @@
         self._stage = wrap(stage,*trap)
         self.block = time.sleep
 
-    def next(self):
+    def __next__(self):
         """ fetch the next value from the Stage flow """
         stage = self._stage
         while True:
@@ -44,7 +44,7 @@
                         self.block(result.timeout)
                         continue
                 raise Unsupported(result)
-            return stage.next()
+            return next(stage)
 
 class Deferred(Controller, defer.Deferred):
     """
--- twisted/flow/pipe.py (original)
+++ twisted/flow/pipe.py (refactored)
@@ -11,8 +11,8 @@
 stages take a single input and modify its results, ie a rewrite stage.
 """
 
-from base import *
-from wrap import wrap
+from .base import *
+from .wrap import wrap
 from twisted.python.failure import Failure
 
 class Pipe(Stage):
@@ -75,7 +75,7 @@
         self._func = func
 
     def process(self, results, stop):
-        self.results.extend(filter(self._func,results))
+        self.results.extend(list(filter(self._func,results)))
 
 class LineBreak(Pipe):
     """ pipe stage which breaks its input into lines """
@@ -108,5 +108,5 @@
             if self._trailer:
                 self.results.append(tail)
             else:
-                raise RuntimeError, "trailing data remains: '%s'" % tail[:10]
+                raise RuntimeError("trailing data remains: '%s'" % tail[:10])
 
--- twisted/flow/protocol.py (original)
+++ twisted/flow/protocol.py (refactored)
@@ -13,9 +13,9 @@
 """
 
 import types
-from base import *
-from wrap import wrap
-from stage import Callback
+from .base import *
+from .wrap import wrap
+from .stage import Callback
 from twisted.internet import protocol
 from twisted.internet.error import ConnectionLost, ConnectionDone
 
@@ -127,7 +127,7 @@
                     self.transport.writeSequence(cmd.results)
                     cmd.results = []
         def connectionMade(self):
-            if types.ClassType == type(self.controller):
+            if type == type(self.controller):
                 self._controller = wrap(self.controller(self))
             else:
                 self._controller = wrap(self.controller())
--- twisted/flow/stage.py (original)
+++ twisted/flow/stage.py (refactored)
@@ -12,8 +12,8 @@
 take more than one input stages or alternative input, such as a callback.
 """
 
-from base import *
-from wrap import wrap
+from .base import *
+from .wrap import wrap
 from twisted.python.failure import Failure
 
 class Map(Stage):
@@ -76,7 +76,7 @@
         if self.func:
             try:
                 curr = self.func(*curr)
-            except Failure, fail:
+            except Failure as fail:
                 self.failure = fail
                 return
             except:
--- twisted/flow/threads.py (original)
+++ twisted/flow/threads.py (refactored)
@@ -12,9 +12,9 @@
     Support for threads within a flow
 """
 
-from __future__ import nested_scopes
-
-from base import *
+
+
+from .base import *
 from twisted.python.failure import Failure
 from twisted.internet import reactor
 from time import sleep
@@ -107,7 +107,7 @@
         else:
             try:
                 while True:
-                    val = self._iterable.next()
+                    val = next(self._iterable)
                     reactor.callFromThread(self._process_result, val)
             except StopIteration:
                 reactor.callFromThread(self._stopping)
@@ -200,7 +200,7 @@
             raise StopIteration
         return ret
 
-    def next(self):
+    def __next__(self):
         ret = self.curs.fetchone()
         if not ret: 
             self.curs = None
--- twisted/flow/web.py (original)
+++ twisted/flow/web.py (refactored)
@@ -9,7 +9,7 @@
     This contains wrappers to apply flow to components in twisted.web.*
 
 """
-from controller import Deferred
+from .controller import Deferred
 from twisted.web import resource, server
 from twisted.python.failure import Failure
 
--- twisted/flow/wrap.py (original)
+++ twisted/flow/wrap.py (refactored)
@@ -11,7 +11,7 @@
     the private classes used for its implementation.
 """
 
-from base import *
+from .base import *
 from twisted.python.failure import Failure
 from twisted.internet.defer import Deferred
 
@@ -90,7 +90,7 @@
                     return instruction
                 self._next = None 
             try:
-                result = self._iterable.next()
+                result = next(self._iterable)
                 if isinstance(result, Instruction):
                     if isinstance(result, Stage):
                         self._next = result
@@ -103,7 +103,7 @@
                 self.results.append(result)
             except StopIteration:
                 self.stop = True
-            except Failure, fail:
+            except Failure as fail:
                 self.failure = fail
             except:
                 self.failure = Failure()
@@ -194,7 +194,7 @@
             obj._trap = tuple(trap)
         return obj
 
-    if callable(obj):
+    if hasattr(obj, '__call__'):
         obj = obj()
 
     typ = type(obj)
@@ -213,5 +213,5 @@
     except TypeError: 
         pass
 
-    raise ValueError, "A wrapper is not available for %r" % (obj,)
-
+    raise ValueError("A wrapper is not available for %r" % (obj,))
+
--- twisted/flow/test/test_flow.py (original)
+++ twisted/flow/test/test_flow.py (refactored)
@@ -5,8 +5,8 @@
 # Author: Clark C. Evans
 #
 
-from __future__ import nested_scopes
-from __future__ import generators
+
+
 
 from twisted.flow import flow
 from twisted.flow.threads import Threaded, QueryIterator
@@ -32,7 +32,7 @@
         self.list = list[:]
     def __iter__(self):
         return self
-    def next(self):
+    def __next__(self):
         if self.list:
             return self.list.pop(0)
         raise StopIteration
@@ -64,7 +64,7 @@
         return self.nam
     def yield_results(self):
         self.next = self.yield_lst
-        return (self.lst.next(), self.nam.next())
+        return (next(self.lst), next(self.nam))
 
 class consumer:
     """ iterator version of the following generator...
@@ -89,13 +89,13 @@
         return self.title
     def yield_title_result(self):
         self.next = self.yield_lst
-        return self.title.next()
+        return next(self.title)
     def yield_lst(self):
         self.next = self.yield_result
         return self.lst
     def yield_result(self):
         self.next = self.yield_lst
-        return self.lst.next()
+        return next(self.lst)
 
 
 class badgen:
@@ -137,7 +137,7 @@
         return self.src
     def yield_append(self):
         try:
-            self.out.append(self.src.next())
+            self.out.append(next(self.src))
         except StopIteration:
             self.next = self.yield_finish
             return self.out
@@ -165,8 +165,8 @@
         return self.both
     def yield_result(self):
         self.next = self.yield_both
-        stage = self.both.next()
-        return (stage.name, stage.next())
+        stage = next(self.both)
+        return (stage.name, next(stage))
 
 class echoServer:
     """ a simple echo protocol, server side
@@ -187,7 +187,7 @@
         return self.conn
     def yield_data(self):
         self.next = self.yield_conn
-        return self.conn.next()
+        return next(self.conn)
 
 class echoClient:
     """ a simple echo client tester
@@ -211,7 +211,7 @@
         return self.conn
     def yield_stop(self):
         # signal that we are done
-        self.conn.factory.d.callback(self.conn.next())
+        self.conn.factory.d.callback(next(self.conn))
         raise StopIteration()
 
 class CountIterator:
@@ -219,7 +219,7 @@
         self.count = count
     def __iter__(self):
         return self
-    def next(self): # this is run in a separate thread
+    def __next__(self): # this is run in a separate thread
         sleep(.1)
         val = self.count
         if not(val):
@@ -230,7 +230,7 @@
 class FlowTest(unittest.TestCase):
     def testNotReady(self):
         x = flow.wrap([1,2,3])
-        self.assertRaises(flow.NotReadyError,x.next)
+        self.assertRaises(flow.NotReadyError,x.__next__)
 
     def testBasic(self):
         lhs = ['string']
@@ -307,7 +307,7 @@
 
     def testBuildList(self):
         src = flow.wrap([1,2,3])
-        out = flow.Block(buildlist(src)).next()
+        out = next(flow.Block(buildlist(src)))
         self.assertEquals(out,[1,2,3])
 
     def testDeferredFailure(self):
@@ -351,7 +351,7 @@
         for x in range(9):
             cb.result(x)
         cb.finish()
-        d.addCallback(self.assertEqual, [range(9)])
+        d.addCallback(self.assertEqual, [list(range(9))])
         return d
 
     def testCallbackFailure(self):
--- twisted/internet/_dumbwin32proc.py (original)
+++ twisted/internet/_dumbwin32proc.py (refactored)
@@ -36,7 +36,7 @@
 
 def debug(msg):
     import sys
-    print msg
+    print(msg)
     sys.stdout.flush()
 
 class _Reaper(_pollingfile._PollableResource):
@@ -174,7 +174,7 @@
                 command, cmdline, None, None, 1, 0, env, path, StartupInfo)
         try:
             doCreate()
-        except pywintypes.error, pwte:
+        except pywintypes.error as pwte:
             if not _invalidWin32App(pwte):
                 # This behavior isn't _really_ documented, but let's make it
                 # consistent with the behavior that is documented.
@@ -196,7 +196,7 @@
                     try:
                         # Let's try again.
                         doCreate()
-                    except pywintypes.error, pwte2:
+                    except pywintypes.error as pwte2:
                         # d'oh, failed again!
                         if _invalidWin32App(pwte2):
                             raise OSError(
--- twisted/internet/_javaserialport.py (original)
+++ twisted/internet/_javaserialport.py (refactored)
@@ -15,7 +15,7 @@
 from serial import PARITY_NONE, PARITY_EVEN, PARITY_ODD
 from serial import STOPBITS_ONE, STOPBITS_TWO
 from serial import FIVEBITS, SIXBITS, SEVENBITS, EIGHTBITS
-from serialport import BaseSerialPort
+from .serialport import BaseSerialPort
 
 # twisted imports
 from twisted.internet import abstract, javareactor, main
@@ -47,14 +47,14 @@
           self._serial.write(data)
           return len(data)
         # should have something better here
-        except Exception, e:
+        except Exception as e:
           return main.CONNECTION_LOST
 
     def doRead(self):
         readBytes = ''
         try:
           readBytes = self._serial.read(min(8192, self.inWaiting()))
-        except Exception, e:
+        except Exception as e:
           return main.CONNECTION_LOST
         if not readBytes:
           return main.CONNECTION_LOST
--- twisted/internet/_posixserialport.py (original)
+++ twisted/internet/_posixserialport.py (refactored)
@@ -16,7 +16,7 @@
 from serial import STOPBITS_ONE, STOPBITS_TWO
 from serial import FIVEBITS, SIXBITS, SEVENBITS, EIGHTBITS
 
-from serialport import BaseSerialPort
+from .serialport import BaseSerialPort
 
 # twisted imports
 from twisted.internet import abstract, fdesc, main
--- twisted/internet/_sslverify.py (original)
+++ twisted/internet/_sslverify.py (refactored)
@@ -14,7 +14,7 @@
 
 # Private - shared between all OpenSSLCertificateOptions, counts up to provide
 # a unique session id for each context
-_sessionCounter = itertools.count().next
+_sessionCounter = itertools.count().__next__
 
 _x509names = {
     'CN': 'commonName',
@@ -57,7 +57,7 @@
     __slots__ = ()
 
     def __init__(self, **kw):
-        for k, v in kw.iteritems():
+        for k, v in kw.items():
             setattr(self, k, v)
 
 
@@ -70,7 +70,7 @@
 
 
     def _copyInto(self, x509name):
-        for k, v in self.iteritems():
+        for k, v in self.items():
             setattr(x509name, k, v)
 
 
@@ -102,7 +102,7 @@
         l = []
         lablen = 0
         def uniqueValues(mapping):
-            return dict.fromkeys(mapping.itervalues()).keys()
+            return list(dict.fromkeys(iter(mapping.values())).keys())
         for k in uniqueValues(_x509names):
             label = util.nameToLabel(k)
             lablen = max(len(label), lablen)
--- twisted/internet/_threadedselect.py (original)
+++ twisted/internet/_threadedselect.py (refactored)
@@ -4,7 +4,7 @@
 # Copyright (c) 2001-2004 Twisted Matrix Laboratories.
 # See LICENSE for details.
 
-from __future__ import generators
+
 
 """
 Threaded select reactor
@@ -58,7 +58,7 @@
 """
 
 from threading import Thread
-from Queue import Queue, Empty
+from queue import Queue, Empty
 from time import sleep
 import sys
 
@@ -127,8 +127,8 @@
 
     def _preenDescriptorsInThread(self):
         log.msg("Malformed file descriptor found.  Preening lists.")
-        readers = self.reads.keys()
-        writers = self.writes.keys()
+        readers = list(self.reads.keys())
+        writers = list(self.writes.keys())
         self.reads.clear()
         self.writes.clear()
         for selDict, selList in ((self.reads, readers), (self.writes, writers)):
@@ -163,20 +163,20 @@
         writes = self.writes
         while 1:
             try:
-                r, w, ignored = _select(reads.keys(),
-                                        writes.keys(),
+                r, w, ignored = _select(list(reads.keys()),
+                                        list(writes.keys()),
                                         [], timeout)
                 break
-            except ValueError, ve:
+            except ValueError as ve:
                 # Possibly a file descriptor has gone negative?
                 log.err()
                 self._preenDescriptorsInThread()
-            except TypeError, te:
+            except TypeError as te:
                 # Something *totally* invalid (object w/o fileno, non-integral
                 # result) was passed
                 log.err()
                 self._preenDescriptorsInThread()
-            except (select.error, IOError), se:
+            except (select.error, IOError) as se:
                 # select(2) encountered an error
                 if se.args[0] in (0, 2):
                     # windows does this if it got an empty list
@@ -257,9 +257,9 @@
         loop = self._interleave()
         def mainWaker(waker=waker, loop=loop):
             #print >>sys.stderr, "mainWaker()"
-            waker(loop.next)
+            waker(loop.__next__)
         self.mainWaker = mainWaker
-        loop.next()
+        next(loop)
         self.ensureWorkerThread()
 
     def _mainLoopShutdown(self):
@@ -329,11 +329,11 @@
 
 
     def getReaders(self):
-        return self.reads.keys()
+        return list(self.reads.keys())
 
 
     def getWriters(self):
-        return self.writes.keys()
+        return list(self.writes.keys())
 
 
     def run(self, installSignalHandlers=1):
--- twisted/internet/_win32serialport.py (original)
+++ twisted/internet/_win32serialport.py (refactored)
@@ -23,7 +23,7 @@
 from twisted.python import log
 
 # sibling imports
-from serialport import BaseSerialPort
+from .serialport import BaseSerialPort
 
 
 class SerialPort(BaseSerialPort, abstract.FileDescriptor):
--- twisted/internet/abstract.py (original)
+++ twisted/internet/abstract.py (refactored)
@@ -176,7 +176,7 @@
         buffer and this descriptor has a registered streaming producer, its
         C{pauseProducing()} method will be called.
         """
-        if isinstance(data, unicode): # no, really, I mean it
+        if isinstance(data, str): # no, really, I mean it
             raise TypeError("Data must not be unicode")
         if not self.connected or self._writeDisconnected:
             return
--- twisted/internet/base.py (original)
+++ twisted/internet/base.py (refactored)
@@ -164,9 +164,9 @@
             return self._str
         if hasattr(self, 'func'):
             if hasattr(self.func, 'func_name'):
-                func = self.func.func_name
+                func = self.func.__name__
                 if hasattr(self.func, 'im_class'):
-                    func = self.func.im_class.__name__ + '.' + func
+                    func = self.func.__self__.__class__.__name__ + '.' + func
             else:
                 func = reflect.safe_repr(self.func)
         else:
@@ -182,7 +182,7 @@
                 if self.kw:
                     L.append(", ")
             if self.kw:
-                L.append(", ".join(['%s=%s' % (k, reflect.safe_repr(v)) for (k, v) in self.kw.iteritems()]))
+                L.append(", ".join(['%s=%s' % (k, reflect.safe_repr(v)) for (k, v) in self.kw.items()]))
             L.append(")")
 
         if self.debug:
@@ -325,7 +325,7 @@
         """
         try:
             phase, callable, args, kwargs = handle
-        except (TypeError, ValueError), e:
+        except (TypeError, ValueError) as e:
             raise ValueError("invalid trigger handle")
         else:
             if phase not in ('before', 'during', 'after'):
@@ -588,7 +588,7 @@
     def addSystemEventTrigger(self, _phase, _eventType, _f, *args, **kw):
         """See twisted.internet.interfaces.IReactorCore.addSystemEventTrigger.
         """
-        assert callable(_f), "%s is not callable" % _f
+        assert hasattr(_f, '__call__'), "%s is not callable" % _f
         if _eventType not in self._eventTriggers:
             self._eventTriggers[_eventType] = _ThreePhaseEvent()
         return (_eventType, self._eventTriggers[_eventType].addTrigger(
@@ -648,8 +648,8 @@
     def callLater(self, _seconds, _f, *args, **kw):
         """See twisted.internet.interfaces.IReactorTime.callLater.
         """
-        assert callable(_f), "%s is not callable" % _f
-        assert sys.maxint >= _seconds >= 0, \
+        assert hasattr(_f, '__call__'), "%s is not callable" % _f
+        assert sys.maxsize >= _seconds >= 0, \
                "%s is not greater than or equal to 0 seconds" % (_seconds,)
         tple = DelayedCall(self.seconds() + _seconds, _f, args, kw,
                            self._cancelCallLater,
@@ -818,7 +818,7 @@
             is returned.  This forces unicode encoding to happen now, rather
             than implicitly later.
             """
-            if isinstance(arg, unicode):
+            if isinstance(arg, str):
                 try:
                     arg = arg.encode(defaultEncoding)
                 except UnicodeEncodeError:
@@ -847,7 +847,7 @@
         outputEnv = None
         if env is not None:
             outputEnv = {}
-            for key, val in env.iteritems():
+            for key, val in env.items():
                 key = argChecker(key)
                 if key is None:
                     raise TypeError("Environment contains a non-string key")
@@ -872,7 +872,7 @@
             """
             See L{twisted.internet.interfaces.IReactorThreads.callFromThread}.
             """
-            assert callable(f), "%s is not callable" % (f,)
+            assert hasattr(f, '__call__'), "%s is not callable" % (f,)
             # lists are thread-safe in CPython, but not in Jython
             # this is probably a bug in Jython, but until fixed this code
             # won't work in Jython.
@@ -917,7 +917,7 @@
     else:
         # This is for signal handlers.
         def callFromThread(self, f, *args, **kw):
-            assert callable(f), "%s is not callable" % (f,)
+            assert hasattr(f, '__call__'), "%s is not callable" % (f,)
             # See comment in the other callFromThread implementation.
             self.threadCallQueue.append((f, args, kw))
 
@@ -952,7 +952,7 @@
     def connect(self):
         """Start connection to remote server."""
         if self.state != "disconnected":
-            raise RuntimeError, "can't connect in this state"
+            raise RuntimeError("can't connect in this state")
 
         self.state = "connecting"
         if not self.factoryStarted:
@@ -966,7 +966,7 @@
     def stopConnecting(self):
         """Stop attempting to connect."""
         if self.state != "connecting":
-            raise error.NotConnectingError, "we're not trying to connect"
+            raise error.NotConnectingError("we're not trying to connect")
 
         self.state = "disconnected"
         self.transport.failIfNotConnected(error.UserError())
@@ -1030,7 +1030,7 @@
 
     def doWrite(self):
         """Raises a RuntimeError"""
-        raise RuntimeError, "doWrite called on a %s" % reflect.qual(self.__class__)
+        raise RuntimeError("doWrite called on a %s" % reflect.qual(self.__class__))
 
 
 
--- twisted/internet/cfreactor.py (original)
+++ twisted/internet/cfreactor.py (refactored)
@@ -61,7 +61,7 @@
         
     def __init__(self, reactor, obj):
         if self.cf:
-            raise ValueError, "This socket wrapper is already initialized"
+            raise ValueError("This socket wrapper is already initialized")
         self.reactor = reactor
         self.obj = obj
         obj._orig_ssw_connectionLost = obj.connectionLost
@@ -218,18 +218,18 @@
 
 
     def getReaders(self):
-        return self.readers.keys()
+        return list(self.readers.keys())
 
 
     def getWriters(self):
-        return self.writers.keys()
+        return list(self.writers.keys())
 
 
     def removeAll(self):
-        r = self.readers.keys()
-        for s in self.readers.itervalues():
+        r = list(self.readers.keys())
+        for s in self.readers.values():
             s.stopReading()
-        for s in self.writers.itervalues():
+        for s in self.writers.values():
             s.stopWriting()
         self.readers.clear()
         self.writers.clear()
@@ -237,7 +237,7 @@
         
     def run(self, installSignalHandlers=1, withRunLoop=None):
         if self.running:
-            raise ValueError, "Reactor already running"
+            raise ValueError("Reactor already running")
         if installSignalHandlers:
             self.pollInterval = self.shortIntervalOfTime
         runLoop = self.getRunLoop(withRunLoop)
@@ -268,13 +268,13 @@
         
     def iterate(self, howlong=0.0):
         if self.running:
-            raise ValueError, "Can't iterate a running reactor"
+            raise ValueError("Can't iterate a running reactor")
         self.runUntilCurrent()
         self.doIteration(howlong)
         
     def doIteration(self, howlong):
         if self.running:
-            raise ValueError, "Can't iterate a running reactor"
+            raise ValueError("Can't iterate a running reactor")
         howlong = howlong or 0.01
         pi = self.pollInterval
         self.pollInterval = howlong
@@ -287,7 +287,7 @@
         if self.crashing:
             return
         if not self.running:
-            raise ValueError, "You can't simulate a stopped reactor"
+            raise ValueError("You can't simulate a stopped reactor")
         if self._doRunUntilCurrent:
             self.runUntilCurrent()
         if self.crashing:
@@ -306,7 +306,7 @@
         
     def _startup(self):
         if self.running:
-            raise ValueError, "Can't bootstrap a running reactor"
+            raise ValueError("Can't bootstrap a running reactor")
         self.timer = cf.PyCFRunLoopTimer(cf.now(), self.pollInterval, self.simulate)
         self.runLoop.addTimer(self.timer)
 
@@ -318,7 +318,7 @@
 
     def crash(self):
         if not self.running:
-            raise ValueError, "Can't crash a stopped reactor"
+            raise ValueError("Can't crash a stopped reactor")
         posixbase.PosixReactorBase.crash(self)
         self.crashing = True
         if self.timer is not None:
@@ -329,7 +329,7 @@
 
     def stop(self):
         if not self.running:
-            raise ValueError, "Can't stop a stopped reactor"
+            raise ValueError("Can't stop a stopped reactor")
         posixbase.PosixReactorBase.stop(self)
 
 def install(runLoop=None):
--- twisted/internet/default.py (original)
+++ twisted/internet/default.py (refactored)
@@ -15,7 +15,7 @@
 warnings.warn("twisted.internet.default is deprecated. Use posixbase or selectreactor instead.", category=DeprecationWarning)
 
 # Backwards compat
-from posixbase import PosixReactorBase
-from selectreactor import SelectReactor, install
+from .posixbase import PosixReactorBase
+from .selectreactor import SelectReactor, install
 
 __all__ = ["install", "PosixReactorBase", "SelectReactor"]
--- twisted/internet/defer.py (original)
+++ twisted/internet/defer.py (refactored)
@@ -9,7 +9,7 @@
 Maintainer: Glyph Lefkowitz
 """
 
-from __future__ import nested_scopes, generators
+
 import traceback
 import warnings
 
@@ -176,8 +176,8 @@
 
         These will be executed when the 'master' callback is run.
         """
-        assert callable(callback)
-        assert errback == None or callable(errback)
+        assert hasattr(callback, '__call__')
+        assert errback == None or hasattr(errback, '__call__')
         cbs = ((callback, callbackArgs, callbackKeywords),
                (errback or (passthru), errbackArgs, errbackKeywords))
         self.callbacks.append(cbs)
@@ -602,7 +602,7 @@
 
     while 1:
         try:
-            result = g.next()
+            result = next(g)
         except StopIteration:
             deferred.callback(result)
             return deferred
@@ -753,7 +753,7 @@
             # fell off the end, or "return" statement
             deferred.callback(None)
             return deferred
-        except _DefGen_Return, e:
+        except _DefGen_Return as e:
             # returnValue call
             deferred.callback(e.value)
             return deferred
--- twisted/internet/epollreactor.py (original)
+++ twisted/internet/epollreactor.py (refactored)
@@ -115,7 +115,7 @@
         """
         fd = xer.fileno()
         if fd == -1:
-            for fd, fdes in selectables.items():
+            for fd, fdes in list(selectables.items()):
                 if xer is fdes:
                     break
             else:
@@ -155,8 +155,8 @@
             if fd in self._reads:
                 del self._reads[fd]
                 del self._selectables[fd]
-        result = self._selectables.values()
-        fds = self._selectables.keys()
+        result = list(self._selectables.values())
+        fds = list(self._selectables.keys())
         self._reads.clear()
         self._writes.clear()
         self._selectables.clear()
@@ -196,7 +196,7 @@
             # the amount of time we block to the value specified by our
             # caller.
             l = self._poller.wait(len(self._selectables), timeout)
-        except IOError, err:
+        except IOError as err:
             if err.errno == errno.EINTR:
                 return
             # See epoll_wait(2) for documentation on the other conditions
--- twisted/internet/fdesc.py (original)
+++ twisted/internet/fdesc.py (refactored)
@@ -60,7 +60,7 @@
     """
     try:
         output = os.read(fd, 8192)
-    except (OSError, IOError), ioe:
+    except (OSError, IOError) as ioe:
         if ioe.args[0] in (errno.EAGAIN, errno.EINTR):
             return
         else:
@@ -84,7 +84,7 @@
     """
     try:
         return os.write(fd, data)
-    except (OSError, IOError), io:
+    except (OSError, IOError) as io:
         if io.errno in (errno.EAGAIN, errno.EINTR):
             return 0
         return CONNECTION_LOST
--- twisted/internet/gtk2reactor.py (original)
+++ twisted/internet/gtk2reactor.py (refactored)
@@ -125,11 +125,11 @@
 
 
     def getReaders(self):
-        return self._reads.keys()
+        return list(self._reads.keys())
 
 
     def getWriters(self):
-        return self._writes.keys()
+        return list(self._writes.keys())
 
 
     def removeAll(self):
--- twisted/internet/gtkreactor.py (original)
+++ twisted/internet/gtkreactor.py (refactored)
@@ -21,7 +21,7 @@
 try:
     import pygtk
     pygtk.require('1.2')
-except ImportError, AttributeError:
+except ImportError as AttributeError:
     pass # maybe we're using pygtk before this hack existed.
 import gtk
 
@@ -70,11 +70,11 @@
 
 
     def getReaders(self):
-        return self._reads.keys()
+        return list(self._reads.keys())
 
 
     def getWriters(self):
-        return self._writes.keys()
+        return list(self._writes.keys())
 
 
     def removeAll(self):
--- twisted/internet/interfaces.py (original)
+++ twisted/internet/interfaces.py (refactored)
@@ -327,7 +327,7 @@
         @return: An object which provides L{IConnector}.
         """
 
-    def listenUNIX(address, factory, backlog=50, mode=0666, wantPID=0):
+    def listenUNIX(address, factory, backlog=50, mode=0o666, wantPID=0):
         """
         Listen on a UNIX socket.
 
@@ -352,7 +352,7 @@
     Datagram UNIX socket methods.
     """
 
-    def connectUNIXDatagram(address, protocol, maxPacketSize=8192, mode=0666, bindAddress=None):
+    def connectUNIXDatagram(address, protocol, maxPacketSize=8192, mode=0o666, bindAddress=None):
         """
         Connect a client protocol to a datagram UNIX socket.
 
@@ -371,7 +371,7 @@
         @return: An object which provides L{IConnector}.
         """
 
-    def listenUNIXDatagram(address, protocol, maxPacketSize=8192, mode=0666):
+    def listenUNIXDatagram(address, protocol, maxPacketSize=8192, mode=0o666):
         """
         Listen on a datagram UNIX socket.
 
--- twisted/internet/kqreactor.py (original)
+++ twisted/internet/kqreactor.py (refactored)
@@ -157,10 +157,10 @@
         """Remove all selectables, and return a list of them."""
         if self.waker is not None:
             self.removeReader(self.waker)
-        result = self._selectables.values()
-        for fd in self._reads.keys():
+        result = list(self._selectables.values())
+        for fd in list(self._reads.keys()):
             self._updateRegistration(fd, EVFILT_READ, EV_DELETE)
-        for fd in self._writes.keys():
+        for fd in list(self._writes.keys()):
             self._updateRegistration(fd, EVFILT_WRITE, EV_DELETE)
         self._reads.clear()
         self._writes.clear()
@@ -187,7 +187,7 @@
 
         try:
             l = self._kq.kevent([], len(self._selectables), timeout)
-        except OSError, e:
+        except OSError as e:
             if e[0] == errno.EINTR:
                 return
             else:
--- twisted/internet/main.py (original)
+++ twisted/internet/main.py (refactored)
@@ -11,7 +11,7 @@
 Maintainer: Itamar Shtull-Trauring
 """
 
-import error
+from . import error
 
 CONNECTION_DONE = error.ConnectionDone('Connection done')
 CONNECTION_LOST = error.ConnectionLost('Connection lost')
@@ -20,7 +20,7 @@
     # this stuff should be common to all reactors.
     import twisted.internet
     import sys
-    assert not sys.modules.has_key('twisted.internet.reactor'), \
+    assert 'twisted.internet.reactor' not in sys.modules, \
            "reactor already installed"
     twisted.internet.reactor = reactor
     sys.modules['twisted.internet.reactor'] = reactor
--- twisted/internet/pollreactor.py (original)
+++ twisted/internet/pollreactor.py (refactored)
@@ -96,7 +96,7 @@
         except:
             # the hard way: necessary because fileno() may disappear at any
             # moment, thanks to python's underlying sockets impl
-            for fd, fdes in self._selectables.items():
+            for fd, fdes in list(self._selectables.items()):
                 if selectable is fdes:
                     break
             else:
@@ -139,8 +139,8 @@
         """Remove all selectables, and return a list of them."""
         if self.waker is not None:
             self.removeReader(self.waker)
-        result = self._selectables.values()
-        fds = self._selectables.keys()
+        result = list(self._selectables.values())
+        fds = list(self._selectables.keys())
         self._reads.clear()
         self._writes.clear()
         self._selectables.clear()
@@ -158,7 +158,7 @@
 
         try:
             l = self._poller.poll(timeout)
-        except SelectError, e:
+        except SelectError as e:
             if e[0] == errno.EINTR:
                 return
             else:
--- twisted/internet/posixbase.py (original)
+++ twisted/internet/posixbase.py (refactored)
@@ -45,7 +45,7 @@
 processEnabled = False
 if platformType == 'posix':
     from twisted.internet import fdesc
-    import process
+    from . import process
     processEnabled = True
 
 if platform.isWindows():
@@ -87,7 +87,8 @@
         """
         try:
             util.untilConcludes(self.w.send, 'x')
-        except socket.error, (err, msg):
+        except socket.error as xxx_todo_changeme:
+            (err, msg) = xxx_todo_changeme.args
             if err != errno.WSAEWOULDBLOCK:
                 raise
 
@@ -136,7 +137,7 @@
         if self.o is not None:
             try:
                 util.untilConcludes(os.write, self.o, 'x')
-            except OSError, e:
+            except OSError as e:
                 if e.errno != errno.EAGAIN:
                     raise
 
@@ -234,9 +235,9 @@
                 from twisted.internet._dumbwin32proc import Process
                 return Process(self, processProtocol, executable, args, env, path)
             else:
-                raise NotImplementedError, "spawnProcess not available since pywin32 is not installed."
+                raise NotImplementedError("spawnProcess not available since pywin32 is not installed.")
         else:
-            raise NotImplementedError, "spawnProcess only available on Windows or POSIX."
+            raise NotImplementedError("spawnProcess only available on Windows or POSIX.")
 
     # IReactorUDP
 
@@ -300,7 +301,7 @@
                 category=DeprecationWarning,
                 stacklevel=3)
         else:
-            mode = 0666
+            mode = 0o666
         return mode
 
 
--- twisted/internet/process.py (original)
+++ twisted/internet/process.py (refactored)
@@ -41,7 +41,7 @@
     """
     Reap all registered processes.
     """
-    for process in reapProcessHandlers.values():
+    for process in list(reapProcessHandlers.values()):
         process.reapProcess()
 
 
@@ -292,7 +292,7 @@
         try:
             try:
                 pid, status = os.waitpid(self.pid, os.WNOHANG)
-            except OSError, e:
+            except OSError as e:
                 if e.errno == errno.ECHILD:
                     # no child process
                     pid = None
@@ -487,8 +487,8 @@
         or real UID is 0.)
         """
         if not proto:
-            assert 'r' not in childFDs.values()
-            assert 'w' not in childFDs.values()
+            assert 'r' not in list(childFDs.values())
+            assert 'w' not in list(childFDs.values())
         _BaseProcess.__init__(self, proto)
 
         self.pipes = {}
@@ -506,7 +506,7 @@
                         }
 
         debug = self.debug
-        if debug: print "childFDs", childFDs
+        if debug: print("childFDs", childFDs)
 
         _openedPipes = []
         def pipe():
@@ -517,37 +517,37 @@
         # fdmap.keys() are filenos of pipes that are used by the child.
         fdmap = {} # maps childFD to parentFD
         try:
-            for childFD, target in childFDs.items():
-                if debug: print "[%d]" % childFD, target
+            for childFD, target in list(childFDs.items()):
+                if debug: print("[%d]" % childFD, target)
                 if target == "r":
                     # we need a pipe that the parent can read from
                     readFD, writeFD = pipe()
-                    if debug: print "readFD=%d, writeFD=%d" % (readFD, writeFD)
+                    if debug: print("readFD=%d, writeFD=%d" % (readFD, writeFD))
                     fdmap[childFD] = writeFD     # child writes to this
                     helpers[childFD] = readFD    # parent reads from this
                 elif target == "w":
                     # we need a pipe that the parent can write to
                     readFD, writeFD = pipe()
-                    if debug: print "readFD=%d, writeFD=%d" % (readFD, writeFD)
+                    if debug: print("readFD=%d, writeFD=%d" % (readFD, writeFD))
                     fdmap[childFD] = readFD      # child reads from this
                     helpers[childFD] = writeFD   # parent writes to this
                 else:
                     assert type(target) == int, '%r should be an int' % (target,)
                     fdmap[childFD] = target      # parent ignores this
-            if debug: print "fdmap", fdmap
-            if debug: print "helpers", helpers
+            if debug: print("fdmap", fdmap)
+            if debug: print("helpers", helpers)
             # the child only cares about fdmap.values()
 
             self._fork(path, uid, gid, executable, args, environment, fdmap=fdmap)
         except:
-            map(os.close, _openedPipes)
+            list(map(os.close, _openedPipes))
             raise
 
         # we are the parent process:
         self.proto = proto
 
         # arrange for the parent-side pipes to be read and written
-        for childFD, parentFD in helpers.items():
+        for childFD, parentFD in list(helpers.items()):
             os.close(fdmap[childFD])
 
             if childFDs[childFD] == "r":
@@ -603,7 +603,7 @@
             errfd = sys.stderr
             errfd.write("starting _setupChild\n")
 
-        destList = fdmap.values()
+        destList = list(fdmap.values())
         try:
             import resource
             maxfds = resource.getrlimit(resource.RLIMIT_NOFILE)[1] + 1
@@ -613,7 +613,7 @@
         except:
             maxfds = 256
 
-        for fd in xrange(maxfds):
+        for fd in range(maxfds):
             if fd in destList:
                 continue
             if debug and fd == errfd.fileno():
@@ -627,33 +627,33 @@
         # be moved to their appropriate positions in the child (the targets
         # of fdmap, i.e. fdmap.values() )
 
-        if debug: print >>errfd, "fdmap", fdmap
-        childlist = fdmap.keys()
+        if debug: print("fdmap", fdmap, file=errfd)
+        childlist = list(fdmap.keys())
         childlist.sort()
 
         for child in childlist:
             target = fdmap[child]
             if target == child:
                 # fd is already in place
-                if debug: print >>errfd, "%d already in place" % target
+                if debug: print("%d already in place" % target, file=errfd)
                 if fcntl and hasattr(fcntl, 'FD_CLOEXEC'):
                     old = fcntl.fcntl(child, fcntl.F_GETFD)
                     fcntl.fcntl(child,
                                 fcntl.F_SETFD, old & ~fcntl.FD_CLOEXEC)
             else:
-                if child in fdmap.values():
+                if child in list(fdmap.values()):
                     # we can't replace child-fd yet, as some other mapping
                     # still needs the fd it wants to target. We must preserve
                     # that old fd by duping it to a new home.
                     newtarget = os.dup(child) # give it a safe home
-                    if debug: print >>errfd, "os.dup(%d) -> %d" % (child,
-                                                                   newtarget)
+                    if debug: print("os.dup(%d) -> %d" % (child,
+                                                                   newtarget), file=errfd)
                     os.close(child) # close the original
-                    for c, p in fdmap.items():
+                    for c, p in list(fdmap.items()):
                         if p == child:
                             fdmap[c] = newtarget # update all pointers
                 # now it should be available
-                if debug: print >>errfd, "os.dup2(%d,%d)" % (target, child)
+                if debug: print("os.dup2(%d,%d)" % (target, child), file=errfd)
                 os.dup2(target, child)
 
         # At this point, the child has everything it needs. We want to close
@@ -665,11 +665,11 @@
         # need to remove duplicates first.
 
         old = []
-        for fd in fdmap.values():
+        for fd in list(fdmap.values()):
             if not fd in old:
-                if not fd in fdmap.keys():
+                if not fd in list(fdmap.keys()):
                     old.append(fd)
-        if debug: print >>errfd, "old", old
+        if debug: print("old", old, file=errfd)
         for fd in old:
             os.close(fd)
 
@@ -685,12 +685,12 @@
             self.pipes[childFD].loseConnection()
 
     def pauseProducing(self):
-        for p in self.pipes.itervalues():
+        for p in self.pipes.values():
             if isinstance(p, ProcessReader):
                 p.stopReading()
 
     def resumeProducing(self):
-        for p in self.pipes.itervalues():
+        for p in self.pipes.values():
             if isinstance(p, ProcessReader):
                 p.startReading()
 
@@ -864,7 +864,7 @@
         os.dup2(slavefd, 1) # stdout
         os.dup2(slavefd, 2) # stderr
 
-        for fd in xrange(3, 256):
+        for fd in range(3, 256):
             try:
                 os.close(fd)
             except:
--- twisted/internet/selectreactor.py (original)
+++ twisted/internet/selectreactor.py (refactored)
@@ -74,8 +74,8 @@
 
     def _preenDescriptors(self):
         log.msg("Malformed file descriptor found.  Preening lists.")
-        readers = self._reads.keys()
-        writers = self._writes.keys()
+        readers = list(self._reads.keys())
+        writers = list(self._writes.keys())
         self._reads.clear()
         self._writes.clear()
         for selDict, selList in ((self._reads, readers),
@@ -83,7 +83,7 @@
             for selectable in selList:
                 try:
                     select.select([selectable], [selectable], [selectable], 0)
-                except Exception, e:
+                except Exception as e:
                     log.msg("bad descriptor %s" % selectable)
                     self._disconnectSelectable(selectable, e, False)
                 else:
@@ -99,20 +99,20 @@
         """
         while 1:
             try:
-                r, w, ignored = _select(self._reads.keys(),
-                                        self._writes.keys(),
+                r, w, ignored = _select(list(self._reads.keys()),
+                                        list(self._writes.keys()),
                                         [], timeout)
                 break
-            except ValueError, ve:
+            except ValueError as ve:
                 # Possibly a file descriptor has gone negative?
                 log.err()
                 self._preenDescriptors()
-            except TypeError, te:
+            except TypeError as te:
                 # Something *totally* invalid (object w/o fileno, non-integral
                 # result) was passed
                 log.err()
                 self._preenDescriptors()
-            except (select.error, IOError), se:
+            except (select.error, IOError) as se:
                 # select(2) encountered an error
                 if se.args[0] in (0, 2):
                     # windows does this if it got an empty list
@@ -186,11 +186,11 @@
 
 
     def getReaders(self):
-        return self._reads.keys()
+        return list(self._reads.keys())
 
 
     def getWriters(self):
-        return self._writes.keys()
+        return list(self._writes.keys())
 
 
 
--- twisted/internet/task.py (original)
+++ twisted/internet/task.py (refactored)
@@ -73,7 +73,7 @@
         assert not self.running, ("Tried to start an already running "
                                   "LoopingCall.")
         if interval < 0:
-            raise ValueError, "interval must be >= 0"
+            raise ValueError("interval must be >= 0")
         self.running = True
         d = self.deferred = defer.Deferred()
         self.starttime = self.clock.seconds()
@@ -141,9 +141,9 @@
 
     def __repr__(self):
         if hasattr(self.f, 'func_name'):
-            func = self.f.func_name
+            func = self.f.__name__
             if hasattr(self.f, 'im_class'):
-                func = self.f.im_class.__name__ + '.' + func
+                func = self.f.__self__.__class__.__name__ + '.' + func
         else:
             func = reflect.safe_repr(self.f)
 
@@ -248,7 +248,7 @@
         for taskObj in self._tasks():
             iterator, doneDeferred = taskObj
             try:
-                result = iterator.next()
+                result = next(iterator)
             except StopIteration:
                 self.iterators.remove(taskObj)
                 doneDeferred.callback(iterator)
--- twisted/internet/tcp.py (original)
+++ twisted/internet/tcp.py (refactored)
@@ -147,13 +147,14 @@
             Connection.startWriting(self)
             Connection.stopReading(self)
             return
-        except SSL.SysCallError, (retval, desc):
+        except SSL.SysCallError as xxx_todo_changeme:
+            (retval, desc) = xxx_todo_changeme.args
             if ((retval == -1 and desc == 'Unexpected EOF')
                 or retval > 0):
                 return main.CONNECTION_LOST
             log.err()
             return main.CONNECTION_LOST
-        except SSL.Error, e:
+        except SSL.Error as e:
             return e
 
     def doWrite(self):
@@ -191,14 +192,14 @@
             return 0
         except SSL.ZeroReturnError:
             return main.CONNECTION_LOST
-        except SSL.SysCallError, e:
+        except SSL.SysCallError as e:
             if e[0] == -1 and data == "":
                 # errors when writing empty strings are expected
                 # and can be ignored
                 return 0
             else:
                 return main.CONNECTION_LOST
-        except SSL.Error, e:
+        except SSL.Error as e:
             return e
 
 
@@ -247,7 +248,7 @@
         # shutdown)
         try:
             os.write(self.socket.fileno(), '')
-        except OSError, se:
+        except OSError as se:
             if se.args[0] in (EINTR, EWOULDBLOCK, ENOBUFS):
                 return 0
             # Write error, socket gone
@@ -265,7 +266,7 @@
                 #              "please upgrade to ver 0.XX", category=UserWarning)
                 self.socket.shutdown()
                 done = True
-        except SSL.Error, e:
+        except SSL.Error as e:
             return e
 
         if done:
@@ -453,7 +454,7 @@
         """
         try:
             data = self.socket.recv(self.bufferSize)
-        except socket.error, se:
+        except socket.error as se:
             if se.args[0] == EWOULDBLOCK:
                 return
             else:
@@ -475,7 +476,7 @@
             # Limit length of buffer to try to send, because some OSes are too
             # stupid to do so themselves (ahem windows)
             return self.socket.send(buffer(data, 0, self.SEND_LIMIT))
-        except socket.error, se:
+        except socket.error as se:
             if se.args[0] == EINTR:
                 return self.writeSomeData(data)
             elif se.args[0] in (EWOULDBLOCK, ENOBUFS):
@@ -643,7 +644,7 @@
         # cleaned up some day, though.
         try:
             connectResult = self.socket.connect_ex(self.realAddress)
-        except socket.error, se:
+        except socket.error as se:
             connectResult = se.args[0]
         if connectResult:
             if connectResult == EISCONN:
@@ -697,13 +698,13 @@
 
         try:
             skt = self.createInternetSocket()
-        except socket.error, se:
+        except socket.error as se:
             err = error.ConnectBindError(se[0], se[1])
             whenDone = None
         if whenDone and bindAddress is not None:
             try:
                 skt.bind(bindAddress)
-            except socket.error, se:
+            except socket.error as se:
                 err = error.ConnectBindError(se[0], se[1])
                 whenDone = None
         self._finishInit(whenDone, skt, err, reactor)
@@ -856,8 +857,8 @@
         try:
             skt = self.createInternetSocket()
             skt.bind((self.interface, self.port))
-        except socket.error, le:
-            raise CannotListenError, (self.interface, self.port, le)
+        except socket.error as le:
+            raise CannotListenError(self.interface, self.port, le)
 
         # Make sure that if we listened on port 0, we update that to
         # reflect what the OS actually assigned us.
@@ -877,7 +878,8 @@
         self.startReading()
 
 
-    def _buildAddr(self, (host, port)):
+    def _buildAddr(self, xxx_todo_changeme1):
+        (host, port) = xxx_todo_changeme1
         return address._ServerFactoryIPv4Address('TCP', host, port)
 
 
@@ -901,7 +903,7 @@
                     return
                 try:
                     skt, addr = self.socket.accept()
-                except socket.error, e:
+                except socket.error as e:
                     if e.args[0] in (EWOULDBLOCK, EAGAIN):
                         self.numberAccepts = i
                         break
@@ -1019,10 +1021,10 @@
 class Connector(base.BaseConnector):
     def __init__(self, host, port, factory, timeout, bindAddress, reactor=None):
         self.host = host
-        if isinstance(port, types.StringTypes):
+        if isinstance(port, str):
             try:
                 port = socket.getservbyname(port, 'tcp')
-            except socket.error, e:
+            except socket.error as e:
                 raise error.ServiceNameUnknownError(string="%s (%r)" % (e, port))
         self.port = port
         self.bindAddress = bindAddress
--- twisted/internet/threads.py (original)
+++ twisted/internet/threads.py (refactored)
@@ -9,7 +9,7 @@
 Maintainer: Itamar Shtull-Trauring
 """
 
-import Queue
+import queue
 
 from twisted.python import failure
 from twisted.internet import defer
@@ -104,7 +104,7 @@
     @return: the result of the callback chain.
     @raise: any error raised during the callback chain.
     """
-    queue = Queue.Queue()
+    queue = queue.Queue()
     def _callFromThread():
         result = defer.maybeDeferred(f, *a, **kw)
         result.addBoth(queue.put)
--- twisted/internet/tksupport.py (original)
+++ twisted/internet/tksupport.py (refactored)
@@ -23,7 +23,7 @@
 """
 
 # system imports
-import Tkinter, tkSimpleDialog, tkMessageBox
+import tkinter, tkSimpleDialog, tkMessageBox
 
 # twisted imports
 from twisted.python import log
--- twisted/internet/udp.py (original)
+++ twisted/internet/udp.py (refactored)
@@ -87,8 +87,8 @@
         try:
             skt = self.createInternetSocket()
             skt.bind((self.interface, self.port))
-        except socket.error, le:
-            raise error.CannotListenError, (self.interface, self.port, le)
+        except socket.error as le:
+            raise error.CannotListenError(self.interface, self.port, le)
 
         # Make sure that if we listened on port 0, we update that to
         # reflect what the OS actually assigned us.
@@ -111,7 +111,7 @@
         while read < self.maxThroughput:
             try:
                 data, addr = self.socket.recvfrom(self.maxPacketSize)
-            except socket.error, se:
+            except socket.error as se:
                 no = se.args[0]
                 if no in (EAGAIN, EINTR, EWOULDBLOCK):
                     return
@@ -137,12 +137,12 @@
             assert addr in (None, self._connectedAddr)
             try:
                 return self.socket.send(datagram)
-            except socket.error, se:
+            except socket.error as se:
                 no = se.args[0]
                 if no == EINTR:
                     return self.write(datagram)
                 elif no == EMSGSIZE:
-                    raise error.MessageLengthError, "message too long"
+                    raise error.MessageLengthError("message too long")
                 elif no == ECONNREFUSED:
                     self.protocol.connectionRefused()
                 else:
@@ -153,12 +153,12 @@
                 warnings.warn("Please only pass IPs to write(), not hostnames", DeprecationWarning, stacklevel=2)
             try:
                 return self.socket.sendto(datagram, addr)
-            except socket.error, se:
+            except socket.error as se:
                 no = se.args[0]
                 if no == EINTR:
                     return self.write(datagram, addr)
                 elif no == EMSGSIZE:
-                    raise error.MessageLengthError, "message too long"
+                    raise error.MessageLengthError("message too long")
                 elif no == ECONNREFUSED:
                     # in non-connected UDP ECONNREFUSED is platform dependent, I think
                     # and the info is not necessarily useful. Nevertheless maybe we
@@ -173,9 +173,9 @@
     def connect(self, host, port):
         """'Connect' to remote server."""
         if self._connectedAddr:
-            raise RuntimeError, "already connected, reconnecting is not currently supported (talk to itamar if you want this)"
+            raise RuntimeError("already connected, reconnecting is not currently supported (talk to itamar if you want this)")
         if not abstract.isIPAddress(host):
-            raise ValueError, "please pass only IP addresses, not domain names"
+            raise ValueError("please pass only IP addresses, not domain names")
         self._connectedAddr = (host, port)
         self.socket.connect((host, port))
 
@@ -239,7 +239,8 @@
 
     implements(interfaces.IUDPConnectedTransport)
 
-    def __init__(self, (remotehost, remoteport), port, proto, interface='', maxPacketSize=8192, reactor=None):
+    def __init__(self, xxx_todo_changeme, port, proto, interface='', maxPacketSize=8192, reactor=None):
+        (remotehost, remoteport) = xxx_todo_changeme
         Port.__init__(self, port, proto, interface, maxPacketSize, reactor)
         self.remotehost = remotehost
         self.remoteport = remoteport
@@ -271,7 +272,7 @@
                 data, addr = self.socket.recvfrom(self.maxPacketSize)
                 read += len(data)
                 self.protocol.datagramReceived(data)
-            except socket.error, se:
+            except socket.error as se:
                 no = se.args[0]
                 if no in (EAGAIN, EINTR, EWOULDBLOCK):
                     return
@@ -286,12 +287,12 @@
         """Write a datagram."""
         try:
             return self.socket.send(data)
-        except socket.error, se:
+        except socket.error as se:
             no = se.args[0]
             if no == EINTR:
                 return self.write(data)
             elif no == EMSGSIZE:
-                raise error.MessageLengthError, "message too long"
+                raise error.MessageLengthError("message too long")
             elif no == ECONNREFUSED:
                 self.protocol.connectionRefused()
             else:
@@ -351,7 +352,7 @@
             cmd = socket.IP_DROP_MEMBERSHIP
         try:
             self.socket.setsockopt(socket.IPPROTO_IP, cmd, addr + interface)
-        except socket.error, e:
+        except socket.error as e:
             return failure.Failure(error.MulticastJoinError(addr, interface, *e.args))
 
     def leaveGroup(self, addr, interface=""):
--- twisted/internet/unix.py (original)
+++ twisted/internet/unix.py (refactored)
@@ -44,7 +44,7 @@
     transport = Server
     lockFile = None
 
-    def __init__(self, fileName, factory, backlog=50, mode=0666, reactor=None, wantPID = 0):
+    def __init__(self, fileName, factory, backlog=50, mode=0o666, reactor=None, wantPID = 0):
         tcp.Port.__init__(self, fileName, factory, backlog, reactor=reactor)
         self.mode = mode
         self.wantPID = wantPID
@@ -69,7 +69,7 @@
         if self.wantPID:
             self.lockFile = lockfile.FilesystemLock(self.port + ".lock")
             if not self.lockFile.lock():
-                raise CannotListenError, (None, self.port, "Cannot acquire lock")
+                raise CannotListenError(None, self.port, "Cannot acquire lock")
             else:
                 if not self.lockFile.clean:
                     try:
@@ -87,8 +87,8 @@
         try:
             skt = self.createInternetSocket()
             skt.bind(self.port)
-        except socket.error, le:
-            raise CannotListenError, (None, self.port, le)
+        except socket.error as le:
+            raise CannotListenError(None, self.port, le)
         else:
             # Make the socket readable and writable to the world.
             try:
@@ -156,7 +156,7 @@
 
     addressFamily = socket.AF_UNIX
 
-    def __init__(self, addr, proto, maxPacketSize=8192, mode=0666, reactor=None):
+    def __init__(self, addr, proto, maxPacketSize=8192, mode=0o666, reactor=None):
         """Initialize with address to listen on.
         """
         udp.Port.__init__(self, addr, proto, maxPacketSize=maxPacketSize, reactor=reactor)
@@ -177,8 +177,8 @@
             skt = self.createInternetSocket() # XXX: haha misnamed method
             if self.port:
                 skt.bind(self.port)
-        except socket.error, le:
-            raise error.CannotListenError, (None, self.port, le)
+        except socket.error as le:
+            raise error.CannotListenError(None, self.port, le)
         if self.port:
             try:
                 os.chmod(self.port, self.mode)
@@ -192,12 +192,12 @@
         """Write a datagram."""
         try:
             return self.socket.sendto(datagram, address)
-        except socket.error, se:
+        except socket.error as se:
             no = se.args[0]
             if no == EINTR:
                 return self.write(datagram, address)
             elif no == EMSGSIZE:
-                raise error.MessageLengthError, "message too long"
+                raise error.MessageLengthError("message too long")
             elif no == EAGAIN:
                 # oh, well, drop the data. The only difference from UDP
                 # is that UDP won't ever notice.
@@ -236,7 +236,7 @@
     implementsOnly(interfaces.IUNIXDatagramConnectedTransport,
                    *(implementedBy(base.BasePort)))
 
-    def __init__(self, addr, proto, maxPacketSize=8192, mode=0666, bindAddress=None, reactor=None):
+    def __init__(self, addr, proto, maxPacketSize=8192, mode=0o666, bindAddress=None, reactor=None):
         assert isinstance(proto, protocol.ConnectedDatagramProtocol)
         DatagramPort.__init__(self, bindAddress, proto, maxPacketSize, mode, reactor)
         self.remoteaddr = addr
@@ -262,7 +262,7 @@
                 data, addr = self.socket.recvfrom(self.maxPacketSize)
                 read += len(data)
                 self.protocol.datagramReceived(data)
-            except socket.error, se:
+            except socket.error as se:
                 no = se.args[0]
                 if no in (EAGAIN, EINTR, EWOULDBLOCK):
                     return
@@ -277,12 +277,12 @@
         """Write a datagram."""
         try:
             return self.socket.send(data)
-        except socket.error, se:
+        except socket.error as se:
             no = se.args[0]
             if no == EINTR:
                 return self.write(data)
             elif no == EMSGSIZE:
-                raise error.MessageLengthError, "message too long"
+                raise error.MessageLengthError("message too long")
             elif no == ECONNREFUSED:
                 self.protocol.connectionRefused()
             elif no == EAGAIN:
--- twisted/internet/utils.py (original)
+++ twisted/internet/utils.py (refactored)
@@ -12,9 +12,9 @@
 from twisted.python import failure, util as tputil
 
 try:
-    import cStringIO as StringIO
+    import io as StringIO
 except ImportError:
-    import StringIO
+    import io
 
 def _callProtocolWithDeferred(protocol, executable, args, env, path, reactor=None):
     if reactor is None:
@@ -64,7 +64,7 @@
 
     def __init__(self, deferred, errortoo=0):
         self.deferred = deferred
-        self.s = StringIO.StringIO()
+        self.s = io.StringIO()
         if errortoo:
             self.errReceived = self.errReceivedIsGood
         else:
@@ -143,8 +143,8 @@
 
     def __init__(self, deferred):
         self.deferred = deferred
-        self.outBuf = StringIO.StringIO()
-        self.errBuf = StringIO.StringIO()
+        self.outBuf = io.StringIO()
+        self.errBuf = io.StringIO()
         self.outReceived = self.outBuf.write
         self.errReceived = self.errBuf.write
 
@@ -192,7 +192,7 @@
     except:
         exc_info = sys.exc_info()
         _resetWarningFilters(None, addedFilters)
-        raise exc_info[0], exc_info[1], exc_info[2]
+        raise exc_info[0](exc_info[1]).with_traceback(exc_info[2])
     else:
         if isinstance(result, defer.Deferred):
             result.addBoth(_resetWarningFilters, addedFilters)
--- twisted/internet/win32eventreactor.py (original)
+++ twisted/internet/win32eventreactor.py (refactored)
@@ -147,11 +147,11 @@
 
 
     def getReaders(self):
-        return self._reads.keys()
+        return list(self._reads.keys())
 
 
     def getWriters(self):
-        return self._writes.keys()
+        return list(self._writes.keys())
 
 
     def doWaitForMultipleEvents(self, timeout):
@@ -168,14 +168,14 @@
             return
 
         canDoMoreWrites = 0
-        for fd in self._writes.keys():
+        for fd in list(self._writes.keys()):
             if log.callWithLogger(fd, self._runWrite, fd):
                 canDoMoreWrites = 1
 
         if canDoMoreWrites:
             timeout = 0
 
-        handles = self._events.keys() or [self.dummyEvent]
+        handles = list(self._events.keys()) or [self.dummyEvent]
         val = MsgWaitForMultipleObjects(handles, 0, timeout, QS_ALLINPUT | QS_ALLEVENTS)
         if val == WAIT_TIMEOUT:
             return
@@ -237,7 +237,7 @@
 def install():
     threadable.init(1)
     r = Win32Reactor()
-    import main
+    from . import main
     main.installReactor(r)
 
 
--- twisted/internet/wxreactor.py (original)
+++ twisted/internet/wxreactor.py (refactored)
@@ -25,7 +25,7 @@
 Maintainer: Itamar Shtull-Trauring
 """
 
-import Queue
+import queue
 try:
     from wx import PySimpleApp as wxPySimpleApp, CallAfter as wxCallAfter, \
          Timer as wxTimer
@@ -118,7 +118,7 @@
         """
         Start the reactor.
         """
-        self._postQueue = Queue.Queue()
+        self._postQueue = queue.Queue()
         if not hasattr(self, "wxapp"):
             log.msg("registerWxApp() was not called on reactor, "
                     "registering my own wxApp instance.")
@@ -157,7 +157,7 @@
             while 1:
                 try:
                     f = self._postQueue.get(timeout=0.01)
-                except Queue.Empty:
+                except queue.Empty:
                     continue
                 else:
                     if f is None:
--- twisted/internet/iocpreactor/abstract.py (original)
+++ twisted/internet/iocpreactor/abstract.py (refactored)
@@ -282,7 +282,7 @@
 
         The data is buffered until his file descriptor is ready for writing.
         """
-        if isinstance(data, unicode): # no, really, I mean it
+        if isinstance(data, str): # no, really, I mean it
             raise TypeError("Data must not be unicode")
         if not self.connected or self._writeDisconnected:
             return
--- twisted/internet/iocpreactor/reactor.py (original)
+++ twisted/internet/iocpreactor/reactor.py (refactored)
@@ -27,7 +27,7 @@
 EVENTS_PER_LOOP = 1000 # XXX: what's a good value here?
 
 # keys to associate with normal and waker events
-KEY_NORMAL, KEY_WAKEUP = range(2)
+KEY_NORMAL, KEY_WAKEUP = list(range(2))
 
 _NO_GETHANDLE = error.ConnectionFdescWentAway(
                     'Handler has no getFileHandle method')
--- twisted/internet/iocpreactor/tcp.py (original)
+++ twisted/internet/iocpreactor/tcp.py (refactored)
@@ -139,17 +139,17 @@
         try:
             try:
                 skt = reactor.createSocket(self.addressFamily, self.socketType)
-            except socket.error, se:
+            except socket.error as se:
                 raise error.ConnectBindError(se[0], se[1])
             else:
                 try:
                     skt.bind(bindAddress)
-                except socket.error, se:
+                except socket.error as se:
                     raise error.ConnectBindError(se[0], se[1])
                 self.socket = skt
                 Connection.__init__(self, skt, None, reactor)
                 reactor.callLater(0, self.resolveAddress)
-        except error.ConnectBindError, err:
+        except error.ConnectBindError as err:
             reactor.callLater(0, self.failIfNotConnected, err)
 
 
@@ -361,8 +361,8 @@
                                             self.socketType)
             # TODO: resolve self.interface if necessary
             skt.bind((self.interface, self.port))
-        except socket.error, le:
-            raise error.CannotListenError, (self.interface, self.port, le)
+        except socket.error as le:
+            raise error.CannotListenError(self.interface, self.port, le)
 
         self.addrLen = _iocp.maxAddrLen(skt.fileno())
 
--- twisted/internet/iocpreactor/udp.py (original)
+++ twisted/internet/iocpreactor/udp.py (refactored)
@@ -92,8 +92,8 @@
         try:
             skt = self.createSocket()
             skt.bind((self.interface, self.port))
-        except socket.error, le:
-            raise error.CannotListenError, (self.interface, self.port, le)
+        except socket.error as le:
+            raise error.CannotListenError(self.interface, self.port, le)
 
         # Make sure that if we listened on port 0, we update that to
         # reflect what the OS actually assigned us.
@@ -165,12 +165,12 @@
             assert addr in (None, self._connectedAddr)
             try:
                 return self.socket.send(datagram)
-            except socket.error, se:
+            except socket.error as se:
                 no = se.args[0]
                 if no == errno.WSAEINTR:
                     return self.write(datagram)
                 elif no == errno.WSAEMSGSIZE:
-                    raise error.MessageLengthError, "message too long"
+                    raise error.MessageLengthError("message too long")
                 elif no in (errno.WSAECONNREFUSED, errno.WSAECONNRESET,
                             ERROR_CONNECTION_REFUSED, ERROR_PORT_UNREACHABLE):
                     self.protocol.connectionRefused()
@@ -183,12 +183,12 @@
                               DeprecationWarning, stacklevel=2)
             try:
                 return self.socket.sendto(datagram, addr)
-            except socket.error, se:
+            except socket.error as se:
                 no = se.args[0]
                 if no == errno.WSAEINTR:
                     return self.write(datagram, addr)
                 elif no == errno.WSAEMSGSIZE:
-                    raise error.MessageLengthError, "message too long"
+                    raise error.MessageLengthError("message too long")
                 elif no in (errno.WSAECONNREFUSED, errno.WSAECONNRESET,
                             ERROR_CONNECTION_REFUSED, ERROR_PORT_UNREACHABLE):
                     # in non-connected UDP ECONNREFUSED is platform dependent,
@@ -212,7 +212,7 @@
                 "already connected, reconnecting is not currently supported "
                 "(talk to itamar if you want this)")
         if not isIPAddress(host):
-            raise ValueError, "please pass only IP addresses, not domain names"
+            raise ValueError("please pass only IP addresses, not domain names")
         self._connectedAddr = (host, port)
         self.socket.connect((host, port))
 
@@ -350,7 +350,7 @@
             cmd = socket.IP_DROP_MEMBERSHIP
         try:
             self.socket.setsockopt(socket.IPPROTO_IP, cmd, addr + interface)
-        except socket.error, e:
+        except socket.error as e:
             return failure.Failure(error.MulticastJoinError(addr, interface,
                                                             *e.args))
 
--- twisted/internet/test/test_process.py (original)
+++ twisted/internet/test/test_process.py (refactored)
@@ -113,9 +113,10 @@
             reactor.spawnProcess, Exiter(), sys.executable,
             [sys.executable, "-c", source], usePTY=self.usePTY)
 
-        def cbExited((failure,)):
+        def cbExited(xxx_todo_changeme):
             # Trapping implicitly verifies that it's a Failure (rather than
             # an exception) and explicitly makes sure it's the right type.
+            (failure,) = xxx_todo_changeme
             failure.trap(ProcessTerminated)
             err = failure.value
             if platform.isWindows():
@@ -238,7 +239,8 @@
              self.keepStdioOpenArg],
             usePTY=self.usePTY)
 
-        def cbEnded((failure,)):
+        def cbEnded(xxx_todo_changeme1):
+            (failure,) = xxx_todo_changeme1
             failure.trap(ProcessDone)
             self.assertEqual(set(lost), set([0, 1, 2]))
         ended.addCallback(cbEnded)
@@ -285,7 +287,8 @@
              self.keepStdioOpenArg],
             usePTY=self.usePTY)
 
-        def cbExited((failure,)):
+        def cbExited(xxx_todo_changeme2):
+            (failure,) = xxx_todo_changeme2
             failure.trap(ProcessDone)
             msg('cbExited; lost = %s' % (lost,))
             self.assertEqual(lost, [])
--- twisted/internet/test/test_unix.py (original)
+++ twisted/internet/test/test_unix.py (refactored)
@@ -37,7 +37,7 @@
         Assert that the mode of the created unix socket is set to the mode
         specified to the reactor method.
         """
-        mode = 0600
+        mode = 0o600
         reactor = self.buildReactor()
         unixPort = getattr(reactor, methodName)(path, factory, mode=mode)
         unixPort.stopListening()
@@ -56,7 +56,7 @@
             _deprecatedModeMessage % dict(
                 interface=interfaceName, method=methodName),
             __file__,
-            lambda: method(path, factory, mode=0246))
+            lambda: method(path, factory, mode=0o246))
         port.stopListening()
 
 
--- twisted/lore/default.py (original)
+++ twisted/lore/default.py (refactored)
@@ -2,7 +2,7 @@
 # See LICENSE for details.
 
 #
-from __future__ import nested_scopes
+
 
 from twisted.lore import tree, latex, lint, process
 from twisted.web import sux, microdom
@@ -21,9 +21,9 @@
         try:
             fp = open(options['template'])
             templ = microdom.parse(fp)
-        except IOError, e:
+        except IOError as e:
             raise process.NoProcessorError(e.filename+": "+e.strerror)
-        except sux.ParseError, e:
+        except sux.ParseError as e:
             raise process.NoProcessorError(str(e))
         df = lambda file, linkrel: self.getDoFile()(file, linkrel, options['ext'],
                                                     options['baseurl'], templ, options, filenameGenerator)
@@ -37,7 +37,7 @@
 
     def generate_latex(self, options, filenameGenerator=None):
         spitter = self.latexSpitters[None]
-        for (key, value) in self.latexSpitters.items():
+        for (key, value) in list(self.latexSpitters.items()):
             if key and options.get(key):
                spitter = value
         df = lambda file, linkrel: latex.convertFile(file, spitter)
--- twisted/lore/docbook.py (original)
+++ twisted/lore/docbook.py (refactored)
@@ -3,7 +3,7 @@
 
 # 
 
-from cStringIO import StringIO
+from io import StringIO
 import os, re, cgi
 from twisted.python import text
 from twisted.web import domhelpers, microdom
--- twisted/lore/htmlbook.py (original)
+++ twisted/lore/htmlbook.py (refactored)
@@ -24,7 +24,7 @@
         Index = self.Index
 
         if filename:
-            execfile(filename)
+            exec(open(filename).read())
 
     def getFiles(self):
         return [c[0] for c in self.chapters]
--- twisted/lore/indexer.py (original)
+++ twisted/lore/indexer.py (refactored)
@@ -12,7 +12,7 @@
 
 def addEntry(filename, anchor, text, reference):
     global entries
-    if not entries.has_key(text):
+    if text not in entries:
         entries[text] = []
     entries[text].append((filename, anchor, reference))
 
--- twisted/lore/latex.py (original)
+++ twisted/lore/latex.py (refactored)
@@ -6,11 +6,11 @@
 from twisted.web import microdom, domhelpers
 from twisted.python import text, procutils
 import os, os.path, re, string
-from cStringIO import StringIO
-
-import urlparse
-
-import tree
+from io import StringIO
+
+import urllib.parse
+
+from . import tree
 
 escapingRE = re.compile(r'([\[\]#$%&_{}^~\\])')
 lowerUpperRE = re.compile(r'([a-z])([A-Z])')
@@ -50,7 +50,7 @@
     if hasattr(node, 'eref'):
         return writer(entities.get(node.eref, ''))
     if hasattr(node, 'data'):
-        return writer(filter(node.data))
+        return writer(list(filter(node.data)))
     for child in node.childNodes:
         getLatexText(child, writer, filter, entities)
 
@@ -202,7 +202,7 @@
     def visitNode_a_listing(self, node):
         fileName = os.path.join(self.currDir, node.getAttribute('href'))
         self.writer('\\begin{verbatim}\n')
-        lines = map(string.rstrip, open(fileName).readlines())
+        lines = list(map(string.rstrip, open(fileName).readlines()))
         lines = lines[int(node.getAttribute('skipLines', 0)):]
         self.writer(text.removeLeadingTrailingBlanks('\n'.join(lines)))
         self.writer('\\end{verbatim}')
@@ -219,7 +219,7 @@
     def visitNode_a_href(self, node):
         supported_schemes=['http', 'https', 'ftp', 'mailto']
         href = node.getAttribute('href')
-        if urlparse.urlparse(href)[0] in supported_schemes:
+        if urllib.parse.urlparse(href)[0] in supported_schemes:
             text = domhelpers.getNodeText(node)
             self.visitNodeDefault(node)
             if text != href:
@@ -362,7 +362,7 @@
     start_q = "``"
     end_q = "''"
 
-    writeNodeData = LatexSpitter.writeNodeData.im_func
+    writeNodeData = LatexSpitter.writeNodeData.__func__
 
 
 class FootnoteLatexSpitter(LatexSpitter):
--- twisted/lore/lint.py (original)
+++ twisted/lore/lint.py (refactored)
@@ -7,7 +7,7 @@
 from twisted.web import domhelpers, microdom
 from twisted.python import reflect
 
-import parser, urlparse, os.path
+import parser, urllib.parse, os.path
 
 # parser.suite in Python 2.3 raises SyntaxError, <2.3 raises parser.ParserError
 parserErrors = (SyntaxError, parser.ParserError)
@@ -26,7 +26,7 @@
         if hlint != 'off':
             self.hadErrors = 1
             pos = getattr(element, '_markpos', None) or (0, 0)
-            print "%s:%s:%s: %s" % ((filename,)+pos+(error,))
+            print("%s:%s:%s: %s" % ((filename,)+pos+(error,)))
 
 
 class DefaultTagChecker(TagChecker):
@@ -120,18 +120,18 @@
                     # Fix < and >
                     text = text.replace('&gt;', '>').replace('&lt;', '<')
                     # Strip blank lines
-                    lines = filter(None,[l.rstrip() for l in text.split('\n')])
+                    lines = [_f for _f in [l.rstrip() for l in text.split('\n')] if _f]
                     # Strip leading space
                     while not [1 for line in lines if line[:1] not in ('',' ')]:
                         lines = [line[1:] for line in lines]
                     text = '\n'.join(lines) + '\n'
                     try:
                         parser.suite(text)
-                    except parserErrors, e:
+                    except parserErrors as e:
                         # Pretend the "..." idiom is syntactically valid
                         text = text.replace("...","'...'")
                         parser.suite(text)
-                except parserErrors, e:
+                except parserErrors as e:
                     self._reportError(filename, node, 
                                       'invalid python code:' + str(e))
 
@@ -147,7 +147,7 @@
             if not node.hasAttribute('href'):
                 continue
             text = domhelpers.getNodeText(node)
-            proto = urlparse.urlparse(text)[0]
+            proto = urllib.parse.urlparse(text)[0]
             if proto and ' ' not in text:
                 if text != node.getAttribute('href',''):
                     self._reportError(filename, node, 
@@ -160,7 +160,7 @@
                                   node.getAttribute('href'))
                 lines = open(fn).readlines()
                 lines = lines[int(node.getAttribute('skipLines', 0)):]
-                for line, num in zip(lines, range(len(lines))):
+                for line, num in zip(lines, list(range(len(lines)))):
                     if line.count('59 Temple Place, Suite 330, Boston'):
                         self._reportError(filename, node,
                             'included source file %s has licence boilerplate.'
--- twisted/lore/lmath.py (original)
+++ twisted/lore/lmath.py (refactored)
@@ -2,7 +2,7 @@
 # See LICENSE for details.
 
 #
-from __future__ import nested_scopes
+
 
 import os, tempfile
 from twisted.web import domhelpers, microdom
--- twisted/lore/nevowlore.py (original)
+++ twisted/lore/nevowlore.py (refactored)
@@ -36,15 +36,15 @@
 def parseStringAndReport(s):
     try:
         return microdom.parseString(s)
-    except microdom.MismatchedTags, e:
+    except microdom.MismatchedTags as e:
         raise process.ProcessingFailure(
               "%s:%s: begin mismatched tags <%s>/</%s>" %
                (e.begLine, e.begCol, e.got, e.expect),
               "%s:%s: end mismatched tags <%s>/</%s>" %
                (e.endLine, e.endCol, e.got, e.expect))
-    except microdom.ParseError, e:
+    except microdom.ParseError as e:
         raise process.ProcessingFailure("%s:%s:%s" % (e.line, e.col, e.message))
-    except IOError, e:
+    except IOError as e:
         raise process.ProcessingFailure(e.strerror)
 
 def ____wait(d):
@@ -70,7 +70,7 @@
 
     newFilename = outfileGenerator(filename, ext)
 
-    if options.has_key('nolore'):
+    if 'nolore' in options:
         f = open(newFilename, 'w')
         f.write(s)
         f.close()
@@ -100,9 +100,9 @@
         try:
             fp = open(options['template'])
             templ = microdom.parse(fp)
-        except IOError, e:
+        except IOError as e:
             raise process.NoProcessorError(e.filename+": "+e.strerror)
-        except sux.ParseError, e:
+        except sux.ParseError as e:
             raise process.NoProcessorError(str(e))
         df = lambda file, linkrel: self.getDoFile()(file, linkrel, options['ext'],
                                                     options['baseurl'], templ, options, filenameGenerator)
--- twisted/lore/process.py (original)
+++ twisted/lore/process.py (refactored)
@@ -4,8 +4,8 @@
 
 #
 import sys, os
-import tree #todo: get rid of this later
-import indexer
+from . import tree #todo: get rid of this later
+from . import indexer
 
 class NoProcessorError(Exception):
     pass
@@ -51,7 +51,7 @@
             self.percentdone((float(i) / len(self.walked)), fname)
             try:
                 self.df(fullpath, linkrel)
-            except ProcessingFailure, e:
+            except ProcessingFailure as e:
                 self.failures.append((fullpath, e))
         indexer.generateIndex()
         self.percentdone(1., None)
@@ -67,13 +67,13 @@
         sys.stdout.write(progstat)
         sys.stdout.flush()
         if fname is None:
-            print
+            print()
 
 class PlainReportingWalker(Walker):
 
     def percentdone(self, percent, fname):
         if fname:
-            print fname
+            print(fname)
 
 class NullReportingWalker(Walker):
 
@@ -114,7 +114,7 @@
     if config.get('ext'):
         ext = config['ext']
     else:
-        from default import htmlDefault
+        from .default import htmlDefault
         ext = htmlDefault['ext']
 
     return m(config, getFilenameGenerator(config, ext))
--- twisted/lore/slides.py (original)
+++ twisted/lore/slides.py (refactored)
@@ -41,7 +41,7 @@
 
     </html>
 """
-from __future__ import nested_scopes
+
 
 from twisted.lore import default
 from twisted.web import domhelpers, microdom
@@ -50,11 +50,11 @@
 from twisted.lore.latex import BaseLatexSpitter, LatexSpitter, processFile, \
                                getLatexText, HeadingLatexSpitter
 from twisted.lore.tree import getHeaders
-from tree import removeH1, fixAPI, fontifyPython, \
+from .tree import removeH1, fixAPI, fontifyPython, \
                      addPyListings, addHTMLListings, setTitle
 
 import os, os.path, re
-from cStringIO import StringIO
+from io import StringIO
 
 hacked_entities = { 'amp': ' &', 'gt': ' >', 'lt': ' <', 'quot': ' "',
                     'copy': ' (c)'}
@@ -266,16 +266,16 @@
 
     return slides
 
-from tree import makeSureDirectoryExists
+from .tree import makeSureDirectoryExists
 
 def getOutputFileName(originalFileName, outputExtension, index):
     return os.path.splitext(originalFileName)[0]+'-'+str(index) + outputExtension
 
 def doFile(filename, linkrel, ext, url, templ, options={}, outfileGenerator=getOutputFileName):    
-    from tree import parseFileAndReport
+    from .tree import parseFileAndReport
     doc = parseFileAndReport(filename)
     slides = munge(doc, templ, linkrel, os.path.dirname(filename), filename, ext, url, options)
-    for slide, index in zip(slides, range(len(slides))):
+    for slide, index in zip(slides, list(range(len(slides)))):
         newFilename = outfileGenerator(filename, ext, index)
         makeSureDirectoryExists(newFilename)
         f = open(newFilename, 'wb')
--- twisted/lore/texi.py (original)
+++ twisted/lore/texi.py (refactored)
@@ -3,7 +3,7 @@
 
 # 
 
-from cStringIO import StringIO
+from io import StringIO
 import os, re
 from twisted.python import text
 from twisted.web import domhelpers
--- twisted/lore/tree.py (original)
+++ twisted/lore/tree.py (refactored)
@@ -2,7 +2,7 @@
 # See LICENSE for details.
 
 
-import re, os, cStringIO, time, cgi, string, urlparse
+import re, os, io, time, cgi, string, urlparse
 from twisted import copyright
 from twisted.python import htmlizer, text
 from twisted.web import microdom, domhelpers
@@ -140,11 +140,11 @@
 
     @return: C{None}
     """
-    oldio = cStringIO.StringIO()
+    oldio = io.StringIO()
     latex.getLatexText(node, oldio.write,
                        entities={'lt': '<', 'gt': '>', 'amp': '&'})
-    oldio = cStringIO.StringIO(oldio.getvalue().strip()+'\n')
-    newio = cStringIO.StringIO()
+    oldio = io.StringIO(oldio.getvalue().strip()+'\n')
+    newio = io.StringIO()
     htmlizer.filter(oldio, newio, writer=htmlizer.SmallerHTMLWriter)
     newio.seek(0)
     newel = microdom.parse(newio).documentElement
@@ -178,10 +178,10 @@
     for node in domhelpers.findElementsWithAttribute(document, "class",
                                                      "py-listing"):
         filename = node.getAttribute("href")
-        outfile = cStringIO.StringIO()
-        lines = map(string.rstrip, open(os.path.join(dir, filename)).readlines())
+        outfile = io.StringIO()
+        lines = list(map(string.rstrip, open(os.path.join(dir, filename)).readlines()))
         data = '\n'.join(lines[int(node.getAttribute('skipLines', 0)):])
-        data = cStringIO.StringIO(text.removeLeadingTrailingBlanks(data))
+        data = io.StringIO(text.removeLeadingTrailingBlanks(data))
         htmlizer.filter(data, outfile, writer=htmlizer.SmallerHTMLWriter)
         val = outfile.getvalue()
         _replaceWithListing(node, val, filename, "py-listing")
@@ -832,15 +832,15 @@
     """
     try:
         return microdom.parse(open(filename))
-    except microdom.MismatchedTags, e:
+    except microdom.MismatchedTags as e:
         raise process.ProcessingFailure(
               "%s:%s: begin mismatched tags <%s>/</%s>" %
                (e.begLine, e.begCol, e.got, e.expect),
               "%s:%s: end mismatched tags <%s>/</%s>" %
                (e.endLine, e.endCol, e.got, e.expect))
-    except microdom.ParseError, e:
+    except microdom.ParseError as e:
         raise process.ProcessingFailure("%s:%s:%s" % (e.line, e.col, e.message))
-    except IOError, e:
+    except IOError as e:
         raise process.ProcessingFailure(e.strerror + ", filename was '" + filename + "'")
 
 def makeSureDirectoryExists(filename):
--- twisted/lore/scripts/lore.py (original)
+++ twisted/lore/scripts/lore.py (refactored)
@@ -74,12 +74,12 @@
             try:
                 module = reflect.namedModule(input)
             except ImportError:
-                print '%s: no such input: %s' % (sys.argv[0], input)
+                print('%s: no such input: %s' % (sys.argv[0], input))
                 return
     try:
         return process.getProcessor(module, output, config)
-    except process.NoProcessorError, e:
-        print "%s: %s" % (sys.argv[0], e)
+    except process.NoProcessorError as e:
+        print("%s: %s" % (sys.argv[0], e))
 
 
 def getWalker(df, opt):
@@ -134,7 +134,7 @@
     if walker.failures:
         for (file, errors) in walker.failures:
             for error in errors:
-                print "%s:%s" % (file, error)
+                print("%s:%s" % (file, error))
         return 'Walker failures'
 
 
@@ -142,14 +142,14 @@
     opt = Options()
     try:
         opt.parseOptions()
-    except usage.UsageError, errortext:
-        print '%s: %s' % (sys.argv[0], errortext)
-        print '%s: Try --help for usage details.' % sys.argv[0]
+    except usage.UsageError as errortext:
+        print('%s: %s' % (sys.argv[0], errortext))
+        print('%s: Try --help for usage details.' % sys.argv[0])
         sys.exit(1)
 
     result = runGivenOptions(opt)
     if result:
-        print result
+        print(result)
         sys.exit(1)
 
 
--- twisted/lore/test/test_lore.py (original)
+++ twisted/lore/test/test_lore.py (refactored)
@@ -31,7 +31,7 @@
 #
 
 import os, shutil
-from StringIO import StringIO
+from io import StringIO
 
 from twisted.trial import unittest
 
@@ -78,7 +78,7 @@
         self.assertEqualsString(expected, act)
 
     def assertEqualsString(self, expected, act):
-        if len(expected) != len(act): print "Actual: " + act ##d
+        if len(expected) != len(act): print("Actual: " + act) ##d
         self.assertEquals(len(expected), len(act))
         for i in range(len(expected)):
             e = expected[i]
@@ -344,4 +344,4 @@
         out = StringIO()
         spitter = LatexSpitter(out.write)
         spitter.visitNode(dom)
-        self.assertEqual(out.getvalue(), u'\\index{name}\n')
+        self.assertEqual(out.getvalue(), '\\index{name}\n')
--- twisted/lore/test/test_man2lore.py (original)
+++ twisted/lore/test/test_man2lore.py (refactored)
@@ -6,7 +6,7 @@
 Tests for L{twisted.lore.man2lore}.
 """
 
-from StringIO import StringIO
+from io import StringIO
 
 from twisted.trial.unittest import TestCase
 
--- twisted/mail/alias.py (original)
+++ twisted/mail/alias.py (refactored)
@@ -35,7 +35,7 @@
         log.err(fmt % arg)
     else:
         user, alias = parts
-        result.setdefault(user.strip(), []).extend(map(str.strip, alias.split(',')))
+        result.setdefault(user.strip(), []).extend(list(map(str.strip, alias.split(','))))
 
 def loadAliasFile(domains, filename=None, fp=None):
     """Load a file containing email aliases.
@@ -85,7 +85,7 @@
             prev = line
     if prev:
         handle(result, prev, filename, i)
-    for (u, a) in result.items():
+    for (u, a) in list(result.items()):
         addr = smtp.Address(u)
         result[u] = AliasGroup(a, domains, u)
     return result
@@ -377,7 +377,7 @@
             o.connectionLost()
 
     def __str__(self):
-        return '<GroupWrapper %r>' % (map(str, self.objs),)
+        return '<GroupWrapper %r>' % (list(map(str, self.objs)),)
 
 
 
@@ -431,5 +431,5 @@
         r = []
         for a in self.aliases:
             r.append(a.resolve(aliasmap, memo))
-        return MultiWrapper(filter(None, r))
-
+        return MultiWrapper([_f for _f in r if _f])
+
--- twisted/mail/bounce.py (original)
+++ twisted/mail/bounce.py (refactored)
@@ -4,7 +4,7 @@
 # See LICENSE for details.
 
 
-import StringIO
+import io
 import rfc822
 import string
 import time
@@ -44,7 +44,7 @@
     messageID = smtp.messageid(uniq='bounce')
     ctime = time.ctime(time.time())
 
-    fp = StringIO.StringIO()
+    fp = io.StringIO()
     fp.write(BOUNCE_FORMAT % vars())
     orig = message.tell()
     message.seek(2, 0)
--- twisted/mail/imap4.py (original)
+++ twisted/mail/imap4.py (refactored)
@@ -30,9 +30,9 @@
 import email.Utils
 
 try:
-    import cStringIO as StringIO
+    import io as StringIO
 except:
-    import StringIO
+    import io
 
 from zope.interface import implements, Interface
 
@@ -82,7 +82,7 @@
         if start is self._empty:
             return
 
-        if isinstance(start, types.ListType):
+        if isinstance(start, list):
             self.ranges = start[:]
             self.clean()
         else:
@@ -189,7 +189,7 @@
 
             oldl,oldh = l,h
 
-        self.ranges = filter(None, self.ranges)
+        self.ranges = [_f for _f in self.ranges if _f]
 
     def __contains__(self, value):
         """
@@ -286,7 +286,7 @@
         if size > self._memoryFileLimit:
             self.data = tempfile.TemporaryFile()
         else:
-            self.data = StringIO.StringIO()
+            self.data = io.StringIO()
 
     def write(self, data):
         self.size -= len(data)
@@ -358,7 +358,7 @@
             names = parseNestedParens(L)
             N = len(names)
             if (N >= 1 and names[0] in self._1_RESPONSES or
-                N >= 2 and names[0] == 'OK' and isinstance(names[1], types.ListType) and names[1][0] in self._OK_RESPONSES):
+                N >= 2 and names[0] == 'OK' and isinstance(names[1], list) and names[1][0] in self._OK_RESPONSES):
                 send.append(L)
             elif N >= 3 and names[1] in self._2_RESPONSES:
                 if isinstance(names[2], list) and len(names[2]) >= 1 and names[2][0] == 'FLAGS' and 'FLAGS' not in self.args:
@@ -514,7 +514,7 @@
         self._queuedAsync = []
 
     def capabilities(self):
-        cap = {'AUTH': self.challengers.keys()}
+        cap = {'AUTH': list(self.challengers.keys())}
         if self.ctx and self.canStartTLS:
             if not self.startedTLS and interfaces.ISSLTransport(self.transport, None) is None:
                 cap['LOGINDISABLED'] = None
@@ -579,7 +579,7 @@
         f = getattr(self, 'parse_' + self.parseState)
         try:
             f(line)
-        except Exception, e:
+        except Exception as e:
             self.sendUntaggedResponse('BAD Server error: ' + str(e))
             log.err()
 
@@ -601,11 +601,11 @@
         cmd = cmd.upper()
         try:
             return self.dispatchCommand(tag, cmd, rest)
-        except IllegalClientResponse, e:
+        except IllegalClientResponse as e:
             self.sendBadResponse(tag, 'Illegal syntax: ' + str(e))
-        except IllegalOperation, e:
+        except IllegalOperation as e:
             self.sendNegativeResponse(tag, 'Illegal operation: ' + str(e))
-        except IllegalMailboxEncoding, e:
+        except IllegalMailboxEncoding as e:
             self.sendNegativeResponse(tag, 'Illegal mailbox name: ' + str(e))
 
     def parse_pending(self, line):
@@ -628,7 +628,7 @@
 
     def __doCommand(self, tag, handler, args, parseargs, line, uid):
         for (i, arg) in enumerate(parseargs):
-            if callable(arg):
+            if hasattr(arg, '__call__'):
                 parseargs = parseargs[i+1:]
                 maybeDeferred(arg, self, line).addCallback(
                     self.__cbDispatch, tag, handler, args,
@@ -646,7 +646,8 @@
         else:
             handler(*args)
 
-    def __cbDispatch(self, (arg, rest), tag, fn, args, parseargs, uid):
+    def __cbDispatch(self, xxx_todo_changeme, tag, fn, args, parseargs, uid):
+        (arg, rest) = xxx_todo_changeme
         args.append(arg)
         self.__doCommand(tag, fn, args, parseargs, rest, uid)
 
@@ -789,7 +790,7 @@
 
         try:
             return (parseIdList(arg), rest)
-        except IllegalIdentifierError, e:
+        except IllegalIdentifierError as e:
             raise IllegalClientResponse("Bad message number " + str(e))
 
     def arg_fetchatt(self, line):
@@ -907,7 +908,7 @@
 
     def listCapabilities(self):
         caps = ['IMAP4rev1']
-        for c, v in self.capabilities().iteritems():
+        for c, v in self.capabilities().items():
             if v is None:
                 caps.append(c)
             elif len(v):
@@ -960,7 +961,7 @@
     def _setupChallenge(self, chal, tag):
         try:
             challenge = chal.getChallenge()
-        except Exception, e:
+        except Exception as e:
             self.sendBadResponse(tag, 'Server error: ' + str(e))
         else:
             coded = base64.encodestring(challenge)[:-1]
@@ -986,7 +987,8 @@
                 (tag,), None, (tag,), None
             )
 
-    def __cbAuthResp(self, (iface, avatar, logout), tag):
+    def __cbAuthResp(self, xxx_todo_changeme1, tag):
+        (iface, avatar, logout) = xxx_todo_changeme1
         assert iface is IAccount, "IAccount is the only supported interface"
         self.account = avatar
         self.state = 'auth'
@@ -1056,7 +1058,8 @@
             )
         raise cred.error.UnauthorizedLogin()
 
-    def __cbLogin(self, (iface, avatar, logout), tag):
+    def __cbLogin(self, xxx_todo_changeme2, tag):
+        (iface, avatar, logout) = xxx_todo_changeme2
         if iface is not IAccount:
             self.sendBadResponse(tag, 'Server error: login returned unexpected value')
             log.err("__cbLogin called with %r, IAccount expected" % (iface,))
@@ -1088,7 +1091,7 @@
     select_NAMESPACE = auth_NAMESPACE
 
     def _parseMbox(self, name):
-        if isinstance(name, unicode):
+        if isinstance(name, str):
             return name
         try:
             return name.decode('imap4-utf-7')
@@ -1162,7 +1165,7 @@
         name = self._parseMbox(name)
         try:
             result = self.account.create(name)
-        except MailboxException, c:
+        except MailboxException as c:
             self.sendNegativeResponse(tag, str(c))
         except:
             self.sendBadResponse(tag, "Server error encountered while creating mailbox")
@@ -1183,7 +1186,7 @@
             return
         try:
             self.account.delete(name)
-        except MailboxException, m:
+        except MailboxException as m:
             self.sendNegativeResponse(tag, str(m))
         except:
             self.sendBadResponse(tag, "Server error encountered while deleting mailbox")
@@ -1195,7 +1198,7 @@
     select_DELETE = auth_DELETE
 
     def do_RENAME(self, tag, oldname, newname):
-        oldname, newname = [self._parseMbox(n) for n in oldname, newname]
+        oldname, newname = [self._parseMbox(n) for n in (oldname, newname)]
         if oldname.lower() == 'inbox' or newname.lower() == 'inbox':
             self.sendNegativeResponse(tag, 'You cannot rename the inbox, or rename another mailbox to inbox.')
             return
@@ -1203,7 +1206,7 @@
             self.account.rename(oldname, newname)
         except TypeError:
             self.sendBadResponse(tag, 'Invalid command syntax')
-        except MailboxException, m:
+        except MailboxException as m:
             self.sendNegativeResponse(tag, str(m))
         except:
             self.sendBadResponse(tag, "Server error encountered while renaming mailbox")
@@ -1218,7 +1221,7 @@
         name = self._parseMbox(name)
         try:
             self.account.subscribe(name)
-        except MailboxException, m:
+        except MailboxException as m:
             self.sendNegativeResponse(tag, str(m))
         except:
             self.sendBadResponse(tag, "Server error encountered while subscribing to mailbox")
@@ -1233,7 +1236,7 @@
         name = self._parseMbox(name)
         try:
             self.account.unsubscribe(name)
-        except MailboxException, m:
+        except MailboxException as m:
             self.sendNegativeResponse(tag, str(m))
         except:
             self.sendBadResponse(tag, "Server error encountered while unsubscribing from mailbox")
@@ -1256,7 +1259,7 @@
             if not sub or self.account.isSubscribed(name):
                 flags = box.getFlags()
                 delim = box.getHierarchicalDelimiter()
-                resp = (DontQuoteMe(cmdName), map(DontQuoteMe, flags), delim, name.encode('imap4-utf-7'))
+                resp = (DontQuoteMe(cmdName), list(map(DontQuoteMe, flags)), delim, name.encode('imap4-utf-7'))
                 self.sendUntaggedResponse(collapseNestedLists(resp))
         self.sendPositiveResponse(tag, '%s completed' % (cmdName,))
 
@@ -1294,7 +1297,7 @@
     select_STATUS = auth_STATUS
 
     def __cbStatus(self, status, tag, box):
-        line = ' '.join(['%s %s' % x for x in status.iteritems()])
+        line = ' '.join(['%s %s' % x for x in status.items()])
         self.sendUntaggedResponse('STATUS %s (%s)' % (box, line))
         self.sendPositiveResponse(tag, 'STATUS complete')
 
@@ -1424,7 +1427,7 @@
 
     def __cbSearch(self, result, tag, mbox, uid):
         if uid:
-            result = map(mbox.getUID, result)
+            result = list(map(mbox.getUID, result))
         ids = ' '.join([str(i) for i in result])
         self.sendUntaggedResponse('SEARCH ' + ids)
         self.sendPositiveResponse(tag, 'SEARCH completed')
@@ -1433,7 +1436,7 @@
         if searchResults is None:
             searchResults = []
         i = 0
-        for (i, (id, msg)) in zip(range(5), result):
+        for (i, (id, msg)) in zip(list(range(5)), result):
             if self.searchFilter(query, id, msg):
                 if uid:
                     searchResults.append(str(msg.getUID()))
@@ -1628,7 +1631,7 @@
         if self.blocked is None:
             self.blocked = []
         try:
-            id, msg = results.next()
+            id, msg = next(results)
         except StopIteration:
             # The idle timeout was suspended while we delivered results,
             # restore it now.
@@ -1834,7 +1837,7 @@
 
     def __cbStore(self, result, tag, mbox, uid, silent):
         if result and not silent:
-              for (k, v) in result.iteritems():
+              for (k, v) in result.items():
                   if uid:
                       uidstr = ' UID %d' % mbox.getUID(k)
                   else:
@@ -1938,7 +1941,7 @@
             self.sendUntaggedResponse(message='[READ-ONLY]', async=True)
 
     def flagsChanged(self, newFlags):
-        for (mId, flags) in newFlags.iteritems():
+        for (mId, flags) in newFlags.items():
             msg = '%d FETCH (FLAGS (%s))' % (mId, ' '.join(flags))
             self.sendUntaggedResponse(msg, async=True)
 
@@ -2078,7 +2081,7 @@
         if self.tags is not None:
             tags = self.tags
             self.tags = None
-            for cmd in tags.itervalues():
+            for cmd in tags.values():
                 if cmd is not None and cmd.defer is not None:
                     cmd.defer.errback(reason)
 
@@ -2158,7 +2161,7 @@
         if octets > self._memoryFileLimit:
             return tempfile.TemporaryFile()
         else:
-            return StringIO.StringIO()
+            return io.StringIO()
 
     def makeTag(self):
         tag = '%0.4X' % self.tagID
@@ -2256,7 +2259,7 @@
             elif L.find('READ-WRITE') != -1:
                 self.modeChanged(1)
             elif L.find('FETCH') != -1:
-                for (mId, fetched) in self.__cbFetch(([L], None)).iteritems():
+                for (mId, fetched) in self.__cbFetch(([L], None)).items():
                     sum = []
                     for f in fetched.get('FLAGS', []):
                         sum.append(f)
@@ -2304,7 +2307,8 @@
         d.addCallback(self.__cbCapabilities)
         return d
 
-    def __cbCapabilities(self, (lines, tagline)):
+    def __cbCapabilities(self, xxx_todo_changeme3):
+        (lines, tagline) = xxx_todo_changeme3
         caps = {}
         for rest in lines:
             rest = rest.split()[1:]
@@ -2338,7 +2342,8 @@
         d.addCallback(self.__cbLogout)
         return d
 
-    def __cbLogout(self, (lines, tagline)):
+    def __cbLogout(self, xxx_todo_changeme4):
+        (lines, tagline) = xxx_todo_changeme4
         self.transport.loseConnection()
         # We don't particularly care what the server said
         return None
@@ -2357,9 +2362,10 @@
         d.addCallback(self.__cbNoop)
         return d
 
-    def __cbNoop(self, (lines, tagline)):
+    def __cbNoop(self, xxx_todo_changeme5):
         # Conceivable, this is elidable.
         # It is, afterall, a no-op.
+        (lines, tagline) = xxx_todo_changeme5
         return lines
 
     def startTLS(self, contextFactory=None):
@@ -2432,13 +2438,13 @@
 
         if self.startedTLS:
             return defer.fail(NoSupportedAuthentication(
-                auths, self.authenticators.keys()))
+                auths, list(self.authenticators.keys())))
         else:
             def ebStartTLS(err):
                 err.trap(IMAP4Exception)
                 # We couldn't negotiate TLS for some reason
                 return defer.fail(NoSupportedAuthentication(
-                    auths, self.authenticators.keys()))
+                    auths, list(self.authenticators.keys())))
 
             d = self.startTLS()
             d.addErrback(ebStartTLS)
@@ -2467,7 +2473,7 @@
                               self.__cbContinueAuth, scheme,
                               secret)
                 return self.sendCommand(cmd)
-        raise NoSupportedAuthentication(auths, self.authenticators.keys())
+        raise NoSupportedAuthentication(auths, list(self.authenticators.keys()))
 
 
     def login(self, username, password):
@@ -2572,7 +2578,8 @@
         d.addCallback(self.__cbNamespace)
         return d
 
-    def __cbNamespace(self, (lines, last)):
+    def __cbNamespace(self, xxx_todo_changeme6):
+        (lines, last) = xxx_todo_changeme6
         for line in lines:
             parts = line.split(None, 1)
             if len(parts) == 2:
@@ -2659,9 +2666,10 @@
         d.addCallback(self.__cbSelect, 0)
         return d
 
-    def __cbSelect(self, (lines, tagline), rw):
+    def __cbSelect(self, xxx_todo_changeme7, rw):
         # In the absense of specification, we are free to assume:
         #   READ-WRITE access
+        (lines, tagline) = xxx_todo_changeme7
         datum = {'READ-WRITE': rw}
         lines.append(tagline)
         for parts in lines:
@@ -2837,12 +2845,13 @@
         d.addCallback(self.__cbList, 'LSUB')
         return d
 
-    def __cbList(self, (lines, last), command):
+    def __cbList(self, xxx_todo_changeme8, command):
+        (lines, last) = xxx_todo_changeme8
         results = []
         for L in lines:
             parts = parseNestedParens(L)
             if len(parts) != 4:
-                raise IllegalServerResponse, L
+                raise IllegalServerResponse(L)
             if parts[0] == command:
                 parts[1] = tuple(parts[1])
                 results.append(tuple(parts[1:]))
@@ -2876,7 +2885,8 @@
         d.addCallback(self.__cbStatus)
         return d
 
-    def __cbStatus(self, (lines, last)):
+    def __cbStatus(self, xxx_todo_changeme9):
+        (lines, last) = xxx_todo_changeme9
         status = {}
         for line in lines:
             parts = parseNestedParens(line)
@@ -2884,12 +2894,12 @@
                 items = parts[2]
                 items = [items[i:i+2] for i in range(0, len(items), 2)]
                 status.update(dict(items))
-        for k in status.keys():
+        for k in list(status.keys()):
             t = self.STATUS_TRANSFORMATIONS.get(k)
             if t:
                 try:
                     status[k] = t(status[k])
-                except Exception, e:
+                except Exception as e:
                     raise IllegalServerResponse('(%s %s): %s' % (k, status[k], str(e)))
         return status
 
@@ -2987,7 +2997,8 @@
         d.addCallback(self.__cbExpunge)
         return d
 
-    def __cbExpunge(self, (lines, last)):
+    def __cbExpunge(self, xxx_todo_changeme10):
+        (lines, last) = xxx_todo_changeme10
         ids = []
         for line in lines:
             parts = line.split(None, 1)
@@ -2996,7 +3007,7 @@
                     try:
                         ids.append(int(parts[0]))
                     except ValueError:
-                        raise IllegalServerResponse, line
+                        raise IllegalServerResponse(line)
         return ids
 
     def search(self, *queries, **kwarg):
@@ -3025,16 +3036,17 @@
         d.addCallback(self.__cbSearch)
         return d
 
-    def __cbSearch(self, (lines, end)):
+    def __cbSearch(self, xxx_todo_changeme11):
+        (lines, end) = xxx_todo_changeme11
         ids = []
         for line in lines:
             parts = line.split(None, 1)
             if len(parts) == 2:
                 if parts[0] == 'SEARCH':
                     try:
-                        ids.extend(map(int, parts[1].split()))
+                        ids.extend(list(map(int, parts[1].split())))
                     except ValueError:
-                        raise IllegalServerResponse, line
+                        raise IllegalServerResponse(line)
         return ids
 
     def fetchUID(self, messages, uid=0):
@@ -3350,7 +3362,8 @@
         d.addCallback(self.__cbFetch)
         return d
 
-    def __cbFetch(self, (lines, last)):
+    def __cbFetch(self, xxx_todo_changeme12):
+        (lines, last) = xxx_todo_changeme12
         flags = {}
         for line in lines:
             parts = line.split(None, 2)
@@ -3359,10 +3372,10 @@
                     try:
                         id = int(parts[0])
                     except ValueError:
-                        raise IllegalServerResponse, line
+                        raise IllegalServerResponse(line)
                     else:
                         data = parseNestedParens(parts[2])
-                        while len(data) == 1 and isinstance(data, types.ListType):
+                        while len(data) == 1 and isinstance(data, list):
                             data = data[0]
                         while data:
                             if len(data) < 2:
@@ -3370,9 +3383,9 @@
                             flags.setdefault(id, {})[data[0]] = data[1]
                             del data[:2]
                 else:
-                    print '(2)Ignoring ', parts
+                    print('(2)Ignoring ', parts)
             else:
-                print '(3)Ignoring ', parts
+                print('(3)Ignoring ', parts)
         return flags
 
     def fetchSpecific(self, messages, uid=0, headerType=None,
@@ -3425,7 +3438,7 @@
         fmt = '%s BODY%s[%s%s%s]%s'
         if headerNumber is None:
             number = ''
-        elif isinstance(headerNumber, types.IntType):
+        elif isinstance(headerNumber, int):
             number = str(headerNumber)
         else:
             number = '.'.join(headerNumber)
@@ -3452,7 +3465,8 @@
         d.addCallback(self.__cbFetchSpecific)
         return d
 
-    def __cbFetchSpecific(self, (lines, last)):
+    def __cbFetchSpecific(self, xxx_todo_changeme13):
+        (lines, last) = xxx_todo_changeme13
         info = {}
         for line in lines:
             parts = line.split(None, 2)
@@ -3461,7 +3475,7 @@
                     try:
                         id = int(parts[0])
                     except ValueError:
-                        raise IllegalServerResponse, line
+                        raise IllegalServerResponse(line)
                     else:
                         info[id] = parseNestedParens(parts[2])
         return info
@@ -3479,7 +3493,7 @@
             del terms['rfc822header']
             terms['rfc822.header'] = True
 
-        cmd = '%s (%s)' % (messages, ' '.join([s.upper() for s in terms.keys()]))
+        cmd = '%s (%s)' % (messages, ' '.join([s.upper() for s in list(terms.keys())]))
         d = self.sendCommand(Command(fetch, cmd, wantResponse=('FETCH',)))
         return d
 
@@ -3620,11 +3634,11 @@
                 if low == '*':
                     low = None
                 else:
-                    low = long(low)
+                    low = int(low)
                 if high == '*':
                     high = None
                 else:
-                    high = long(high)
+                    high = int(high)
                 res.extend((low, high))
             except ValueError:
                 raise IllegalIdentifierError(p)
@@ -3633,7 +3647,7 @@
                 if p == '*':
                     p = None
                 else:
-                    p = long(p)
+                    p = int(p)
             except ValueError:
                 raise IllegalIdentifierError(p)
             else:
@@ -3761,7 +3775,7 @@
     @return: The formatted query string
     """
     cmd = []
-    keys = kwarg.keys()
+    keys = list(kwarg.keys())
     if sorted:
         keys.sort()
     for k in keys:
@@ -3783,7 +3797,7 @@
 def Or(*args):
     """The disjunction of two or more queries"""
     if len(args) < 2:
-        raise IllegalQueryError, args
+        raise IllegalQueryError(args)
     elif len(args) == 2:
         return '(OR %s %s)' % args
     else:
@@ -3825,7 +3839,7 @@
     s = s.strip()
     result = []
     inQuote = inWord = start = 0
-    for (i, c) in zip(range(len(s)), s):
+    for (i, c) in zip(list(range(len(s))), s):
         if c == '"' and not inQuote:
             inQuote = 1
             start = i + 1
@@ -3883,14 +3897,14 @@
     """
     copy = []
     begun = None
-    listsList = [isinstance(s, types.ListType) for s in results]
-
-    pred = lambda e: isinstance(e, types.TupleType)
+    listsList = [isinstance(s, list) for s in results]
+
+    pred = lambda e: isinstance(e, tuple)
     tran = {
         0: lambda e: splitQuoted(''.join(e)),
         1: lambda e: [''.join([i[0] for i in e])]
     }
-    for (i, c, isList) in zip(range(len(results)), results, listsList):
+    for (i, c, isList) in zip(list(range(len(results))), results, listsList):
         if isList:
             if begun is not None:
                 copy.extend(splitOn(results[begun:i], pred, tran))
@@ -3940,7 +3954,7 @@
                 elif handleLiteral and c == '{':
                     end = s.find('}', i)
                     if end == -1:
-                        raise ValueError, "Malformed literal"
+                        raise ValueError("Malformed literal")
                     literalSize = int(s[i+1:end])
                     contentStack[-1].append((s[end+3:end+3+literalSize],))
                     i = end + 3 + literalSize
@@ -4018,9 +4032,9 @@
     for i in items:
         if i is None:
             pieces.extend([' ', 'NIL'])
-        elif isinstance(i, (DontQuoteMe, int, long)):
+        elif isinstance(i, (DontQuoteMe, int, int)):
             pieces.extend([' ', str(i)])
-        elif isinstance(i, types.StringTypes):
+        elif isinstance(i, str):
             if _needsLiteral(i):
                 pieces.extend([' ', '{', str(len(i)), '}', IMAP4Server.delimiter, i])
             else:
@@ -4317,15 +4331,15 @@
     ##
     def addMailbox(self, name, mbox = None):
         name = name.upper()
-        if self.mailboxes.has_key(name):
-            raise MailboxCollision, name
+        if name in self.mailboxes:
+            raise MailboxCollision(name)
         if mbox is None:
             mbox = self._emptyMailbox(name, self.allocateID())
         self.mailboxes[name] = mbox
         return 1
 
     def create(self, pathspec):
-        paths = filter(None, pathspec.split('/'))
+        paths = [_f for _f in pathspec.split('/') if _f]
         for accum in range(1, len(paths)):
             try:
                 self.addMailbox('/'.join(paths[:accum]))
@@ -4354,9 +4368,9 @@
         if r'\Noselect' in mbox.getFlags():
             # Check for hierarchically inferior mailboxes with this one
             # as part of their root.
-            for others in self.mailboxes.keys():
+            for others in list(self.mailboxes.keys()):
                 if others != name and others.startswith(name):
-                    raise MailboxException, "Hierarchically inferior mailboxes exist and \\Noselect is set"
+                    raise MailboxException("Hierarchically inferior mailboxes exist and \\Noselect is set")
         mbox.destroy()
 
         # iff there are no hierarchically inferior names, we will
@@ -4367,15 +4381,15 @@
     def rename(self, oldname, newname):
         oldname = oldname.upper()
         newname = newname.upper()
-        if not self.mailboxes.has_key(oldname):
-            raise NoSuchMailbox, oldname
+        if oldname not in self.mailboxes:
+            raise NoSuchMailbox(oldname)
 
         inferiors = self._inferiorNames(oldname)
         inferiors = [(o, o.replace(oldname, newname, 1)) for o in inferiors]
 
         for (old, new) in inferiors:
-            if self.mailboxes.has_key(new):
-                raise MailboxCollision, new
+            if new in self.mailboxes:
+                raise MailboxCollision(new)
 
         for (old, new) in inferiors:
             self.mailboxes[new] = self.mailboxes[old]
@@ -4383,7 +4397,7 @@
 
     def _inferiorNames(self, name):
         inferiors = []
-        for infname in self.mailboxes.keys():
+        for infname in list(self.mailboxes.keys()):
             if infname.startswith(name):
                 inferiors.append(infname)
         return inferiors
@@ -4399,7 +4413,7 @@
     def unsubscribe(self, name):
         name = name.upper()
         if name not in self.subscriptions:
-            raise MailboxException, "Not currently subscribed to " + name
+            raise MailboxException("Not currently subscribed to " + name)
         self.subscriptions.remove(name)
 
     def listMailboxes(self, ref, wildcard):
@@ -4497,7 +4511,7 @@
 
 
     size = str(msg.getSize())
-    unquotedAttrs = [(k, unquote(v)) for (k, v) in attrs.iteritems()]
+    unquotedAttrs = [(k, unquote(v)) for (k, v) in attrs.items()]
     result = [
         major, minor,                       # Main and Sub MIME types
         unquotedAttrs,                      # content-type parameter list
@@ -4545,7 +4559,7 @@
                 i += 1
         except IndexError:
             result.append(minor)
-            result.append(attrs.items())
+            result.append(list(attrs.items()))
 
             # XXX - I dunno if this is really right
             headers = msg.getHeaders(False, 'content-disposition', 'content-language')
@@ -4890,7 +4904,7 @@
 
 def _formatHeaders(headers):
     hdrs = [': '.join((k.title(), '\r\n'.join(v.splitlines()))) for (k, v)
-            in headers.iteritems()]
+            in headers.items()]
     hdrs = '\r\n'.join(hdrs) + '\r\n'
     return hdrs
 
@@ -4918,7 +4932,7 @@
     d = defer.Deferred()
     def go(last):
         try:
-            r = i.next()
+            r = next(i)
         except StopIteration:
             d.callback(last)
         except:
@@ -5291,7 +5305,7 @@
             raise Exception("Header list must end with )")
 
         headers = s[1:end].split()
-        self.pending_body.header.fields = map(str.upper, headers)
+        self.pending_body.header.fields = list(map(str.upper, headers))
         return end + 1
 
     def state_maybe_partial(self, s):
@@ -5306,7 +5320,7 @@
         parts = partial.split('.', 1)
         if len(parts) != 2:
             raise Exception("Partial specification did not include two .-delimited integers")
-        begin, length = map(int, parts)
+        begin, length = list(map(int, parts))
         self.pending_body.partialBegin = begin
         self.pending_body.partialLength = length
 
@@ -5369,14 +5383,14 @@
     }
     m = re.match('%(day)s-%(mon)s-%(year)s' % expr, s)
     if not m:
-        raise ValueError, "Cannot parse time string %r" % (s,)
+        raise ValueError("Cannot parse time string %r" % (s,))
     d = m.groupdict()
     try:
         d['mon'] = 1 + (months.index(d['mon'].lower()) % 12)
         d['year'] = int(d['year'])
         d['day'] = int(d['day'])
     except ValueError:
-        raise ValueError, "Cannot parse time string %r" % (s,)
+        raise ValueError("Cannot parse time string %r" % (s,))
     else:
         return time.struct_time(
             (d['year'], d['mon'], d['day'], 0, 0, 0, -1, -1, -1)
@@ -5407,7 +5421,7 @@
     r = []
     _in = []
     for c in s:
-        if ord(c) in (range(0x20, 0x26) + range(0x27, 0x7f)):
+        if ord(c) in (list(range(0x20, 0x26)) + list(range(0x27, 0x7f))):
             if _in:
                 r.extend(['&', modified_base64(''.join(_in)), '-'])
                 del _in[:]
--- twisted/mail/mail.py (original)
+++ twisted/mail/mail.py (refactored)
@@ -85,22 +85,22 @@
         return DomainWithDefaultDict(self.domains.copy(), self.default)
 
     def iteritems(self):
-        return self.domains.iteritems()
+        return iter(self.domains.items())
 
     def iterkeys(self):
-        return self.domains.iterkeys()
+        return iter(self.domains.keys())
 
     def itervalues(self):
-        return self.domains.itervalues()
+        return iter(self.domains.values())
 
     def keys(self):
-        return self.domains.keys()
+        return list(self.domains.keys())
 
     def values(self):
-        return self.domains.values()
+        return list(self.domains.values())
 
     def items(self):
-        return self.domains.items()
+        return list(self.domains.items())
 
     def popitem(self):
         return self.domains.popitem()
@@ -259,7 +259,7 @@
 
     def addDomain(self, name, domain):
         portal = cred.portal.Portal(domain)
-        map(portal.registerChecker, domain.getCredentialsCheckers())
+        list(map(portal.registerChecker, domain.getCredentialsCheckers()))
         self.domains[name] = domain
         self.portals[name] = portal
         if self.aliases and IAliasableDomain.providedBy(domain):
@@ -294,7 +294,7 @@
 
     def _setupMonitor(self):
         from twisted.internet import reactor
-        t, self.index = self.intervals.next()
+        t, self.index = next(self.intervals)
         self._call = reactor.callLater(t, self._monitor)
 
     def stopService(self):
--- twisted/mail/maildir.py (original)
+++ twisted/mail/maildir.py (refactored)
@@ -15,9 +15,9 @@
 from zope.interface import implements
 
 try:
-    import cStringIO as StringIO
+    import io as StringIO
 except ImportError:
-    import StringIO
+    import io
 
 from twisted.python.compat import set
 from twisted.mail import pop3
@@ -62,11 +62,11 @@
 
 def initializeMaildir(dir):
     if not os.path.isdir(dir):
-        os.mkdir(dir, 0700)
+        os.mkdir(dir, 0o700)
         for subdir in ['new', 'cur', 'tmp', '.Trash']:
-            os.mkdir(os.path.join(dir, subdir), 0700)
+            os.mkdir(os.path.join(dir, subdir), 0o700)
         for subdir in ['new', 'cur', 'tmp']:
-            os.mkdir(os.path.join(dir, '.Trash', subdir), 0700)
+            os.mkdir(os.path.join(dir, '.Trash', subdir), 0o700)
         # touch
         open(os.path.join(dir, '.Trash', 'maildirfolder'), 'w').close()
 
@@ -172,7 +172,7 @@
         self.defer = defer.Deferred()
         self.openCall = None
         if not hasattr(msg, "read"):
-            msg = StringIO.StringIO(msg)
+            msg = io.StringIO(msg)
         self.msg = msg
         # This is needed, as this startup phase might call defer.errback and zero out self.defer
         # By doing it on the reactor iteration appendMessage is able to use .defer without problems.
@@ -222,7 +222,8 @@
             try:
                 self.osrename(self.tmpname, newname)
                 break
-            except OSError, (err, estr):
+            except OSError as xxx_todo_changeme:
+                (err, estr) = xxx_todo_changeme.args
                 import errno
                 # if the newname exists, retry with a new newname.
                 if err != errno.EEXIST:
@@ -243,7 +244,7 @@
         while True:
             self.tmpname = os.path.join(self.mbox.path, "tmp", _generateMaildirName())
             try:
-                self.fh = self.osopen(self.tmpname, attr, 0600)
+                self.fh = self.osopen(self.tmpname, attr, 0o600)
                 return None
             except OSError:
                 tries += 1
@@ -317,10 +318,11 @@
         This moves any messages from .Trash/ subfolder back to their
         original position, and empties out the deleted dictionary.
         """
-        for (real, trash) in self.deleted.items():
+        for (real, trash) in list(self.deleted.items()):
             try:
                 os.rename(trash, real)
-            except OSError, (err, estr):
+            except OSError as xxx_todo_changeme1:
+                (err, estr) = xxx_todo_changeme1.args
                 import errno
                 # If the file has been deleted from disk, oh well!
                 if err != errno.ENOENT:
@@ -372,7 +374,7 @@
         Return an in-memory file-like object for the message content at the
         given offset.
         """
-        return StringIO.StringIO(self.msgs[i])
+        return io.StringIO(self.msgs[i])
 
 
     def getUidl(self, i):
@@ -444,7 +446,7 @@
         Otherwise, returns postmaster's mailbox instead if bounces
         go to postmaster, otherwise return None
         """
-        if not self.dbm.has_key(name):
+        if name not in self.dbm:
             if not self.postmaster:
                 return None
             name = 'postmaster'
--- twisted/mail/pb.py (original)
+++ twisted/mail/pb.py (refactored)
@@ -99,10 +99,10 @@
             self.sendAnswer(requestID, collection)
 
     def getCollection(self, name, domain, password):
-        if not self.domains.has_key(domain):
+        if domain not in self.domains:
             return
         domain = self.domains[domain]
-        if (domain.dbm.has_key(name) and
+        if (name in domain.dbm and
             domain.dbm[name] == password):
             return MaildirCollection(domain.userDirectory(name))
 
--- twisted/mail/pop3.py (original)
+++ twisted/mail/pop3.py (refactored)
@@ -129,9 +129,9 @@
         return self
 
 
-    def next(self):
+    def __next__(self):
         try:
-            v = self.iterator.next()
+            v = next(self.iterator)
         except StopIteration:
             if self.lines:
                 self.write(self.lines)
@@ -342,7 +342,7 @@
     def state_COMMAND(self, line):
         try:
             return self.processCommand(*line.split(' '))
-        except (ValueError, AttributeError, POP3Error, TypeError), e:
+        except (ValueError, AttributeError, POP3Error, TypeError) as e:
             log.err()
             self.failResponse('bad protocol or server: %s: %s' % (e.__class__.__name__, e))
 
@@ -423,7 +423,7 @@
             except:
                 log.err()
             else:
-                baseCaps.append("SASL " + ' '.join(v.keys()))
+                baseCaps.append("SASL " + ' '.join(list(v.keys())))
         return baseCaps
 
     def do_CAPA(self):
@@ -477,7 +477,8 @@
         d.addCallbacks(self._cbMailbox, self._ebMailbox, callbackArgs=(user,)
         ).addErrback(self._ebUnexpected)
 
-    def _cbMailbox(self, (interface, avatar, logout), user):
+    def _cbMailbox(self, xxx_todo_changeme, user):
+        (interface, avatar, logout) = xxx_todo_changeme
         if interface is not IMailbox:
             self.failResponse('Authentication failed')
             log.err("_cbMailbox() called with an interface other than IMailbox")
@@ -958,7 +959,7 @@
         pass
 
 
-NONE, SHORT, FIRST_LONG, LONG = range(4)
+NONE, SHORT, FIRST_LONG, LONG = list(range(4))
 
 NEXT = {}
 NEXT[NONE] = NONE
--- twisted/mail/pop3client.py (original)
+++ twisted/mail/pop3client.py (refactored)
@@ -65,7 +65,8 @@
     # it takes care of padding out the missing values with None.
     def __init__(self, L):
         self.L = L
-    def setitem(self, (item, value)):
+    def setitem(self, xxx_todo_changeme):
+        (item, value) = xxx_todo_changeme
         diff = item - len(self.L) + 1
         if diff > 0:
             self.L.extend([None] * diff)
--- twisted/mail/relay.py (original)
+++ twisted/mail/relay.py (refactored)
@@ -12,7 +12,7 @@
 import os
 
 try:
-    import cPickle as pickle
+    import pickle as pickle
 except ImportError:
     import pickle
 
@@ -30,8 +30,8 @@
         """
         if self.willRelay(user.dest, user.protocol):
             # The most cursor form of verification of the addresses
-            orig = filter(None, str(user.orig).split('@', 1))
-            dest = filter(None, str(user.dest).split('@', 1))
+            orig = [_f for _f in str(user.orig).split('@', 1) if _f]
+            dest = [_f for _f in str(user.dest).split('@', 1) if _f]
             if len(orig) == 2 and len(dest) == 2:
                 return lambda: self.startMessage(user)
         raise smtp.SMTPBadRcpt(user)
--- twisted/mail/relaymanager.py (original)
+++ twisted/mail/relaymanager.py (refactored)
@@ -24,7 +24,7 @@
 import time
 
 try:
-    import cPickle as pickle
+    import pickle as pickle
 except ImportError:
     import pickle
 
@@ -167,13 +167,13 @@
             self.addMessage(message[:-2])
 
     def getWaiting(self):
-        return self.waiting.keys()
+        return list(self.waiting.keys())
 
     def hasWaiting(self):
         return len(self.waiting) > 0
 
     def getRelayed(self):
-        return self.relayed.keys()
+        return list(self.relayed.keys())
 
     def setRelaying(self, message):
         del self.waiting[message]
@@ -307,7 +307,7 @@
         if self.manager.queue.noisy:
             log.msg("Backing off on delivery of " + str(msgs))
         def setWaiting(queue, messages):
-            map(queue.setWaiting, messages)
+            list(map(queue.setWaiting, messages))
         from twisted.internet import reactor
         reactor.callLater(30, setWaiting, self.manager.queue, msgs)
         del self.manager.managed[relay]
@@ -414,10 +414,10 @@
             self.mxcalc = MXCalculator()
 
         relays = []
-        for (domain, msgs) in exchanges.iteritems():
+        for (domain, msgs) in exchanges.items():
             manager = _AttemptManager(self)
             factory = self.factory(msgs, manager, *self.fArgs, **self.fKwArgs)
-            self.managed[factory] = map(os.path.basename, msgs)
+            self.managed[factory] = list(map(os.path.basename, msgs))
             relayAttemptDeferred = manager.getCompletionDeferred()
             connectSetupDeferred = self.mxcalc.getMX(domain)
             connectSetupDeferred.addCallback(lambda mx: str(mx.name))
@@ -436,7 +436,7 @@
         log.err('Error setting up managed relay factory for ' + domain)
         log.err(failure)
         def setWaiting(queue, messages):
-            map(queue.setWaiting, messages)
+            list(map(queue.setWaiting, messages))
         from twisted.internet import reactor
         reactor.callLater(30, setWaiting, self.queue, self.managed[factory])
         del self.managed[factory]
--- twisted/mail/smtp.py (original)
+++ twisted/mail/smtp.py (refactored)
@@ -32,9 +32,9 @@
 from twisted.python.runtime import platform
 
 try:
-    from cStringIO import StringIO
+    from io import StringIO
 except ImportError:
-    from StringIO import StringIO
+    from io import StringIO
 
 # Cache the hostname (XXX Yes - this is broken)
 if platform.isMacOSX():
@@ -45,7 +45,7 @@
     DNSNAME = socket.getfqdn()
 
 # Used for fast success code lookup
-SUCCESS = dict(map(None, range(200, 300), []))
+SUCCESS = dict(list(map(None, list(range(200, 300)), [])))
 
 class IMessageDelivery(Interface):
     def receivedHeader(helo, origin, recipients):
@@ -305,7 +305,7 @@
         yield i
         i += 1
 
-def messageid(uniq=None, N=idGenerator().next):
+def messageid(uniq=None, N=idGenerator().__next__):
     """Return a globally unique random string in RFC 2822 Message-ID format
 
     <datetime.pid.random@host.dom.ain>
@@ -314,7 +314,7 @@
     """
     datetime = time.strftime('%Y%m%d%H%M%S', time.gmtime())
     pid = os.getpid()
-    rand = random.randrange(2**31L-1)
+    rand = random.randrange(2**31-1)
     if uniq is None:
         uniq = ''
     else:
@@ -372,12 +372,12 @@
         if isinstance(addr, Address):
             self.__dict__ = addr.__dict__.copy()
             return
-        elif not isinstance(addr, types.StringTypes):
+        elif not isinstance(addr, str):
             addr = str(addr)
         self.addrstr = addr
 
         # Tokenize
-        atl = filter(None,self.tstring.split(addr))
+        atl = [_f for _f in self.tstring.split(addr) if _f]
 
         local = []
         domain = []
@@ -385,7 +385,7 @@
         while atl:
             if atl[0] == '<':
                 if atl[-1] != '>':
-                    raise AddressError, "Unbalanced <>"
+                    raise AddressError("Unbalanced <>")
                 atl = atl[1:-1]
             elif atl[0] == '@':
                 atl = atl[1:]
@@ -395,15 +395,15 @@
                         # remove it
                         atl = atl[1:]
                     if not atl:
-                        raise AddressError, "Malformed source route"
+                        raise AddressError("Malformed source route")
                     atl = atl[1:] # remove :
                 elif domain:
-                    raise AddressError, "Too many @"
+                    raise AddressError("Too many @")
                 else:
                     # Now in domain
                     domain = ['']
             elif len(atl[0]) == 1 and not self.atomre.match(atl[0]) and atl[0] !=  '.':
-                raise AddressError, "Parse error at %r of %r" % (atl[0], (addr, atl))
+                raise AddressError("Parse error at %r of %r" % (atl[0], (addr, atl)))
             else:
                 if not domain:
                     local.append(atl[0])
@@ -424,7 +424,7 @@
         """Remove RFC-2821 quotes from address."""
         res = []
 
-        atl = filter(None,self.tstring.split(str(addr)))
+        atl = [_f for _f in self.tstring.split(str(addr)) if _f]
 
         for t in atl:
             if t[0] == '"' and t[-1] == '"':
@@ -636,7 +636,7 @@
 
         try:
             addr = Address(m.group('path'), self.host)
-        except AddressError, e:
+        except AddressError as e:
             self.sendCode(553, str(e))
             return
 
@@ -674,7 +674,7 @@
 
         try:
             user = User(m.group('path'), self._helo, self, self._from)
-        except AddressError, e:
+        except AddressError as e:
             self.sendCode(553, str(e))
             return
 
@@ -729,7 +729,7 @@
                 if rcvdhdr:
                     msg.lineReceived(rcvdhdr)
                 msgs.append(msg)
-            except SMTPServerError, e:
+            except SMTPServerError as e:
                 self.sendCode(e.code, e.resp)
                 self.mode = COMMAND
                 self._disconnect(msgs)
@@ -813,7 +813,7 @@
 
             for message in self.__messages:
                 message.lineReceived(line)
-        except SMTPServerError, e:
+        except SMTPServerError as e:
             self.datafailed = e
             for message in self.__messages:
                 message.connectionLost()
@@ -835,10 +835,11 @@
             self.sendCode(250, 'Delivery in progress')
 
 
-    def _cbAnonymousAuthentication(self, (iface, avatar, logout)):
+    def _cbAnonymousAuthentication(self, xxx_todo_changeme):
         """
         Save the state resulting from a successful anonymous cred login.
         """
+        (iface, avatar, logout) = xxx_todo_changeme
         if issubclass(iface, IMessageDeliveryFactory):
             self.deliveryFactory = avatar
             self.delivery = None
@@ -1090,7 +1091,7 @@
         self.toAddressesResult = []
         self.successAddresses = []
         self._okresponse = self.smtpState_toOrData
-        self._expected = xrange(0,1000)
+        self._expected = range(0,1000)
         self.lastAddress = None
         return self.smtpState_toOrData(0, '')
 
@@ -1100,7 +1101,7 @@
             if code in SUCCESS:
                 self.successAddresses.append(self.lastAddress)
         try:
-            self.lastAddress = self.toAddresses.next()
+            self.lastAddress = next(self.toAddresses)
         except StopIteration:
             if self.successAddresses:
                 self.sendLine('DATA')
@@ -1195,7 +1196,7 @@
         raise NotImplementedError
 
     def _disconnectFromServer(self):
-        self._expected = xrange(0, 1000)
+        self._expected = range(0, 1000)
         self._okresponse = self.smtpState_disconnect
         self.sendLine('QUIT')
 
@@ -1376,7 +1377,7 @@
 
         try:
             challenge = base64.decodestring(challenge)
-        except binascii.Error, e:
+        except binascii.Error as e:
             # Illegal challenge, give up, then quit
             self.sendLine('*')
             self._okresponse = self.esmtpAUTHMalformedChallenge
@@ -1420,7 +1421,7 @@
 
 
     def extensions(self):
-        ext = {'AUTH': self.challengers.keys()}
+        ext = {'AUTH': list(self.challengers.keys())}
         if self.canStartTLS and not self.startedTLS:
             ext['STARTTLS'] = None
         return ext
@@ -1433,7 +1434,7 @@
 
     def listExtensions(self):
         r = []
-        for (c, v) in self.extensions().iteritems():
+        for (c, v) in self.extensions().items():
             if v is not None:
                 if v:
                     # Intentionally omit extensions with empty argument lists
@@ -1647,9 +1648,9 @@
         @param timeout: Period, in seconds, for which to wait for
         server responses, or None to wait forever.
         """
-        assert isinstance(retries, (int, long))
-
-        if isinstance(toEmail, types.StringTypes):
+        assert isinstance(retries, (int, int))
+
+        if isinstance(toEmail, str):
             toEmail = [toEmail]
         self.fromEmail = Address(fromEmail)
         self.nEmails = len(toEmail)
@@ -1909,10 +1910,10 @@
     writer.addheader("Mime-Version", "1.0")
     if headers:
         # Setup the mail headers
-        for (header, value) in headers.items():
+        for (header, value) in list(headers.items()):
             writer.addheader(header, value)
 
-        headkeys = [k.lower() for k in headers.keys()]
+        headkeys = [k.lower() for k in list(headers.keys())]
     else:
         headkeys = ()
 
--- twisted/mail/scripts/mailmail.py (original)
+++ twisted/mail/scripts/mailmail.py (refactored)
@@ -10,12 +10,12 @@
 import sys
 import rfc822
 import getpass
-from ConfigParser import ConfigParser
+from configparser import ConfigParser
 
 try:
-    import cStringIO as StringIO
+    import io as StringIO
 except:
-    import StringIO
+    import io
 
 from twisted.internet import reactor
 from twisted.mail import smtp
@@ -129,7 +129,7 @@
     }
 
     headers = []
-    buffer = StringIO.StringIO()
+    buffer = io.StringIO()
     while 1:
         write = 1
         line = sys.stdin.readline()
@@ -173,7 +173,7 @@
                 pass
 
     buffer.seek(0, 0)
-    o.body = StringIO.StringIO(buffer.getvalue() + sys.stdin.read())
+    o.body = io.StringIO(buffer.getvalue() + sys.stdin.read())
     return o
 
 class Configuration:
@@ -257,7 +257,7 @@
                         else:
                             L.append(id)
             order = p.get(section, 'order')
-            order = map(str.split, map(str.lower, order.split(',')))
+            order = list(map(str.split, list(map(str.lower, order.split(',')))))
             if order[0] == 'allow':
                 setattr(c, section, 'allow')
             else:
@@ -296,9 +296,9 @@
 def senderror(failure, options):
     recipient = [options.sender]
     sender = '"Internally Generated Message (%s)"<postmaster@%s>' % (sys.argv[0], smtp.DNSNAME)
-    error = StringIO.StringIO()
+    error = io.StringIO()
     failure.printTraceback(file=error)
-    body = StringIO.StringIO(ERROR_FMT % error.getvalue())
+    body = io.StringIO(ERROR_FMT % error.getvalue())
 
     d = smtp.sendmail('localhost', sender, recipient, body)
     d.addBoth(lambda _: reactor.stop())
--- twisted/mail/test/pop3testserver.py (original)
+++ twisted/mail/test/pop3testserver.py (refactored)
@@ -224,7 +224,7 @@
 """
 
 def printMessage(msg):
-    print "Server Starting in %s mode" % msg
+    print("Server Starting in %s mode" % msg)
 
 def processArg(arg):
 
@@ -285,11 +285,11 @@
         printMessage("Slow Greeting")
 
     elif arg.lower() == '--help':
-        print usage
+        print(usage)
         sys.exit()
 
     else:
-        print usage
+        print(usage)
         sys.exit()
 
 def main():
--- twisted/mail/test/test_bounce.py (original)
+++ twisted/mail/test/test_bounce.py (refactored)
@@ -7,7 +7,7 @@
 
 from twisted.trial import unittest
 from twisted.mail import bounce
-import rfc822, cStringIO
+import rfc822, io
 
 class BounceTestCase(unittest.TestCase):
     """
@@ -15,7 +15,7 @@
     """
 
     def testBounceFormat(self):
-        from_, to, s = bounce.generateBounce(cStringIO.StringIO('''\
+        from_, to, s = bounce.generateBounce(io.StringIO('''\
 From: Moshe Zadka <moshez@example.com>
 To: nonexistant@example.org
 Subject: test
@@ -23,7 +23,7 @@
 '''), 'moshez@example.com', 'nonexistant@example.org')
         self.assertEquals(from_, '')
         self.assertEquals(to, 'moshez@example.com')
-        mess = rfc822.Message(cStringIO.StringIO(s))
+        mess = rfc822.Message(io.StringIO(s))
         self.assertEquals(mess['To'], 'moshez@example.com')
         self.assertEquals(mess['From'], 'postmaster@example.org')
         self.assertEquals(mess['subject'], 'Returned Mail: see transcript for details')
--- twisted/mail/test/test_imap.py (original)
+++ twisted/mail/test/test_imap.py (refactored)
@@ -8,9 +8,9 @@
 """
 
 try:
-    from cStringIO import StringIO
+    from io import StringIO
 except ImportError:
-    from StringIO import StringIO
+    from io import StringIO
 
 import os
 import types
@@ -49,19 +49,19 @@
     l = l[:]
     l.sort()
     for i in range(len(l)):
-        if isinstance(l[i], types.ListType):
+        if isinstance(l[i], list):
             l[i] = sortNest(l[i])
-        elif isinstance(l[i], types.TupleType):
+        elif isinstance(l[i], tuple):
             l[i] = tuple(sortNest(list(l[i])))
     return l
 
 class IMAP4UTF7TestCase(unittest.TestCase):
     tests = [
-        [u'Hello world', 'Hello world'],
-        [u'Hello & world', 'Hello &- world'],
-        [u'Hello\xffworld', 'Hello&AP8-world'],
-        [u'\xff\xfe\xfd\xfc', '&AP8A,gD9APw-'],
-        [u'~peter/mail/\u65e5\u672c\u8a9e/\u53f0\u5317',
+        ['Hello world', 'Hello world'],
+        ['Hello & world', 'Hello &- world'],
+        ['Hello\xffworld', 'Hello&AP8-world'],
+        ['\xff\xfe\xfd\xfc', '&AP8A,gD9APw-'],
+        ['~peter/mail/\u65e5\u672c\u8a9e/\u53f0\u5317',
          '~peter/mail/&ZeVnLIqe-/&U,BTFw-'], # example from RFC 2060
     ]
 
@@ -71,7 +71,7 @@
         I{imap4-utf-7} codec should produce the same result as not
         specifying the error policy.
         """
-        text = u'Hello world'
+        text = 'Hello world'
         self.assertEqual(
             text.encode('imap4-utf-7', 'strict'),
             text.encode('imap4-utf-7'))
@@ -98,7 +98,7 @@
 
     def testPrintableSingletons(self):
         # All printables represent themselves
-        for o in range(0x20, 0x26) + range(0x27, 0x7f):
+        for o in list(range(0x20, 0x26)) + list(range(0x27, 0x7f)):
             self.failUnlessEqual(chr(o), chr(o).encode('imap4-utf-7'))
             self.failUnlessEqual(chr(o), chr(o).decode('imap4-utf-7'))
         self.failUnlessEqual('&'.encode('imap4-utf-7'), '&-')
@@ -855,7 +855,8 @@
         d.addCallback(self.__cb_fetchBodyParts)
         return d
 
-    def __cb_fetchBodyParts(self, (lines, last)):
+    def __cb_fetchBodyParts(self, xxx_todo_changeme):
+        (lines, last) = xxx_todo_changeme
         info = {}
         for line in lines:
             parts = line.split(None, 2)
@@ -864,7 +865,7 @@
                     try:
                         mail_id = int(parts[0])
                     except ValueError:
-                        raise imap4.IllegalServerResponse, line
+                        raise imap4.IllegalServerResponse(line)
                     else:
                         body_parts = imap4.parseNestedParens(parts[2])[0]
                         dict_parts = {}
@@ -1116,7 +1117,7 @@
 
     def _cbTestCreate(self, ignored, succeed, fail):
         self.assertEquals(self.result, [1] * len(succeed) + [0] * len(fail))
-        mbox = SimpleServer.theAccount.mailboxes.keys()
+        mbox = list(SimpleServer.theAccount.mailboxes.keys())
         answers = ['inbox', 'testbox', 'test/box', 'test', 'test/box/box']
         mbox.sort()
         answers.sort()
@@ -1135,7 +1136,7 @@
         d2 = self.loopback()
         d = defer.gatherResults([d1, d2])
         d.addCallback(lambda _:
-                      self.assertEquals(SimpleServer.theAccount.mailboxes.keys(), []))
+                      self.assertEquals(list(SimpleServer.theAccount.mailboxes.keys()), []))
         return d
 
     def testIllegalInboxDelete(self):
@@ -1214,7 +1215,7 @@
         d2 = self.loopback()
         d = defer.gatherResults([d1, d2])
         d.addCallback(lambda _:
-                      self.assertEquals(SimpleServer.theAccount.mailboxes.keys(),
+                      self.assertEquals(list(SimpleServer.theAccount.mailboxes.keys()),
                                         ['NEWNAME']))
         return d
 
@@ -1253,7 +1254,7 @@
         return d.addCallback(self._cbTestHierarchicalRename)
 
     def _cbTestHierarchicalRename(self, ignored):
-        mboxes = SimpleServer.theAccount.mailboxes.keys()
+        mboxes = list(SimpleServer.theAccount.mailboxes.keys())
         expected = ['newname', 'newname/m1', 'newname/m2']
         mboxes.sort()
         self.assertEquals(mboxes, [s.upper() for s in expected])
@@ -1733,7 +1734,7 @@
 
     def _cbTestFlagChange(self, ignored, flags):
         E = self.client.events
-        expect = [['flagsChanged', {x[0]: x[1]}] for x in flags.items()]
+        expect = [['flagsChanged', {x[0]: x[1]}] for x in list(flags.items())]
         E.sort()
         expect.sort()
         self.assertEquals(E, expect)
@@ -2307,11 +2308,11 @@
     def fetch(self, messages, uid):
         self.received_messages = messages
         self.received_uid = uid
-        return iter(zip(range(len(self.msgObjs)), self.msgObjs))
+        return iter(zip(list(range(len(self.msgObjs))), self.msgObjs))
 
     def _fetchWork(self, uid):
         if uid:
-            for (i, msg) in zip(range(len(self.msgObjs)), self.msgObjs):
+            for (i, msg) in zip(list(range(len(self.msgObjs))), self.msgObjs):
                 self.expected[i]['UID'] = str(msg.getUID())
 
         def result(R):
@@ -2783,7 +2784,7 @@
             self.server_received_parts and self.server_received_parts.sort()
 
             if self.uid:
-                for (k, v) in self.expected.items():
+                for (k, v) in list(self.expected.items()):
                     v['UID'] = str(k)
 
             self.assertEquals(self.result, self.expected)
@@ -2863,7 +2864,7 @@
 
         m = FakeMailbox()
         msgs = [FakeyMessage({'Header-Counter': str(i)}, (), 'Date', 'Body %d' % (i,), i + 10, None) for i in range(1, 11)]
-        d = f([im for im in zip(range(1, 11), msgs)], 'tag', m)
+        d = f([im for im in zip(list(range(1, 11)), msgs)], 'tag', m)
 
         def cbCopy(results):
             seen = []
@@ -2891,10 +2892,10 @@
 
         m = MessageCopierMailbox()
         msgs = [object() for i in range(1, 11)]
-        d = f([im for im in zip(range(1, 11), msgs)], 'tag', m)
+        d = f([im for im in zip(list(range(1, 11)), msgs)], 'tag', m)
 
         def cbCopy(results):
-            self.assertEquals(results, zip([1] * 10, range(1, 11)))
+            self.assertEquals(results, list(zip([1] * 10, list(range(1, 11)))))
             for (orig, new) in zip(msgs, m.msgs):
                 self.assertIdentical(orig, new)
 
@@ -2930,7 +2931,7 @@
         self.client.requireTransportSecurity = True
 
         methods = [login, list, status, examine, logout]
-        map(self.connected.addCallback, map(strip, methods))
+        list(map(self.connected.addCallback, list(map(strip, methods))))
         self.connected.addCallbacks(self._cbStopClient, self._ebGeneral)
         def check(ignored):
             self.assertEquals(self.server.startedTLS, True)
@@ -3051,7 +3052,7 @@
             self.assertNotEquals(self.server.state, 'timeout')
 
         def cbAdvance(ignored):
-            for i in xrange(4):
+            for i in range(4):
                 c.advance(.5)
 
         SlowMailbox.fetchDeferred.addCallback(cbAdvance)
--- twisted/mail/test/test_mail.py (original)
+++ twisted/mail/test/test_mail.py (refactored)
@@ -9,7 +9,7 @@
 import errno
 import shutil
 import pickle
-import StringIO
+import io
 import rfc822
 import tempfile
 import signal
@@ -57,30 +57,30 @@
         d = mail.mail.DomainWithDefaultDict(d, 'Default')
 
         self.assertEquals(len(d), 10)
-        self.assertEquals(list(iter(d)), range(10))
-        self.assertEquals(list(d.iterkeys()), list(iter(d)))
-
-        items = list(d.iteritems())
+        self.assertEquals(list(iter(d)), list(range(10)))
+        self.assertEquals(list(d.keys()), list(iter(d)))
+
+        items = list(d.items())
         items.sort()
         self.assertEquals(items, [(x, x + 10) for x in range(10)])
 
-        values = list(d.itervalues())
+        values = list(d.values())
         values.sort()
-        self.assertEquals(values, range(10, 20))
-
-        items = d.items()
+        self.assertEquals(values, list(range(10, 20)))
+
+        items = list(d.items())
         items.sort()
         self.assertEquals(items, [(x, x + 10) for x in range(10)])
 
-        values = d.values()
+        values = list(d.values())
         values.sort()
-        self.assertEquals(values, range(10, 20))
+        self.assertEquals(values, list(range(10, 20)))
 
         for x in range(10):
             self.assertEquals(d[x], x + 10)
             self.assertEquals(d.get(x), x + 10)
             self.failUnless(x in d)
-            self.failUnless(d.has_key(x))
+            self.failUnless(x in d)
 
         del d[2], d[4], d[6]
 
@@ -358,7 +358,7 @@
         mbox = mail.maildir.MaildirMailbox(self.d)
         mbox.AppendFactory = FailingMaildirMailboxAppendMessageTask
         ds = []
-        for i in xrange(1, 11):
+        for i in range(1, 11):
             ds.append(mbox.appendMessage("X" * i))
             ds[-1].addCallback(self.assertEqual, None)
         d = defer.gatherResults(ds)
@@ -394,7 +394,7 @@
         def _check(res, t):
             t.close()
             self.assertEqual(res, None)
-        for i in xrange(1, 11):
+        for i in range(1, 11):
             temp = tempfile.TemporaryFile()
             temp.write("X" * i)
             temp.seek(0,0)
@@ -449,7 +449,7 @@
             i = i + 1
 
         mb = mail.maildir.MaildirMailbox(self.d)
-        self.assertEquals(mb.listMessages(), range(1, 11))
+        self.assertEquals(mb.listMessages(), list(range(1, 11)))
         self.assertEquals(mb.listMessages(1), 2)
         self.assertEquals(mb.listMessages(5), 6)
 
@@ -605,10 +605,10 @@
              smtp.Address('<someguy@somplace>'),
              ['user@host.name']
          )
-         fp = StringIO.StringIO(hdr)
+         fp = io.StringIO(hdr)
          m = rfc822.Message(fp)
-         self.assertEquals(len(m.items()), 1)
-         self.failUnless(m.has_key('Received'))
+         self.assertEquals(len(list(m.items())), 1)
+         self.failUnless('Received' in m)
 
     def testValidateTo(self):
         user = smtp.User('user@test.domain', 'helo', None, 'wherever@whatever')
@@ -617,7 +617,7 @@
             )
 
     def _cbValidateTo(self, result):
-        self.failUnless(callable(result))
+        self.failUnless(hasattr(result, '__call__'))
 
     def testValidateToBadUsername(self):
         user = smtp.User('resu@test.domain', 'helo', None, 'wherever@whatever')
@@ -658,7 +658,7 @@
         self.S.addDomain('test.domain', self.D)
 
         portal = cred.portal.Portal(self.D)
-        map(portal.registerChecker, self.D.getCredentialsCheckers())
+        list(map(portal.registerChecker, self.D.getCredentialsCheckers()))
         self.S.portals[''] = self.S.portals['test.domain'] = portal
 
         self.P = mail.protocols.VirtualPOP3()
@@ -740,7 +740,7 @@
             user.protocol.transport = empty()
             user.protocol.transport.getPeer = lambda: peer
 
-            self.failUnless(callable(domain.exists(user)))
+            self.failUnless(hasattr(domain.exists(user), '__call__'))
 
         for peer in dontRelay:
             user = empty()
@@ -811,7 +811,7 @@
 class ManagedRelayerTestCase(unittest.TestCase):
     def setUp(self):
         self.manager = Manager()
-        self.messages = range(0, 20, 2)
+        self.messages = list(range(0, 20, 2))
         self.factory = object()
         self.relay = mail.relaymanager.ManagedRelayerMixin(self.manager)
         self.relay.messages = self.messages[:]
@@ -1381,7 +1381,7 @@
         domain.addUser('user', 'password')
         service.addDomain('test.domain', domain)
         service.portals[''] = service.portals['test.domain']
-        map(service.portals[''].registerChecker, domain.getCredentialsCheckers())
+        list(map(service.portals[''].registerChecker, domain.getCredentialsCheckers()))
 
         service.setQueue(mail.relay.DomainQueuer(service))
         manager = mail.relaymanager.SmartHostSMTPRelayingManager(service.queue, None)
@@ -1491,7 +1491,7 @@
         return done
 
 
-aliasFile = StringIO.StringIO("""\
+aliasFile = io.StringIO("""\
 # Here's a comment
    # woop another one
 testuser:                   address1,address2, address3,
@@ -1740,7 +1740,7 @@
 while read i; do
     echo $i >> process.alias.out
 done""")
-        os.chmod(sh.path, 0700)
+        os.chmod(sh.path, 0o700)
         a = mail.alias.ProcessAlias(sh.path, None, None)
         m = a.createMessageReceiver()
 
@@ -1849,34 +1849,34 @@
         })
 
         res1 = A1.resolve(aliases)
-        r1 = map(str, res1.objs)
+        r1 = list(map(str, res1.objs))
         r1.sort()
-        expected = map(str, [
+        expected = list(map(str, [
             mail.alias.AddressAlias('user1', None, None),
             mail.alias.MessageWrapper(DummyProcess(), 'echo'),
             mail.alias.FileWrapper('/file'),
-        ])
+        ]))
         expected.sort()
         self.assertEquals(r1, expected)
 
         res2 = A2.resolve(aliases)
-        r2 = map(str, res2.objs)
+        r2 = list(map(str, res2.objs))
         r2.sort()
-        expected = map(str, [
+        expected = list(map(str, [
             mail.alias.AddressAlias('user2', None, None),
             mail.alias.AddressAlias('user3', None, None)
-        ])
+        ]))
         expected.sort()
         self.assertEquals(r2, expected)
 
         res3 = A3.resolve(aliases)
-        r3 = map(str, res3.objs)
+        r3 = list(map(str, res3.objs))
         r3.sort()
-        expected = map(str, [
+        expected = list(map(str, [
             mail.alias.AddressAlias('user1', None, None),
             mail.alias.MessageWrapper(DummyProcess(), 'echo'),
             mail.alias.FileWrapper('/file'),
-        ])
+        ]))
         expected.sort()
         self.assertEquals(r3, expected)
 
@@ -1904,11 +1904,11 @@
         aliases['alias4'] = A4
 
         res = A4.resolve(aliases)
-        r = map(str, res.objs)
+        r = list(map(str, res.objs))
         r.sort()
-        expected = map(str, [
+        expected = list(map(str, [
             mail.alias.MessageWrapper(DummyProcess(), 'echo')
-        ])
+        ]))
         expected.sort()
         self.assertEquals(r, expected)
 
@@ -1940,6 +1940,6 @@
 from twisted.python.runtime import platformType
 import types
 if platformType != "posix":
-    for o in locals().values():
-        if isinstance(o, (types.ClassType, type)) and issubclass(o, unittest.TestCase):
+    for o in list(locals().values()):
+        if isinstance(o, (type, type)) and issubclass(o, unittest.TestCase):
             o.skip = "twisted.mail only works on posix"
--- twisted/mail/test/test_mailmail.py (original)
+++ twisted/mail/test/test_mailmail.py (refactored)
@@ -7,7 +7,7 @@
 """
 
 import sys
-from StringIO import StringIO
+from io import StringIO
 
 from twisted.trial.unittest import TestCase
 from twisted.mail.scripts.mailmail import parseOptions
--- twisted/mail/test/test_pop3.py (original)
+++ twisted/mail/test/test_pop3.py (refactored)
@@ -5,7 +5,7 @@
 Test cases for Ltwisted.mail.pop3} module.
 """
 
-import StringIO
+import io
 import hmac
 import base64
 import itertools
@@ -49,14 +49,14 @@
         c = pop3._IteratorBuffer(output.extend, input, 6)
         i = iter(c)
         self.assertEquals(output, []) # nothing is buffer
-        i.next()
+        next(i)
         self.assertEquals(output, []) # '012' is buffered
-        i.next()
+        next(i)
         self.assertEquals(output, []) # '012345' is buffered
-        i.next()
+        next(i)
         self.assertEquals(output, ['012', '345', '6']) # nothing is buffered
         for n in range(5):
-            i.next()
+            next(i)
         self.assertEquals(output, ['012', '345', '6', '7', '8', '9', '012', '345'])
 
 
@@ -164,11 +164,11 @@
 
     def listMessages(self, i=None):
         if i is None:
-            return map(len, self.list)
+            return list(map(len, self.list))
         return len(self.list[i])
 
     def getMessage(self, i):
-        return StringIO.StringIO(self.list[i])
+        return io.StringIO(self.list[i])
 
     def getUidl(self, i):
         return i
@@ -190,8 +190,8 @@
         code = parts[0]
         data = (parts[1:] or ['NONE'])[0]
         if code != '+OK':
-            print parts
-            raise AssertionError, 'code is ' + code
+            print(parts)
+            raise AssertionError('code is ' + code)
         self.lines = []
         self.retr(1)
 
@@ -204,7 +204,7 @@
 
     def handle_QUIT(self, line):
         if line[:3] != '+OK':
-            raise AssertionError, 'code is ' + line
+            raise AssertionError('code is ' + line)
 
 
 class POP3TestCase(unittest.TestCase):
@@ -283,13 +283,13 @@
 
     def listMessages(self, i=None):
         if i is None:
-            return map(len, self.messages)
+            return list(map(len, self.messages))
         if i >= len(self.messages):
             raise self.exceptionType()
         return len(self.messages[i])
 
     def getMessage(self, i):
-        return StringIO.StringIO(self.messages[i])
+        return io.StringIO(self.messages[i])
 
     def getUidl(self, i):
         if i >= len(self.messages):
@@ -444,7 +444,7 @@
 
 class CapabilityTestCase(unittest.TestCase):
     def setUp(self):
-        s = StringIO.StringIO()
+        s = io.StringIO()
         p = pop3.POP3()
         p.factory = TestServerFactory()
         p.transport = internet.protocol.FileWrapper(s)
@@ -454,7 +454,7 @@
         self.caps = p.listCapabilities()
         self.pcaps = s.getvalue().splitlines()
 
-        s = StringIO.StringIO()
+        s = io.StringIO()
         p.mbox = TestMailbox()
         p.transport = internet.protocol.FileWrapper(s)
         p.do_CAPA()
@@ -499,7 +499,7 @@
 
 class GlobalCapabilitiesTestCase(unittest.TestCase):
     def setUp(self):
-        s = StringIO.StringIO()
+        s = io.StringIO()
         p = pop3.POP3()
         p.factory = TestServerFactory()
         p.factory.pue = p.factory.puld = False
@@ -510,7 +510,7 @@
         self.caps = p.listCapabilities()
         self.pcaps = s.getvalue().splitlines()
 
-        s = StringIO.StringIO()
+        s = io.StringIO()
         p.mbox = TestMailbox()
         p.transport = internet.protocol.FileWrapper(s)
         p.do_CAPA()
@@ -548,7 +548,7 @@
         ch.addUser('testuser', 'testpassword')
         p.portal.registerChecker(ch)
 
-        s = StringIO.StringIO()
+        s = io.StringIO()
         p.transport = internet.protocol.FileWrapper(s)
         p.connectionMade()
 
@@ -590,7 +590,7 @@
         p.schedule = list
         self.pop3Server = p
 
-        s = StringIO.StringIO()
+        s = io.StringIO()
         p.transport = internet.protocol.FileWrapper(s)
         p.connectionMade()
         s.truncate(0)
--- twisted/mail/test/test_pop3client.py (original)
+++ twisted/mail/test/test_pop3client.py (refactored)
@@ -174,7 +174,8 @@
     def __init__(self):
         self.data = {}
 
-    def consume(self, (item, value)):
+    def consume(self, xxx_todo_changeme):
+        (item, value) = xxx_todo_changeme
         self.data.setdefault(item, []).append(value)
 
 class MessageConsumer:
@@ -471,10 +472,10 @@
         def connectionMade(self):
             self.factory.input = []
             self.output = self.output[:]
-            map(self.sendLine, self.output.pop(0))
+            list(map(self.sendLine, self.output.pop(0)))
         def lineReceived(self, line):
             self.factory.input.append(line)
-            map(self.sendLine, self.output.pop(0))
+            list(map(self.sendLine, self.output.pop(0)))
             if line == 'STLS':
                 self.transport.startTLS(self.context)
 
@@ -558,7 +559,7 @@
         pop3testserver.TIMEOUT_RESPONSE = True
 
         methods = [login, quit]
-        map(self.connected.addCallback, map(strip, methods))
+        list(map(self.connected.addCallback, list(map(strip, methods))))
         self.connected.addCallback(self._cbStopClient)
         self.connected.addErrback(self._ebGeneral)
         return self.loopback()
--- twisted/mail/test/test_smtp.py (original)
+++ twisted/mail/test/test_smtp.py (refactored)
@@ -37,9 +37,9 @@
 import re
 
 try:
-    from cStringIO import StringIO
+    from io import StringIO
 except ImportError:
-    from StringIO import StringIO
+    from io import StringIO
 
 def spameater(*spam, **eggs):
     return None
@@ -72,7 +72,7 @@
            self.messages[name] = []
 
    def exists(self, user):
-       if self.messages.has_key(user.dest.local):
+       if user.dest.local in self.messages:
            return defer.succeed(lambda: self.startMessage(user))
        return defer.fail(smtp.SMTPBadRcpt(user))
 
@@ -322,7 +322,7 @@
             data = output.getvalue()
             output.truncate(0)
             if not re.match(expect, data):
-                raise AssertionError, (send, expect, data)
+                raise AssertionError(send, expect, data)
             if data[:3] == '354':
                 for line in msg.splitlines():
                     if line and line[0] == '.':
@@ -335,7 +335,7 @@
                 output.truncate()
                 resp, msgdata = msgexpect
                 if not re.match(resp, data):
-                    raise AssertionError, (resp, data)
+                    raise AssertionError(resp, data)
                 for recip in msgdata[2]:
                     expected = list(msgdata[:])
                     expected[2] = [recip]
@@ -454,7 +454,7 @@
         I{xtext} codec should produce the same result as not
         specifying the error policy.
         """
-        text = u'Hello world'
+        text = 'Hello world'
         self.assertEqual(
             smtp.xtext_encode(text, 'strict'),
             (text.encode('xtext'), len(text)))
--- twisted/manhole/_inspectro.py (original)
+++ twisted/manhole/_inspectro.py (refactored)
@@ -87,7 +87,7 @@
 
 class DictionaryNode(InspectorNode):
     def get(self, index):
-        L = self.original.items()
+        L = list(self.original.items())
         L.sort()
         return L[index]
 
@@ -129,7 +129,7 @@
             return "__class__", v
         else:
             index -= 1
-            L = self.original.__dict__.items()
+            L = list(self.original.__dict__.items())
             L.sort()
             return L[index]
 
@@ -206,7 +206,7 @@
                 colnames[i], gtk.CellRendererText(), text=i))
         d = {}
         for m in reflect.prefixedMethods(self, "on_"):
-            d[m.im_func.__name__] = m
+            d[m.__func__.__name__] = m
         self.xml.signal_autoconnect(d)
         if o is not None:
             self.inspect(o)
@@ -231,14 +231,14 @@
     def do(self, command):
         filename = '<inspector>'
         try:
-            print repr(command)
+            print(repr(command))
             try:
                 code = compile(command, filename, 'eval')
             except:
                 code = compile(command, filename, 'single')
             val = eval(code, self.ns, self.ns)
             if val is not None:
-                print repr(val)
+                print(repr(val))
             self.ns['_'] = val
         except:
             log.err()
@@ -346,10 +346,12 @@
         for i in r:
             self.model.append(i)
     
-    def updateIn(self, (time, data)):
+    def updateIn(self, xxx_todo_changeme):
+        (time, data) = xxx_todo_changeme
         self.model.append((str(time - self.startTime), "R", repr(data)[1:-1]))
 
-    def updateOut(self, (time, data)):
+    def updateOut(self, xxx_todo_changeme1):
+        (time, data) = xxx_todo_changeme1
         self.model.append((str(time - self.startTime), "S", repr(data)[1:-1]))
 
     def on_logview_destroy(self, w):
--- twisted/manhole/explorer.py (original)
+++ twisted/manhole/explorer.py (refactored)
@@ -29,7 +29,7 @@
 class Pool(UserDict.UserDict):
     def getExplorer(self, object, identifier):
         oid = id(object)
-        if self.data.has_key(oid):
+        if oid in self.data:
             # XXX: This potentially returns something with
             # 'identifier' set to a different value.
             return self.data[oid]
@@ -117,7 +117,7 @@
     def get_elements(self):
         self.len = len(self.seq)
         l = []
-        for i in xrange(self.len):
+        for i in range(self.len):
             identifier = "%s[%s]" % (self.identifier, i)
 
             # GLOBAL: using global explorerPool
@@ -145,10 +145,10 @@
         self.keys = []
 
     def get_keys(self):
-        keys = self.dct.keys()
+        keys = list(self.dct.keys())
         self.len = len(keys)
         l = []
-        for i in xrange(self.len):
+        for i in range(self.len):
             identifier = "%s.keys()[%s]" % (self.identifier, i)
 
             # GLOBAL: using global explorerPool
@@ -278,7 +278,7 @@
     """
     def __init__(self, function, identifier):
         Explorer.__init__(self, function, identifier)
-        code = function.func_code
+        code = function.__code__
         argcount = code.co_argcount
         takesList = (code.co_flags & 0x04) and 1
         takesKeywords = (code.co_flags & 0x08) and 1
@@ -286,11 +286,11 @@
         n = (argcount + takesList + takesKeywords)
         signature = Signature(code.co_varnames[:n])
 
-        if function.func_defaults:
+        if function.__defaults__:
             i_d = 0
-            for i in xrange(argcount - len(function.func_defaults),
+            for i in range(argcount - len(function.__defaults__),
                             argcount):
-                default = function.func_defaults[i_d]
+                default = function.__defaults__[i_d]
                 default = explorerPool.getExplorer(
                     default, '%s.func_defaults[%d]' % (identifier, i_d))
                 signature.set_default(i, default)
@@ -323,18 +323,18 @@
     """
     def __init__(self, method, identifier):
 
-        function = method.im_func
+        function = method.__func__
         if type(function) is types.InstanceType:
-            function = function.__call__.im_func
+            function = function.__call__.__func__
 
         ExplorerFunction.__init__(self, function, identifier)
         self.id = id(method)
-        self.klass = explorerPool.getExplorer(method.im_class,
+        self.klass = explorerPool.getExplorer(method.__self__.__class__,
                                               identifier + '.im_class')
-        self.self = explorerPool.getExplorer(method.im_self,
+        self.self = explorerPool.getExplorer(method.__self__,
                                              identifier + '.im_self')
 
-        if method.im_self:
+        if method.__self__:
             # I'm a bound method -- eat the 'self' arg.
             self.signature.discardSelf()
 
@@ -360,13 +360,13 @@
         functions = {}
         classes = {}
         data = {}
-        for key, value in module.__dict__.items():
+        for key, value in list(module.__dict__.items()):
             if key[0] == '_':
                 continue
 
             mIdentifier = "%s.%s" % (identifier, key)
 
-            if type(value) is types.ClassType:
+            if type(value) is type:
                 classes[key] = explorerPool.getExplorer(value,
                                                         mIdentifier)
             elif type(value) is types.FunctionType:
@@ -385,20 +385,20 @@
         self.data = data
 
 typeTable = {types.InstanceType: ExplorerInstance,
-             types.ClassType: ExplorerClass,
+             type: ExplorerClass,
              types.MethodType: ExplorerMethod,
              types.FunctionType: ExplorerFunction,
              types.ModuleType: ExplorerModule,
              types.BuiltinFunctionType: ExplorerBuiltin,
-             types.ListType: ExplorerSequence,
-             types.TupleType: ExplorerSequence,
-             types.DictType: ExplorerMapping,
-             types.StringType: ExplorerImmutable,
-             types.NoneType: ExplorerImmutable,
-             types.IntType: ExplorerImmutable,
-             types.FloatType: ExplorerImmutable,
-             types.LongType: ExplorerImmutable,
-             types.ComplexType: ExplorerImmutable,
+             list: ExplorerSequence,
+             tuple: ExplorerSequence,
+             dict: ExplorerMapping,
+             bytes: ExplorerImmutable,
+             type(None): ExplorerImmutable,
+             int: ExplorerImmutable,
+             float: ExplorerImmutable,
+             int: ExplorerImmutable,
+             complex: ExplorerImmutable,
              }
 
 class Signature(pb.Copyable):
@@ -421,7 +421,7 @@
         return self.name[arg]
 
     def get_default(self, arg):
-        if arg is types.StringType:
+        if arg is bytes:
             arg = self.name.index(arg)
 
         # Wouldn't it be nice if we just returned "None" when there
@@ -433,32 +433,32 @@
             return (False, None)
 
     def set_default(self, arg, value):
-        if arg is types.StringType:
+        if arg is bytes:
             arg = self.name.index(arg)
 
         self.flavour[arg] = self._HAS_DEFAULT
         self.default[arg] = value
 
     def set_varlist(self, arg):
-        if arg is types.StringType:
+        if arg is bytes:
             arg = self.name.index(arg)
 
         self.flavour[arg] = self._VAR_LIST
 
     def set_keyword(self, arg):
-        if arg is types.StringType:
+        if arg is bytes:
             arg = self.name.index(arg)
 
         self.flavour[arg] = self._KEYWORD_DICT
 
     def is_varlist(self, arg):
-        if arg is types.StringType:
+        if arg is bytes:
             arg = self.name.index(arg)
 
         return (self.flavour[arg] == self._VAR_LIST)
 
     def is_keyword(self, arg):
-        if arg is types.StringType:
+        if arg is bytes:
             arg = self.name.index(arg)
 
         return (self.flavour[arg] == self._KEYWORD_DICT)
@@ -483,7 +483,7 @@
 
     def __str__(self):
         arglist = []
-        for arg in xrange(len(self)):
+        for arg in range(len(self)):
             name = self.get_name(arg)
             hasDefault, default = self.get_default(arg)
             if hasDefault:
@@ -537,16 +537,16 @@
         objects which are members of this one.
         """
         if type(object) is not types.InstanceType:
-            raise TypeError, "Sorry, can only place a watch on Instances."
+            raise TypeError("Sorry, can only place a watch on Instances.")
 
         # uninstallers = []
 
         dct = {}
         reflect.addMethodNamesToDict(object.__class__, dct, '')
-        for k in object.__dict__.keys():
+        for k in list(object.__dict__.keys()):
             dct[k] = 1
 
-        members = dct.keys()
+        members = list(dct.keys())
 
         clazzNS = {}
         clazz = new.classobj('Watching%s%X' %
@@ -566,7 +566,7 @@
             m = getattr(object, name)
             # Only hook bound methods.
             if ((type(m) is types.MethodType)
-                and (m.im_self is not None)):
+                and (m.__self__ is not None)):
                 # What's the use of putting watch monkeys on methods
                 # in addition to __setattr__?  Well, um, uh, if the
                 # methods modify their attributes (i.e. add a key to
@@ -628,7 +628,7 @@
         """Pretend to be the method I replaced, and ring the bell.
         """
         if self.oldMethod[1]:
-            rval = apply(self.oldMethod[1], a, kw)
+            rval = self.oldMethod[1](*a, **kw)
         else:
             rval = None
 
--- twisted/manhole/gladereactor.py (original)
+++ twisted/manhole/gladereactor.py (refactored)
@@ -28,32 +28,32 @@
     """
 
     def listenTCP(self, port, factory, backlog=50, interface=''):
-        from _inspectro import LoggingFactory
+        from ._inspectro import LoggingFactory
         factory = LoggingFactory(factory)
         return sup.listenTCP(self, port, factory, backlog, interface)
     
     def connectTCP(self, host, port, factory, timeout=30, bindAddress=None):
-        from _inspectro import LoggingFactory
+        from ._inspectro import LoggingFactory
         factory = LoggingFactory(factory)
         return sup.connectTCP(self, host, port, factory, timeout, bindAddress)
 
     def listenSSL(self, port, factory, contextFactory, backlog=50, interface=''):
-        from _inspectro import LoggingFactory
+        from ._inspectro import LoggingFactory
         factory = LoggingFactory(factory)
         return sup.listenSSL(self, port, factory, contextFactory, backlog, interface)
 
     def connectSSL(self, host, port, factory, contextFactory, timeout=30, bindAddress=None):
-        from _inspectro import LoggingFactory
+        from ._inspectro import LoggingFactory
         factory = LoggingFactory(factory)
         return sup.connectSSL(self, host, port, factory, contextFactory, timeout, bindAddress)
 
     def connectUNIX(self, address, factory, timeout=30):
-        from _inspectro import LoggingFactory
+        from ._inspectro import LoggingFactory
         factory = LoggingFactory(factory)
         return sup.connectUNIX(self, address, factory, timeout)
 
-    def listenUNIX(self, address, factory, backlog=50, mode=0666):
-        from _inspectro import LoggingFactory
+    def listenUNIX(self, address, factory, backlog=50, mode=0o666):
+        from ._inspectro import LoggingFactory
         factory = LoggingFactory(factory)
         return sup.listenUNIX(self, address, factory, backlog, mode)
 
@@ -64,14 +64,14 @@
     def on_viewlog_clicked(self, w):
         store, iter = self.servers.get_selection().get_selected()
         data = store[iter][1]
-        from _inspectro import LogViewer
+        from ._inspectro import LogViewer
         if hasattr(data, "protocol") and not data.protocol.logViewer:
             LogViewer(data.protocol)
     
     def on_inspect_clicked(self, w):
         store, iter = self.servers.get_selection().get_selected()
         data = store[iter]
-        from _inspectro import Inspectro
+        from ._inspectro import Inspectro
         Inspectro(data[1])
 
     def on_suspend_clicked(self, w):
@@ -117,7 +117,7 @@
         self.xml = gtk.glade.XML(util.sibpath(__file__,"gladereactor.glade"))
         d = {}
         for m in reflect.prefixedMethods(self, "on_"):
-            d[m.im_func.__name__] = m
+            d[m.__func__.__name__] = m
         self.xml.signal_autoconnect(d)
         self.xml.get_widget('window1').connect('destroy',
                                                lambda w: self.stop())
--- twisted/manhole/service.py (original)
+++ twisted/manhole/service.py (refactored)
@@ -15,10 +15,10 @@
 from zope.interface import implements, Interface
 
 # sibling imports
-import explorer
+from . import explorer
 
 # system imports
-from cStringIO import StringIO
+from io import StringIO
 
 import string
 import sys
@@ -51,7 +51,7 @@
         outlist = []
         last_type = inlist[0]
         block_begin = 0
-        for i in xrange(1, len(self.list)):
+        for i in range(1, len(self.list)):
             (mtype, message) = inlist[i]
             if mtype == last_type:
                 continue
@@ -59,8 +59,7 @@
                 if (i - block_begin) == 1:
                     outlist.append(inlist[block_begin])
                 else:
-                    messages = map(lambda l: l[1],
-                                   inlist[block_begin:i])
+                    messages = [l[1] for l in inlist[block_begin:i]]
                     message = string.join(messages, '')
                     outlist.append((last_type, message))
                 last_type = mtype
@@ -119,7 +118,7 @@
         kw = {}
     if localNS is None:
         localNS = globalNS
-    if (globalNS is None) and (not callable(command)):
+    if (globalNS is None) and (not hasattr(command, '__call__')):
         raise ValueError("Need a namespace to evaluate the command in.")
 
     try:
@@ -128,8 +127,8 @@
         sys.stdout = fakeout
         sys.stderr = fakeerr
         try:
-            if callable(command):
-                val = apply(command, args, kw)
+            if hasattr(command, '__call__'):
+                val = command(*args, **kw)
             else:
                 try:
                     code = compile(command, filename, 'eval')
@@ -202,7 +201,7 @@
     def __getstate__(self):
         state = self.__dict__.copy()
         state['clients'] = {}
-        if state['localNamespace'].has_key("__builtins__"):
+        if "__builtins__" in state['localNamespace']:
             del state['localNamespace']['__builtins__']
         return state
 
@@ -250,15 +249,15 @@
     def console(self, message):
         """Pass a message to my clients' console.
         """
-        clients = self.clients.keys()
+        clients = list(self.clients.keys())
         origMessage = message
         compatMessage = None
         for client in clients:
             try:
-                if not client.capabilities.has_key("Failure"):
+                if "Failure" not in client.capabilities:
                     if compatMessage is None:
                         compatMessage = origMessage[:]
-                        for i in xrange(len(message)):
+                        for i in range(len(message)):
                             if ((message[i][0] == "exception") and
                                 isinstance(message[i][1], failure.Failure)):
                                 compatMessage[i] = (
@@ -274,7 +273,7 @@
     def receiveExplorer(self, objectLink):
         """Pass an Explorer on to my clients.
         """
-        clients = self.clients.keys()
+        clients = list(self.clients.keys())
         for client in clients:
             try:
                 client.callRemote('receiveExplorer', objectLink)
@@ -394,6 +393,6 @@
         dict = self.__dict__.copy()
         ns = dict['namespace'].copy()
         dict['namespace'] = ns
-        if ns.has_key('__builtins__'):
+        if '__builtins__' in ns:
             del ns['__builtins__']
         return dict
--- twisted/manhole/telnet.py (original)
+++ twisted/manhole/telnet.py (refactored)
@@ -11,7 +11,7 @@
 
 # system imports
 import string, copy, sys
-from cStringIO import StringIO
+from io import StringIO
 
 
 class Shell(telnet.Telnet):
@@ -62,8 +62,8 @@
             except:
                 try:
                     code = compile(cmd, fn, 'exec')
-                    exec code in self.factory.namespace
-                except SyntaxError, e:
+                    exec(code, self.factory.namespace)
+                except SyntaxError as e:
                     if not self.lineBuffer and str(e)[:14] == "unexpected EOF":
                         self.lineBuffer.append(cmd)
                         self.transport.write("... ")
@@ -112,6 +112,6 @@
         dict = self.__dict__
         ns = copy.copy(dict['namespace'])
         dict['namespace'] = ns
-        if ns.has_key('__builtins__'):
+        if '__builtins__' in ns:
             del ns['__builtins__']
         return dict
--- twisted/manhole/ui/gtk2manhole.py (original)
+++ twisted/manhole/ui/gtk2manhole.py (refactored)
@@ -132,10 +132,10 @@
         self.buffer = textView.get_buffer()
 
         # TODO: Make this a singleton tag table.
-        for name, props in tagdefs.iteritems():
+        for name, props in tagdefs.items():
             tag = self.buffer.create_tag(name)
             # This can be done in the constructor in newer pygtk (post 1.99.14)
-            for k, v in props.iteritems():
+            for k, v in props.items():
                 tag.set_property(k, v)
 
         self.buffer.tag_table.lookup("default").set_priority(0)
@@ -236,7 +236,7 @@
                 self, 'key_%s' % ksym, lambda *a, **kw: None)(entry, event)
 
         if self.__debug:
-            print ksym
+            print(ksym)
         return rvalue
 
     def getText(self):
@@ -253,7 +253,7 @@
         # Figure out if that Return meant "next line" or "execute."
         try:
             c = code.compile_command(text)
-        except SyntaxError, e:
+        except SyntaxError as e:
             # This could conceivably piss you off if the client's python
             # doesn't accept keywords that are known to the manhole's
             # python.
@@ -261,7 +261,7 @@
             buffer.place(point)
             # TODO: Componentize!
             self.toplevel.output.append(str(e), "exception")
-        except (OverflowError, ValueError), e:
+        except (OverflowError, ValueError) as e:
             self.toplevel.output.append(str(e), "exception")
         else:
             if c is not None:
@@ -352,7 +352,7 @@
 
     def remote_console(self, messages):
         for kind, content in messages:
-            if isinstance(content, types.StringTypes):
+            if isinstance(content, str):
                 self.original.output.append(content, kind)
             elif (kind == "exception") and isinstance(content, failure.Failure):
                 content.printTraceback(_Notafile(self.original.output,
--- twisted/manhole/ui/gtkmanhole.py (original)
+++ twisted/manhole/ui/gtkmanhole.py (refactored)
@@ -23,7 +23,7 @@
 False = gtk.FALSE
 
 try:
-    import spelunk_gnome
+    from . import spelunk_gnome
 except ImportError:
     _GNOME_POWER = False
 else:
@@ -39,7 +39,7 @@
 ##             return pos+1
 ##     return 0
 
-import pywidgets
+from . import pywidgets
 
 class Interaction(pywidgets.Interaction, pb.Referenceable):
     loginWindow = None
@@ -138,24 +138,24 @@
         # select referenced objects to browse them with
         # browse(selectedLink.identifier)
 
-        if obj.type in map(explorer.typeString, [types.FunctionType,
-                                                 types.MethodType]):
+        if obj.type in list(map(explorer.typeString, [types.FunctionType,
+                                                 types.MethodType])):
             arglist = []
             for arg in obj.value['signature']:
-                if arg.has_key('default'):
+                if 'default' in arg:
                     a = "%s=%s" % (arg['name'], arg['default'])
-                elif arg.has_key('list'):
+                elif 'list' in arg:
                     a = "*%s" % (arg['name'],)
-                elif arg.has_key('keywords'):
+                elif 'keywords' in arg:
                     a = "**%s" % (arg['name'],)
                 else:
                     a = arg['name']
                 arglist.append(a)
 
             things = ''
-            if obj.value.has_key('class'):
+            if 'class' in obj.value:
                 things = "Class: %s\n" % (obj.value['class'],)
-            if obj.value.has_key('self'):
+            if 'self' in obj.value:
                 things = things + "Self: %s\n" % (obj.value['self'],)
 
             s = "%(name)s(%(arglist)s)\n%(things)s\n%(doc)s\n" % {
--- twisted/manhole/ui/pywidgets.py (original)
+++ twisted/manhole/ui/pywidgets.py (refactored)
@@ -78,14 +78,14 @@
                     else:
                         # This will tell us it's a complete expression.
                         c = code.compile_command(text)
-                except SyntaxError, e:
+                except SyntaxError as e:
                     # Ding!
                     self.set_positionLineOffset(e.lineno, e.offset)
-                    print "offset", e.offset
+                    print("offset", e.offset)
                     errmsg = {'traceback': [],
                               'exception': [str(e) + '\n']}
                     self.toplevel.output.console([('exception', errmsg)])
-                except OverflowError, e:
+                except OverflowError as e:
                     e = traceback.format_exception_only(OverflowError, e)
                     errmsg = {'traceback': [],
                               'exception': e}
@@ -118,7 +118,7 @@
     def set_positionLineOffset(self, line, offset):
         text = self.get_chars(0, -1)
         pos = 0
-        for l in xrange(line - 1):
+        for l in range(line - 1):
             pos = string.index(text, '\n', pos) + 1
         pos = pos + offset - 1
         self.set_position(pos)
--- twisted/manhole/ui/spelunk_gnome.py (original)
+++ twisted/manhole/ui/spelunk_gnome.py (refactored)
@@ -45,12 +45,12 @@
 from twisted.manhole import explorer
 
 import string, sys, types
-import UserList
+import collections
 _PIXELS_PER_UNIT=10
 
 #### Support class.
 
-class PairList(UserList.UserList):
+class PairList(collections.UserList):
     """An ordered list of key, value pairs.
 
     Kinda like an ordered dictionary.  Made with small data sets
@@ -66,7 +66,7 @@
             return (None, None)
 
     def keys(self):
-        return map(lambda x: x[0], self.data)
+        return [x[0] for x in self.data]
 
 
 #### Public
@@ -91,7 +91,7 @@
         Explorer.canvas = self
 
     def receiveExplorer(self, xplorer):
-        if self.visages.has_key(xplorer.id):
+        if xplorer.id in self.visages:
             log.msg("Using cached visage for %d" % (xplorer.id, ))
             # Ikk.  Just because we just received this explorer, that
             # doesn't necessarily mean its attributes are fresh.  Fix
@@ -135,7 +135,7 @@
             klass = klass[0]
         spelunker = klass(self, group, canvas)
         if hasattr(canvas, "visages") \
-           and not canvas.visages.has_key(self.id):
+           and self.id not in canvas.visages:
             canvas.visages[self.id] = spelunker
 
         self.give_properties(spelunker)
@@ -162,13 +162,13 @@
         """Give a spelunker my properties in an ordered list.
         """
         valuelist = PairList()
-        for p in spelunker.propertyLabels.keys():
+        for p in list(spelunker.propertyLabels.keys()):
             value = getattr(self, p, None)
             valuelist.append((p,value))
         spelunker.fill_properties(valuelist)
 
     def give_attributes(self, spelunker):
-        for a in spelunker.groupLabels.keys():
+        for a in list(spelunker.groupLabels.keys()):
             things = getattr(self, a)
             spelunker.fill_attributeGroup(a, things)
 
@@ -354,12 +354,12 @@
 
         row = 1 # 0 is title
 
-        for name, value in attributes.items():
+        for name, value in list(attributes.items()):
             label = gtk.Label(name)
             label.set_name("AttributeName")
             label.set_alignment(0, 0)
 
-            if type(value) is types.StringType:
+            if type(value) is bytes:
                 widget = gtk.Label(value)
                 widget.set_alignment(0, 0)
             else:
@@ -471,7 +471,7 @@
 
     def signal_buttonPressEvent(self, widget, eventButton, unused_data):
         if eventButton.type == GDK._2BUTTON_PRESS:
-            if self.parent.canvas.visages.has_key(self.explorer.id):
+            if self.explorer.id in self.parent.canvas.visages:
                 visage = self.parent.canvas.visages[self.explorer.id]
             else:
                 visage = self.explorer.newVisage(self.parent.rootGroup,
@@ -557,7 +557,7 @@
     def getTextForLabel(self):
         signature = self.explorer.signature
         arglist = []
-        for arg in xrange(len(signature)):
+        for arg in range(len(signature)):
             name = signature.name[arg]
             hasDefault, default = signature.get_default(arg)
             if hasDefault:
--- twisted/names/authority.py (original)
+++ twisted/names/authority.py (refactored)
@@ -3,7 +3,7 @@
 # See LICENSE for details.
 
 
-from __future__ import nested_scopes
+
 
 import os
 import time
@@ -12,7 +12,7 @@
 from twisted.internet import defer
 from twisted.python import failure
 
-import common
+from . import common
 
 def getSerial(filename = '/tmp/twisted-names.serial'):
     """Return a monotonically increasing (across program runs) integer.
@@ -22,7 +22,7 @@
     """
     serial = time.strftime('%Y%m%d')
 
-    o = os.umask(0177)
+    o = os.umask(0o177)
     try:
         if not os.path.exists(filename):
             f = file(filename, 'w')
@@ -132,7 +132,7 @@
             else:
                 soa_ttl = default_ttl
             results = [dns.RRHeader(self.soa[0], dns.SOA, dns.IN, soa_ttl, self.soa[1], auth=True)]
-            for (k, r) in self.records.items():
+            for (k, r) in list(self.records.items()):
                 for rec in r:
                     if rec.ttl is not None:
                         ttl = rec.ttl
@@ -159,9 +159,9 @@
 
     def loadFile(self, filename):
         g, l = self.setupConfigNamespace(), {}
-        execfile(filename, g, l)
-        if not l.has_key('zone'):
-            raise ValueError, "No zone defined in " + filename
+        exec(open(filename).read(), g, l)
+        if 'zone' not in l:
+            raise ValueError("No zone defined in " + filename)
 
         self.records = {}
         for rr in l['zone']:
@@ -176,7 +176,7 @@
 
     def setupConfigNamespace(self):
         r = {}
-        items = dns.__dict__.iterkeys()
+        items = iter(dns.__dict__.keys())
         for record in [x for x in items if x.startswith('Record_')]:
             type = getattr(dns, record)
             f = self.wrapRecord(type)
@@ -223,7 +223,7 @@
         L = []
         for line in lines:
             L.append(line.split())
-        return filter(None, L)
+        return [_f for _f in L if _f]
 
 
     def parseLines(self, lines):
@@ -232,7 +232,7 @@
 
         self.records = {}
 
-        for (line, index) in zip(lines, range(len(lines))):
+        for (line, index) in zip(lines, list(range(len(lines)))):
             if line[0] == '$TTL':
                 TTL = dns.str2time(line[1])
             elif line[0] == '$ORIGIN':
@@ -254,7 +254,7 @@
         if f:
             f(ttl, type, domain, rdata)
         else:
-            raise NotImplementedError, "Record class %r not supported" % cls
+            raise NotImplementedError("Record class %r not supported" % cls)
 
 
     def class_IN(self, ttl, type, domain, rdata):
@@ -264,18 +264,18 @@
             r.ttl = ttl
             self.records.setdefault(domain.lower(), []).append(r)
 
-            print 'Adding IN Record', domain, ttl, r
+            print('Adding IN Record', domain, ttl, r)
             if type == 'SOA':
                 self.soa = (domain, r)
         else:
-            raise NotImplementedError, "Record type %r not supported" % type
+            raise NotImplementedError("Record type %r not supported" % type)
 
 
     #
     # This file ends here.  Read no further.
     #
     def parseRecordLine(self, origin, ttl, line):
-        MARKERS = dns.QUERY_CLASSES.values() + dns.QUERY_TYPES.values()
+        MARKERS = list(dns.QUERY_CLASSES.values()) + list(dns.QUERY_TYPES.values())
         cls = 'IN'
         owner = origin
 
@@ -297,7 +297,7 @@
             line = line[1:]
 #            print 'domain is ', domain
 
-        if line[0] in dns.QUERY_CLASSES.values():
+        if line[0] in list(dns.QUERY_CLASSES.values()):
             cls = line[0]
             line = line[1:]
 #            print 'cls is ', cls
@@ -309,7 +309,7 @@
             ttl = int(line[0])
             line = line[1:]
 #            print 'ttl is ', ttl
-            if line[0] in dns.QUERY_CLASSES.values():
+            if line[0] in list(dns.QUERY_CLASSES.values()):
                 cls = line[0]
                 line = line[1:]
 #                print 'cls is ', cls
--- twisted/names/cache.py (original)
+++ twisted/names/cache.py (refactored)
@@ -11,7 +11,7 @@
 from twisted.python import failure, log
 from twisted.internet import interfaces, defer
 
-import common
+from . import common
 
 class CacheResolver(common.ResolverBase):
     """A resolver that serves records from a local, memory cache."""
@@ -34,7 +34,7 @@
         self.__dict__ = state
 
         now = time.time()
-        for (k, (when, (ans, add, ns))) in self.cache.items():
+        for (k, (when, (ans, add, ns))) in list(self.cache.items()):
             diff = now - when
             for rec in ans + add + ns:
                 if rec.ttl < diff:
@@ -43,7 +43,7 @@
 
 
     def __getstate__(self):
-        for c in self.cancel.values():
+        for c in list(self.cancel.values()):
             c.cancel()
         self.cancel.clear()
         return self.__dict__
@@ -79,7 +79,7 @@
 
         self.cache[query] = (time.time(), payload)
 
-        if self.cancel.has_key(query):
+        if query in self.cancel:
             self.cancel[query].cancel()
 
         s = list(payload[0]) + list(payload[1]) + list(payload[2])
--- twisted/names/client.py (original)
+++ twisted/names/client.py (refactored)
@@ -119,7 +119,7 @@
         self.resolv = resolv
 
         if not len(self.servers) and not resolv:
-            raise ValueError, "No nameservers specified"
+            raise ValueError("No nameservers specified")
 
         self.factory = DNSClientFactory(self, timeout)
         self.factory.noisy = 0   # Be quiet by default
@@ -151,7 +151,7 @@
 
         try:
             resolvConf = file(self.resolv)
-        except IOError, e:
+        except IOError as e:
             if e.errno == errno.ENOENT:
                 # Missing resolv.conf is treated the same as an empty resolv.conf
                 self.parseConfig(())
--- twisted/names/common.py (original)
+++ twisted/names/common.py (refactored)
@@ -16,13 +16,13 @@
 
     def __init__(self):
         self.typeToMethod = {}
-        for (k, v) in typeToMethod.items():
+        for (k, v) in list(typeToMethod.items()):
             self.typeToMethod[k] = getattr(self, v)
 
     def query(self, query, timeout = None):
         try:
             return self.typeToMethod[query.type](str(query.name), timeout)
-        except KeyError, e:
+        except KeyError as e:
             return defer.fail(failure.Failure(NotImplementedError(str(self.__class__) + " " + str(query.type))))
 
     def _lookup(self, name, cls, type, timeout):
@@ -171,7 +171,8 @@
             ).addCallback(self._cbRecords, name, effort
             )
 
-    def _cbRecords(self, (ans, auth, add), name, effort):
+    def _cbRecords(self, xxx_todo_changeme, name, effort):
+        (ans, auth, add) = xxx_todo_changeme
         result = extractRecord(self, dns.Name(name), ans + auth + add, effort)
         if not result:
             raise error.DNSLookupError(name)
@@ -202,7 +203,7 @@
             from twisted.names import client
             r = client.Resolver(servers=[(str(r.payload.name), dns.PORT)])
             return r.lookupAddress(str(name)
-                ).addCallback(lambda (ans, auth, add): extractRecord(r, name, ans + auth + add, level - 1)
+                ).addCallback(lambda ans_auth_add: extractRecord(r, name, ans_auth_add[0] + ans_auth_add[1] + ans_auth_add[2], level - 1)
                 ).addBoth(lambda passthrough: (r.protocol.transport.stopListening(), passthrough)[1])
 
 typeToMethod = {
--- twisted/names/dns.py (original)
+++ twisted/names/dns.py (refactored)
@@ -20,9 +20,9 @@
 import struct, random, types, socket
 
 try:
-    import cStringIO as StringIO
+    import io as StringIO
 except ImportError:
-    import StringIO
+    import io
 
 AF_INET6 = socket.AF_INET6
 
@@ -47,7 +47,7 @@
 PORT = 53
 
 (A, NS, MD, MF, CNAME, SOA, MB, MG, MR, NULL, WKS, PTR, HINFO, MINFO, MX, TXT,
- RP, AFSDB) = range(1, 19)
+ RP, AFSDB) = list(range(1, 19))
 AAAA = 28
 SRV = 33
 NAPTR = 35
@@ -83,7 +83,7 @@
     DNAME: 'DNAME'
 }
 
-IXFR, AXFR, MAILB, MAILA, ALL_RECORDS = range(251, 256)
+IXFR, AXFR, MAILB, MAILA, ALL_RECORDS = list(range(251, 256))
 
 # "Extended" queries (Hey, half of these are deprecated, good job)
 EXT_QUERIES = {
@@ -95,10 +95,10 @@
 }
 
 REV_TYPES = dict([
-    (v, k) for (k, v) in QUERY_TYPES.items() + EXT_QUERIES.items()
+    (v, k) for (k, v) in list(QUERY_TYPES.items()) + list(EXT_QUERIES.items())
 ])
 
-IN, CS, CH, HS = range(1, 5)
+IN, CS, CH, HS = list(range(1, 5))
 ANY = 255
 
 QUERY_CLASSES = {
@@ -109,18 +109,18 @@
     ANY: 'ANY'
 }
 REV_CLASSES = dict([
-    (v, k) for (k, v) in QUERY_CLASSES.items()
+    (v, k) for (k, v) in list(QUERY_CLASSES.items())
 ])
 
 
 # Opcodes
-OP_QUERY, OP_INVERSE, OP_STATUS = range(3)
+OP_QUERY, OP_INVERSE, OP_STATUS = list(range(3))
 OP_NOTIFY = 4 # RFC 1996
 OP_UPDATE = 5 # RFC 2136
 
 
 # Response Codes
-OK, EFORMAT, ESERVER, ENAME, ENOTIMP, EREFUSED = range(6)
+OK, EFORMAT, ESERVER, ENAME, ENOTIMP, EREFUSED = list(range(6))
 
 class IRecord(Interface):
     """
@@ -141,7 +141,7 @@
         ('S', 1), ('M', 60), ('H', 60 * 60), ('D', 60 * 60 * 24),
         ('W', 60 * 60 * 24 * 7), ('Y', 60 * 60 * 24 * 365)
     )
-    if isinstance(s, types.StringType):
+    if isinstance(s, bytes):
         s = s.upper().strip()
         for (suff, mult) in suffixes:
             if s.endswith(suff):
@@ -149,7 +149,7 @@
         try:
             s = int(s)
         except ValueError:
-            raise ValueError, "Invalid time interval specifier: " + s
+            raise ValueError("Invalid time interval specifier: " + s)
     return s
 
 
@@ -255,7 +255,7 @@
     implements(IEncodable)
 
     def __init__(self, name=''):
-        assert isinstance(name, types.StringTypes), "%r is not a string" % (name,)
+        assert isinstance(name, str), "%r is not a string" % (name,)
         self.name = name
 
     def encode(self, strio, compDict=None):
@@ -1470,7 +1470,7 @@
 
     def encode(self, strio):
         compDict = {}
-        body_tmp = StringIO.StringIO()
+        body_tmp = io.StringIO()
         for q in self.queries:
             q.encode(body_tmp, compDict)
         for q in self.answers:
@@ -1548,13 +1548,13 @@
 
 
     def toStr(self):
-        strio = StringIO.StringIO()
+        strio = io.StringIO()
         self.encode(strio)
         return strio.getvalue()
 
 
     def fromStr(self, str):
-        strio = StringIO.StringIO(str)
+        strio = io.StringIO(str)
         self.decode(strio)
 
 class DNSMixin(object):
--- twisted/names/hosts.py (original)
+++ twisted/names/hosts.py (refactored)
@@ -38,7 +38,7 @@
     def upgradeToVersion1(self):
         # <3 exarkun
         self.typeToMethod = {}
-        for (k, v) in common.typeToMethod.items():
+        for (k, v) in list(common.typeToMethod.items()):
             self.typeToMethod[k] = getattr(self, v)
 
 
--- twisted/names/resolve.py (original)
+++ twisted/names/resolve.py (refactored)
@@ -14,7 +14,7 @@
 from twisted.internet import defer, interfaces
 from twisted.names import dns
 from zope.interface import implements
-import common
+from . import common
 
 class FailureHandler:
     def __init__(self, resolver, query, timeout):
--- twisted/names/root.py (original)
+++ twisted/names/root.py (refactored)
@@ -15,7 +15,7 @@
     documentation
 """
 
-from __future__ import generators
+
 
 import sys
 
@@ -197,7 +197,7 @@
 
 if __name__ == '__main__':
     if len(sys.argv) < 2:
-        print 'Specify a domain'
+        print('Specify a domain')
     else:
         log.startLogging(sys.stdout)
         from twisted.names.client import ThreadedResolver
--- twisted/names/server.py (original)
+++ twisted/names/server.py (refactored)
@@ -95,7 +95,8 @@
             log.msg("Processed query in %0.3f seconds" % (time.time() - message.timeReceived))
 
 
-    def gotResolverResponse(self, (ans, auth, add), protocol, message, address):
+    def gotResolverResponse(self, xxx_todo_changeme, protocol, message, address):
+        (ans, auth, add) = xxx_todo_changeme
         message.rCode = dns.OK
         message.answers = ans
         for x in ans:
--- twisted/names/srvconnect.py (original)
+++ twisted/names/srvconnect.py (refactored)
@@ -84,7 +84,8 @@
         self.servers = []
         self.orderedServers = []
 
-    def _cbGotServers(self, (answers, auth, add)):
+    def _cbGotServers(self, xxx_todo_changeme):
+        (answers, auth, add) = xxx_todo_changeme
         if len(answers) == 1 and answers[0].type == dns.SRV \
                              and answers[0].payload \
                              and answers[0].payload.target == dns.Name('.'):
@@ -125,8 +126,8 @@
         self.servers.sort(self._serverCmp)
         minPriority=self.servers[0][0]
 
-        weightIndex = zip(xrange(len(self.servers)), [x[1] for x in self.servers
-                                                      if x[0]==minPriority])
+        weightIndex = list(zip(range(len(self.servers)), [x[1] for x in self.servers
+                                                      if x[0]==minPriority]))
         weightSum = reduce(lambda x, y: (None, x[1]+y[1]), weightIndex, (None, 0))[1]
         rand = random.randint(0, weightSum)
 
@@ -140,7 +141,7 @@
                 p, w, host, port = chosen
                 return host, port
 
-        raise RuntimeError, 'Impossible %s pickServer result.' % self.__class__.__name__
+        raise RuntimeError('Impossible %s pickServer result.' % self.__class__.__name__)
 
     def _reallyConnect(self):
         if self.stopAfterDNS:
--- twisted/names/tap.py (original)
+++ twisted/names/tap.py (refactored)
@@ -78,13 +78,13 @@
         for f in self.zonefiles:
             try:
                 self.zones.append(authority.PySourceAuthority(f))
-            except Exception, e:
+            except Exception as e:
                 traceback.print_exc()
                 raise usage.UsageError("Invalid syntax in " + f)
         for f in self.bindfiles:
             try:
                 self.zones.append(authority.BindAuthority(f))
-            except Exception, e:
+            except Exception as e:
                 traceback.print_exc()
                 raise usage.UsageError("Invalid syntax in " + f)
         for f in self.secondaries:
--- twisted/names/test/test_client.py (original)
+++ twisted/names/test/test_client.py (refactored)
@@ -161,7 +161,8 @@
         queries.pop()[-1].callback(response)
 
         d = defer.gatherResults([firstResult, secondResult])
-        def cbFinished((firstResponse, secondResponse)):
+        def cbFinished(xxx_todo_changeme):
+            (firstResponse, secondResponse) = xxx_todo_changeme
             self.assertEqual(firstResponse, ([answer], [], []))
             self.assertEqual(secondResponse, ([answer], [], []))
         d.addCallback(cbFinished)
@@ -433,10 +434,11 @@
         """
         client.theResolver = None
 
-    def checkResult(self, (results, authority, additional), qtype):
+    def checkResult(self, xxx_todo_changeme1, qtype):
         """
         Verify that the result is the same query type as what is expected.
         """
+        (results, authority, additional) = xxx_todo_changeme1
         result = results[0]
         self.assertEquals(str(result.name), self.hostname)
         self.assertEquals(result.type, qtype)
--- twisted/names/test/test_dns.py (original)
+++ twisted/names/test/test_dns.py (refactored)
@@ -7,9 +7,9 @@
 """
 
 try:
-    from cStringIO import StringIO
+    from io import StringIO
 except ImportError:
-    from StringIO import StringIO
+    from io import StringIO
 
 import struct
 
@@ -258,9 +258,9 @@
         Test content received after a query.
         """
         d = self.proto.query(('127.0.0.1', 21345), [dns.Query('foo')])
-        self.assertEquals(len(self.proto.liveMessages.keys()), 1)
+        self.assertEquals(len(list(self.proto.liveMessages.keys())), 1)
         m = dns.Message()
-        m.id = self.proto.liveMessages.items()[0][0]
+        m.id = list(self.proto.liveMessages.items())[0][0]
         m.answers = [dns.RRHeader(payload=dns.Record_A(address='1.2.3.4'))]
         called = False
         def cb(result):
@@ -380,9 +380,9 @@
         Test content received after a query.
         """
         d = self.proto.query([dns.Query('foo')])
-        self.assertEquals(len(self.proto.liveMessages.keys()), 1)
+        self.assertEquals(len(list(self.proto.liveMessages.keys())), 1)
         m = dns.Message()
-        m.id = self.proto.liveMessages.items()[0][0]
+        m.id = list(self.proto.liveMessages.items())[0][0]
         m.answers = [dns.RRHeader(payload=dns.Record_A(address='1.2.3.4'))]
         called = False
         def cb(result):
--- twisted/names/test/test_names.py (original)
+++ twisted/names/test/test_names.py (refactored)
@@ -5,7 +5,7 @@
 """
 Test cases for twisted.names.
 """
-from __future__ import nested_scopes
+
 
 import socket, operator, copy
 
@@ -197,9 +197,9 @@
             if isinstance(self.response, failure.Failure):
                 raise self.response
             results = justPayload(self.response)
-            assert len(results) == len(r), "%s != %s" % (map(str, results), map(str, r))
+            assert len(results) == len(r), "%s != %s" % (list(map(str, results)), list(map(str, r)))
             for rec in results:
-                assert rec in r, "%s not in %s" % (rec, map(str, r))
+                assert rec in r, "%s not in %s" % (rec, list(map(str, r)))
 
         d.addBoth(setDone)
         d.addCallback(checkResults)
@@ -386,7 +386,7 @@
     def testZoneTransfer(self):
         """Test DNS 'AXFR' queries (Zone transfer)"""
         default_ttl = soa_record.expire
-        results = [copy.copy(r) for r in reduce(operator.add, test_domain_com.records.values())]
+        results = [copy.copy(r) for r in reduce(operator.add, list(test_domain_com.records.values()))]
         for r in results:
             if r.ttl is None:
                 r.ttl = default_ttl
--- twisted/news/database.py (original)
+++ twisted/news/database.py (refactored)
@@ -15,7 +15,7 @@
 
 import getpass, pickle, time, socket
 import os
-import StringIO
+import io
 
 from zope.interface import implements, Interface
 
@@ -28,7 +28,7 @@
 
 
 
-ERR_NOGROUP, ERR_NOARTICLE = range(2, 4)  # XXX - put NNTP values here (I guess?)
+ERR_NOGROUP, ERR_NOARTICLE = list(range(2, 4))  # XXX - put NNTP values here (I guess?)
 
 OVERVIEW_FMT = [
     'Subject', 'From', 'Date', 'Message-ID', 'References',
@@ -36,7 +36,7 @@
 ]
 
 def hexdigest(md5): #XXX: argh. 1.5.2 doesn't have this.
-    return ''.join(map(lambda x: hex(ord(x))[2:], md5.digest()))
+    return ''.join([hex(ord(x))[2:] for x in md5.digest()])
 
 class Article:
     def __init__(self, head, body):
@@ -69,7 +69,7 @@
 
     def getHeader(self, header):
         h = header.lower()
-        if self.headers.has_key(h):
+        if h in self.headers:
             return self.headers[h][1]
         else:
             return ''
@@ -81,7 +81,7 @@
 
     def textHeaders(self):
         headers = []
-        for i in self.headers.values():
+        for i in list(self.headers.values()):
             headers.append('%s: %s' % i)
         return '\r\n'.join(headers) + '\r\n'
 
@@ -252,7 +252,7 @@
         moderators = []
         for group in groups:
             moderators.append(self.db['moderators'].get(group, None))
-        return filter(None, moderators)
+        return [_f for _f in moderators if _f]
 
 
     def notifyModerators(self, moderators, article):
@@ -263,7 +263,7 @@
             'twisted@' + socket.gethostname(),
             moderators,
             article.body,
-            dict(article.headers.values())
+            dict(list(article.headers.values()))
         )
 
 
@@ -272,12 +272,12 @@
         l = self.db['groups']
         r = []
         for i in l:
-            if len(self.db[i].keys()):
+            if len(list(self.db[i].keys())):
                 low = min(self.db[i].keys())
                 high = max(self.db[i].keys()) + 1
             else:
                 low = high = 0
-            if self.db['moderators'].has_key(i):
+            if i in self.db['moderators']:
                 flags = 'm'
             else:
                 flags = 'y'
@@ -301,8 +301,8 @@
             return self.notifyModerators(moderators, a)
 
         for group in groups:
-            if self.db.has_key(group):
-                if len(self.db[group].keys()):
+            if group in self.db:
+                if len(list(self.db[group].keys())):
                     index = max(self.db[group].keys()) + 1
                 else:
                     index = 1
@@ -314,7 +314,7 @@
 
         a.putHeader('Xref', '%s %s' % (
             socket.gethostname().split()[0],
-            ''.join(map(lambda x: ':'.join(x), xref))
+            ''.join([':'.join(x) for x in xref])
         ))
 
         self.flush()
@@ -326,35 +326,35 @@
 
 
     def xoverRequest(self, group, low, high):
-        if not self.db.has_key(group):
+        if group not in self.db:
             return defer.succeed([])
         r = []
-        for i in self.db[group].keys():
+        for i in list(self.db[group].keys()):
             if (low is None or i >= low) and (high is None or i <= high):
                 r.append([str(i)] + self.db[group][i].overview())
         return defer.succeed(r)
 
 
     def xhdrRequest(self, group, low, high, header):
-        if not self.db.has_key(group):
+        if group not in self.db:
             return defer.succeed([])
         r = []
-        for i in self.db[group].keys():
+        for i in list(self.db[group].keys()):
             if low is None or i >= low and high is None or i <= high:
                 r.append((i, self.db[group][i].getHeader(header)))
         return defer.succeed(r)
 
 
     def listGroupRequest(self, group):
-        if self.db.has_key(group):
-            return defer.succeed((group, self.db[group].keys()))
+        if group in self.db:
+            return defer.succeed((group, list(self.db[group].keys())))
         else:
             return defer.fail(None)
 
     def groupRequest(self, group):
-        if self.db.has_key(group):
-            if len(self.db[group].keys()):
-                num = len(self.db[group].keys())
+        if group in self.db:
+            if len(list(self.db[group].keys())):
+                num = len(list(self.db[group].keys()))
                 low = min(self.db[group].keys())
                 high = max(self.db[group].keys())
             else:
@@ -366,8 +366,8 @@
 
 
     def articleExistsRequest(self, id):
-        for g in self.db.values():
-            for a in g.values():
+        for g in list(self.db.values()):
+            for a in list(g.values()):
                 if a.getHeader('Message-ID') == id:
                     return defer.succeed(1)
         return defer.succeed(0)
@@ -377,13 +377,13 @@
         if id is not None:
             raise NotImplementedError
 
-        if self.db.has_key(group):
-            if self.db[group].has_key(index):
+        if group in self.db:
+            if index in self.db[group]:
                 a = self.db[group][index]
                 return defer.succeed((
                     index,
                     a.getHeader('Message-ID'),
-                    StringIO.StringIO(a.textHeaders() + '\r\n' + a.body)
+                    io.StringIO(a.textHeaders() + '\r\n' + a.body)
                 ))
             else:
                 return defer.fail(ERR_NOARTICLE)
@@ -392,8 +392,8 @@
 
 
     def headRequest(self, group, index):
-        if self.db.has_key(group):
-            if self.db[group].has_key(index):
+        if group in self.db:
+            if index in self.db[group]:
                 a = self.db[group][index]
                 return defer.succeed((index, a.getHeader('Message-ID'), a.textHeaders()))
             else:
@@ -403,10 +403,10 @@
 
 
     def bodyRequest(self, group, index):
-        if self.db.has_key(group):
-            if self.db[group].has_key(index):
+        if group in self.db:
+            if index in self.db[group]:
                 a = self.db[group][index]
-                return defer.succeed((index, a.getHeader('Message-ID'), StringIO.StringIO(a.body)))
+                return defer.succeed((index, a.getHeader('Message-ID'), io.StringIO(a.body)))
             else:
                 return defer.fail(ERR_NOARTICLE)
         else:
@@ -420,13 +420,13 @@
 
 
     def load(self, filename, groups = None, moderators = ()):
-        if PickleStorage.sharedDBs.has_key(filename):
+        if filename in PickleStorage.sharedDBs:
             self.db = PickleStorage.sharedDBs[filename]
         else:
             try:
                 self.db = pickle.load(open(filename))
                 PickleStorage.sharedDBs[filename] = self.db
-            except IOError, e:
+            except IOError as e:
                 self.db = PickleStorage.sharedDBs[filename] = {}
                 self.db['groups'] = groups
                 if groups is not None:
@@ -464,7 +464,7 @@
             os.mkdir(path)
 
         self.dbm = dirdbm.Shelf(os.path.join(path, "newsshelf"))
-        if not len(self.dbm.keys()):
+        if not len(list(self.dbm.keys())):
             self.initialize()
 
 
@@ -496,7 +496,7 @@
 
     def listRequest(self):
         result = []
-        for g in self.dbm['groups'].values():
+        for g in list(self.dbm['groups'].values()):
             result.append((g.name, g.maxArticle, g.minArticle, g.flags))
         return defer.succeed(result)
 
@@ -519,14 +519,14 @@
     def notifyModerator(self, moderator, article):
         # Moderated postings go through as long as they have an Approved
         # header, regardless of what the value is
-        print 'To is ', moderator
+        print('To is ', moderator)
         article.putHeader('To', moderator)
         return smtp.sendEmail(
             self.mailhost,
             'twisted-news@' + socket.gethostname(),
             moderator,
             article.body,
-            dict(article.headers.values())
+            dict(list(article.headers.values()))
         )
 
 
@@ -559,7 +559,7 @@
         if not xref:
             return defer.fail(NewsServerError("No groups carried: " + ' '.join(groups)))
 
-        article.putHeader('Xref', '%s %s' % (socket.gethostname().split()[0], ' '.join(map(lambda x: ':'.join(x), xref))))
+        article.putHeader('Xref', '%s %s' % (socket.gethostname().split()[0], ' '.join([':'.join(x) for x in xref])))
         self.dbm['Message-IDs'][article.getHeader('Message-ID')] = xref
         return defer.succeed(None)
 
@@ -569,7 +569,7 @@
 
 
     def xoverRequest(self, group, low, high):
-        if not self.dbm['groups'].has_key(group):
+        if group not in self.dbm['groups']:
             return defer.succeed([])
 
         if low is None:
@@ -578,7 +578,7 @@
             high = self.dbm['groups'][group].maxArticle
         r = []
         for i in range(low, high + 1):
-            if self.dbm['groups'][group].articles.has_key(i):
+            if i in self.dbm['groups'][group].articles:
                 r.append([str(i)] + self.dbm['groups'][group].articles[i].overview())
         return defer.succeed(r)
 
@@ -593,14 +593,14 @@
             high = self.dbm['groups'][group].maxArticle
         r = []
         for i in range(low, high + 1):
-            if self.dbm['groups'][group].articles.has_key(i):
+            if i in self.dbm['groups'][group].articles:
                 r.append((i, self.dbm['groups'][group].articles[i].getHeader(header)))
         return defer.succeed(r)
 
 
     def listGroupRequest(self, group):
-        if self.dbm['groups'].has_key(group):
-            return defer.succeed((group, self.dbm['groups'][group].articles.keys()))
+        if group in self.dbm['groups']:
+            return defer.succeed((group, list(self.dbm['groups'][group].articles.keys())))
         return defer.fail(NewsServerError("No such group: " + group))
 
 
@@ -639,7 +639,7 @@
             return defer.succeed((
                 index,
                 a.getHeader('Message-ID'),
-                StringIO.StringIO(a.textHeaders() + '\r\n' + a.body)
+                io.StringIO(a.textHeaders() + '\r\n' + a.body)
             ))
 
 
@@ -676,7 +676,7 @@
         except KeyError:
             return defer.fail(NewsServerError("No such group: " + group))
         else:
-            return defer.succeed((index, a.getHeader('Message-ID'), StringIO.StringIO(a.body)))
+            return defer.succeed((index, a.getHeader('Message-ID'), io.StringIO(a.body)))
 
 
 class NewsStorageAugmentation:
@@ -947,7 +947,7 @@
             lambda result: (
                 result[0][0],
                 result[0][1],
-                StringIO.StringIO(result[0][2] + '\r\n' + result[0][3])
+                io.StringIO(result[0][2] + '\r\n' + result[0][3])
             )
         )
 
@@ -978,7 +978,7 @@
         return self.dbpool.runQuery(sql).addCallback(
             lambda result: result[0]
         ).addCallback(
-            lambda (index, id, body): (index, id, StringIO.StringIO(body))
+            lambda index_id_body: (index_id_body[0], index_id_body[1], io.StringIO(index_id_body[2]))
         )
 
 ####
--- twisted/news/news.py (original)
+++ twisted/news/news.py (refactored)
@@ -37,7 +37,7 @@
 
 
     def clientConnectionFailed(self, connector, reason):
-        print 'Connection failed: ', reason
+        print('Connection failed: ', reason)
     
     
     def updateChecks(self, addr):
--- twisted/news/nntp.py (original)
+++ twisted/news/nntp.py (refactored)
@@ -34,9 +34,9 @@
 import types
 
 try:
-    import cStringIO as StringIO
+    import io as StringIO
 except:
-    import StringIO
+    import io
 
 from twisted.protocols import basic
 from twisted.python import log
@@ -47,7 +47,7 @@
         try:
             a = int(articles[0])
             return a, a
-        except ValueError, e:
+        except ValueError as e:
             return None, None
     elif len(articles) == 2:
         try:
@@ -59,7 +59,7 @@
                 h = int(articles[1])
             else:
                 h = None
-        except ValueError, e:
+        except ValueError as e:
             return None, None
     return l, h
 
@@ -406,7 +406,8 @@
         log.err('Passive Error: %s' % (error,))
 
 
-    def _headerInitial(self, (code, message)):
+    def _headerInitial(self, xxx_todo_changeme):
+        (code, message) = xxx_todo_changeme
         if code == 200:
             self.canPost = 1
         else:
@@ -416,7 +417,7 @@
 
     def _stateList(self, line):
         if line != '.':
-            data = filter(None, line.strip().split())
+            data = [_f for _f in line.strip().split() if _f]
             self._newLine((data[0], int(data[1]), int(data[2]), data[3]), 0)
         else:
             self.gotAllGroups(self._endState())
@@ -424,7 +425,7 @@
 
     def _stateOverview(self, line):
         if line != '.':
-            self._newLine(filter(None, line.strip().split()), 0)
+            self._newLine([_f for _f in line.strip().split() if _f], 0)
         else:
             self.gotOverview(self._endState())
 
@@ -436,7 +437,8 @@
             self.gotSubscriptions(self._endState())
 
 
-    def _headerGroup(self, (code, line)):
+    def _headerGroup(self, xxx_todo_changeme1):
+        (code, line) = xxx_todo_changeme1
         self.gotGroup(tuple(line.split()))
         self._endState()
 
@@ -466,7 +468,8 @@
             self.gotBody('\n'.join(self._endState())+'\n')
 
 
-    def _headerPost(self, (code, message)):
+    def _headerPost(self, xxx_todo_changeme2):
+        (code, message) = xxx_todo_changeme2
         if code == 340:
             self.transport.write(self._postText[0].replace('\n', '\r\n').replace('\r\n.', '\r\n..'))
             if self._postText[0][-1:] != '\n':
@@ -479,7 +482,8 @@
         self._endState()
 
 
-    def _headerPosted(self, (code, message)):
+    def _headerPosted(self, xxx_todo_changeme3):
+        (code, message) = xxx_todo_changeme3
         if code == 240:
             self.postedOk()
         else:
@@ -508,7 +512,8 @@
             self.gotNewGroups(self._endState())
 
 
-    def _headerMode(self, (code, message)):
+    def _headerMode(self, xxx_todo_changeme4):
+        (code, message) = xxx_todo_changeme4
         if code == 203:
             self.setStreamSuccess()
         else:
@@ -587,7 +592,7 @@
 
 
     def _errList(self, failure):
-        print 'LIST failed: ', failure
+        print('LIST failed: ', failure)
         self.sendLine('503 program fault - command not performed')
 
 
@@ -599,7 +604,7 @@
 
 
     def _errSubscription(self, failure):
-        print 'SUBSCRIPTIONS failed: ', failure
+        print('SUBSCRIPTIONS failed: ', failure)
         self.sendLine('503 program fault - comand not performed')
 
 
@@ -611,7 +616,7 @@
 
 
     def _errOverview(self, failure):
-        print 'LIST OVERVIEW.FMT failed: ', failure
+        print('LIST OVERVIEW.FMT failed: ', failure)
         self.sendLine('503 program fault - command not performed')
 
 
@@ -624,7 +629,8 @@
             defer.addCallbacks(self._gotListGroup, self._errListGroup)
 
 
-    def _gotListGroup(self, (group, articles)):
+    def _gotListGroup(self, xxx_todo_changeme5):
+        (group, articles) = xxx_todo_changeme5
         self.currentGroup = group
         if len(articles):
             self.currentIndex = int(articles[0])
@@ -638,7 +644,7 @@
 
 
     def _errListGroup(self, failure):
-        print 'LISTGROUP failed: ', failure
+        print('LISTGROUP failed: ', failure)
         self.sendLine('502 no permission')
 
 
@@ -659,7 +665,7 @@
 
 
     def _errXOver(self, failure):
-        print 'XOVER failed: ', failure
+        print('XOVER failed: ', failure)
         self.sendLine('420 No article(s) selected')
 
 
@@ -696,7 +702,7 @@
         self.sendLine('.')
 
     def _errXHDR(self, failure):
-        print 'XHDR failed: ', failure
+        print('XHDR failed: ', failure)
         self.sendLine('502 no permission')
 
 
@@ -714,7 +720,7 @@
 
 
     def _errXROVER(self, failure):
-        print 'XROVER failed: ',
+        print('XROVER failed: ', end=' ')
         self._errXHDR(failure)
 
 
@@ -741,7 +747,7 @@
         
     
     def _errPost(self, failure):
-        print 'POST failed: ', failure
+        print('POST failed: ', failure)
         self.sendLine('441 posting failed')
 
 
@@ -758,7 +764,7 @@
     
     
     def _errCheck(self, failure):
-        print 'CHECK failed: ', failure
+        print('CHECK failed: ', failure)
         self.sendLine('431 try sending it again later')
 
 
@@ -783,7 +789,7 @@
     
     
     def _errTakeThis(self, failure):
-        print 'TAKETHIS failed: ', failure
+        print('TAKETHIS failed: ', failure)
         self.sendLine('439 article transfer failed')
 
 
@@ -792,14 +798,15 @@
         defer.addCallbacks(self._gotGroup, self._errGroup)
 
     
-    def _gotGroup(self, (name, num, high, low, flags)):
+    def _gotGroup(self, xxx_todo_changeme6):
+        (name, num, high, low, flags) = xxx_todo_changeme6
         self.currentGroup = name
         self.currentIndex = low
         self.sendLine('211 %d %d %d %s group selected' % (num, low, high, name))
     
     
     def _errGroup(self, failure):
-        print 'GROUP failed: ', failure
+        print('GROUP failed: ', failure)
         self.sendLine('411 no such group')
 
 
@@ -819,7 +826,7 @@
                     try:
                         article = int(article)
                         return func(self.currentGroup, article) 
-                    except ValueError, e:
+                    except ValueError as e:
                         self.sendLine('501 command syntax error')
 
 
@@ -829,14 +836,15 @@
             defer.addCallbacks(self._gotArticle, self._errArticle)
 
 
-    def _gotArticle(self, (index, id, article)):
-        if isinstance(article, types.StringType):
+    def _gotArticle(self, xxx_todo_changeme7):
+        (index, id, article) = xxx_todo_changeme7
+        if isinstance(article, bytes):
             import warnings
             warnings.warn(
                 "Returning the article as a string from `articleRequest' "
                 "is deprecated.  Return a file-like object instead."
             )
-            article = StringIO.StringIO(article)
+            article = io.StringIO(article)
         self.currentIndex = index
         self.sendLine('220 %d %s article' % (index, id))
         s = basic.FileSender()
@@ -855,7 +863,7 @@
     ##
 
     def _errArticle(self, failure):
-        print 'ARTICLE failed: ', failure
+        print('ARTICLE failed: ', failure)
         self.sendLine('423 bad article number')
 
 
@@ -865,13 +873,14 @@
             defer.addCallbacks(self._gotStat, self._errStat)
     
     
-    def _gotStat(self, (index, id, article)):
+    def _gotStat(self, xxx_todo_changeme8):
+        (index, id, article) = xxx_todo_changeme8
         self.currentIndex = index
         self.sendLine('223 %d %s article retreived - request text separately' % (index, id))
 
 
     def _errStat(self, failure):
-        print 'STAT failed: ', failure
+        print('STAT failed: ', failure)
         self.sendLine('423 bad article number')
 
 
@@ -881,7 +890,8 @@
             defer.addCallbacks(self._gotHead, self._errHead)
     
     
-    def _gotHead(self, (index, id, head)):
+    def _gotHead(self, xxx_todo_changeme9):
+        (index, id, head) = xxx_todo_changeme9
         self.currentIndex = index
         self.sendLine('221 %d %s article retrieved' % (index, id))
         self.transport.write(head + '\r\n')
@@ -889,7 +899,7 @@
     
     
     def _errHead(self, failure):
-        print 'HEAD failed: ', failure
+        print('HEAD failed: ', failure)
         self.sendLine('423 no such article number in this group')
 
 
@@ -899,14 +909,15 @@
             defer.addCallbacks(self._gotBody, self._errBody)
 
 
-    def _gotBody(self, (index, id, body)):
-        if isinstance(body, types.StringType):
+    def _gotBody(self, xxx_todo_changeme10):
+        (index, id, body) = xxx_todo_changeme10
+        if isinstance(body, bytes):
             import warnings
             warnings.warn(
                 "Returning the article as a string from `articleRequest' "
                 "is deprecated.  Return a file-like object instead."
             )
-            body = StringIO.StringIO(body)
+            body = io.StringIO(body)
         self.currentIndex = index
         self.sendLine('221 %d %s article retrieved' % (index, id))
         self.lastsent = ''
@@ -915,7 +926,7 @@
         d.addCallback(self.finishedFileTransfer)
 
     def _errBody(self, failure):
-        print 'BODY failed: ', failure
+        print('BODY failed: ', failure)
         self.sendLine('423 no such article number in this group')
 
 
@@ -1008,7 +1019,7 @@
     
     
     def _errIHAVE(self, failure):
-        print 'IHAVE failed: ', failure
+        print('IHAVE failed: ', failure)
         self.sendLine('436 transfer failed - try again later')
 
 
--- twisted/news/tap.py (original)
+++ twisted/news/tap.py (refactored)
@@ -125,7 +125,7 @@
         else:
             db.addGroup(g, 'y')
     for s in config.subscriptions:
-        print s
+        print(s)
         db.addSubscription(s)
     s = config['port']
     if config['interface']:
--- twisted/pair/ethernet.py (original)
+++ twisted/pair/ethernet.py (refactored)
@@ -39,9 +39,9 @@
     def addProto(self, num, proto):
         proto = raw.IRawPacketProtocol(proto)
         if num < 0:
-            raise TypeError, 'Added protocol must be positive or zero'
+            raise TypeError('Added protocol must be positive or zero')
         if num >= 2**16:
-            raise TypeError, 'Added protocol must fit in 16 bits'
+            raise TypeError('Added protocol must fit in 16 bits')
         if num not in self.etherProtos:
             self.etherProtos[num] = []
         self.etherProtos[num].append(proto)
--- twisted/pair/ip.py (original)
+++ twisted/pair/ip.py (refactored)
@@ -29,7 +29,7 @@
         self.dont_fragment = (frag_off & 0x4000 != 0)
         self.more_fragments = (frag_off & 0x2000 != 0)
 
-MAX_SIZE = 2L**32
+MAX_SIZE = 2**32
 
 class IPProtocol(protocol.AbstractDatagramProtocol):
     implements(raw.IRawPacketProtocol)
@@ -40,9 +40,9 @@
     def addProto(self, num, proto):
         proto = raw.IRawDatagramProtocol(proto)
         if num < 0:
-            raise TypeError, 'Added protocol must be positive or zero'
+            raise TypeError('Added protocol must be positive or zero')
         if num >= MAX_SIZE:
-            raise TypeError, 'Added protocol must fit in 32 bits'
+            raise TypeError('Added protocol must fit in 32 bits')
         if num not in self.ipProtos:
             self.ipProtos[num] = []
         self.ipProtos[num].append(proto)
--- twisted/pair/rawudp.py (original)
+++ twisted/pair/rawudp.py (refactored)
@@ -25,11 +25,11 @@
 
     def addProto(self, num, proto):
         if not isinstance(proto, protocol.DatagramProtocol):
-            raise TypeError, 'Added protocol must be an instance of DatagramProtocol'
+            raise TypeError('Added protocol must be an instance of DatagramProtocol')
         if num < 0:
-            raise TypeError, 'Added protocol must be positive or zero'
+            raise TypeError('Added protocol must be positive or zero')
         if num >= 2**16:
-            raise TypeError, 'Added protocol must fit in 16 bits'
+            raise TypeError('Added protocol must fit in 16 bits')
         if num not in self.udpProtos:
             self.udpProtos[num] = []
         self.udpProtos[num].append(proto)
--- twisted/pair/tuntap.py (original)
+++ twisted/pair/tuntap.py (refactored)
@@ -73,8 +73,8 @@
             fd, name = opentuntap(name=self.interface,
                                   ethernet=self.ethernet,
                                   packetinfo=0)
-        except OSError, e:
-            raise error.CannotListenError, (None, self.interface, e)
+        except OSError as e:
+            raise error.CannotListenError(None, self.interface, e)
         fdesc.setNonBlocking(fd)
         self.interface = name
         self.connected = 1
@@ -98,12 +98,12 @@
                 self.protocol.datagramReceived(data,
                                                partial=0 # pkt.isPartial(),
                                                )
-            except OSError, e:
+            except OSError as e:
                 if e.errno in (errno.EWOULDBLOCK,):
                     return
                 else:
                     raise
-            except IOError, e:
+            except IOError as e:
                 if e.errno in (errno.EAGAIN, errno.EINTR):
                     return
                 else:
@@ -116,11 +116,11 @@
 #        header = makePacketInfo(0, 0)
         try:
             return os.write(self.fd, datagram)
-        except IOError, e:
+        except IOError as e:
             if e.errno == errno.EINTR:
                 return self.write(datagram)
             elif e.errno == errno.EMSGSIZE:
-                raise error.MessageLengthError, "message too long"
+                raise error.MessageLengthError("message too long")
             elif e.errno == errno.ECONNREFUSED:
                 raise error.ConnectionRefusedError
             else:
--- twisted/pair/test/test_ethernet.py (original)
+++ twisted/pair/test/test_ethernet.py (refactored)
@@ -182,7 +182,7 @@
         except components.CannotAdapt:
             pass
         else:
-            raise AssertionError, 'addProto must raise an exception for bad protocols'
+            raise AssertionError('addProto must raise an exception for bad protocols')
 
 
     def testAddingBadProtos_TooSmall(self):
@@ -190,13 +190,13 @@
         e = ethernet.EthernetProtocol()
         try:
             e.addProto(-1, MyProtocol([]))
-        except TypeError, e:
+        except TypeError as e:
             if e.args == ('Added protocol must be positive or zero',):
                 pass
             else:
                 raise
         else:
-            raise AssertionError, 'addProto must raise an exception for bad protocols'
+            raise AssertionError('addProto must raise an exception for bad protocols')
 
 
     def testAddingBadProtos_TooBig(self):
@@ -204,23 +204,23 @@
         e = ethernet.EthernetProtocol()
         try:
             e.addProto(2**16, MyProtocol([]))
-        except TypeError, e:
+        except TypeError as e:
             if e.args == ('Added protocol must fit in 16 bits',):
                 pass
             else:
                 raise
         else:
-            raise AssertionError, 'addProto must raise an exception for bad protocols'
+            raise AssertionError('addProto must raise an exception for bad protocols')
 
     def testAddingBadProtos_TooBig2(self):
         """Adding a protocol with a number >=2**16 raises an exception."""
         e = ethernet.EthernetProtocol()
         try:
             e.addProto(2**16+1, MyProtocol([]))
-        except TypeError, e:
+        except TypeError as e:
             if e.args == ('Added protocol must fit in 16 bits',):
                 pass
             else:
                 raise
         else:
-            raise AssertionError, 'addProto must raise an exception for bad protocols'
+            raise AssertionError('addProto must raise an exception for bad protocols')
--- twisted/pair/test/test_ip.py (original)
+++ twisted/pair/test/test_ip.py (refactored)
@@ -19,8 +19,8 @@
         assert self.expecting, 'Got a packet when not expecting anymore.'
         expectData, expectKw = self.expecting.pop(0)
 
-        expectKwKeys = expectKw.keys(); expectKwKeys.sort()
-        kwKeys = kw.keys(); kwKeys.sort()
+        expectKwKeys = list(expectKw.keys()); expectKwKeys.sort()
+        kwKeys = list(kw.keys()); kwKeys.sort()
         assert expectKwKeys == kwKeys, "Expected %r, got %r" % (expectKwKeys, kwKeys)
 
         for k in expectKwKeys:
@@ -373,7 +373,7 @@
         except components.CannotAdapt:
             pass
         else:
-            raise AssertionError, 'addProto must raise an exception for bad protocols'
+            raise AssertionError('addProto must raise an exception for bad protocols')
 
 
     def testAddingBadProtos_TooSmall(self):
@@ -381,37 +381,37 @@
         e = ip.IPProtocol()
         try:
             e.addProto(-1, MyProtocol([]))
-        except TypeError, e:
+        except TypeError as e:
             if e.args == ('Added protocol must be positive or zero',):
                 pass
             else:
                 raise
         else:
-            raise AssertionError, 'addProto must raise an exception for bad protocols'
+            raise AssertionError('addProto must raise an exception for bad protocols')
 
 
     def testAddingBadProtos_TooBig(self):
         """Adding a protocol with a number >=2**32 raises an exception."""
         e = ip.IPProtocol()
         try:
-            e.addProto(2L**32, MyProtocol([]))
-        except TypeError, e:
+            e.addProto(2**32, MyProtocol([]))
+        except TypeError as e:
             if e.args == ('Added protocol must fit in 32 bits',):
                 pass
             else:
                 raise
         else:
-            raise AssertionError, 'addProto must raise an exception for bad protocols'
+            raise AssertionError('addProto must raise an exception for bad protocols')
 
     def testAddingBadProtos_TooBig2(self):
         """Adding a protocol with a number >=2**32 raises an exception."""
         e = ip.IPProtocol()
         try:
-            e.addProto(2L**32+1, MyProtocol([]))
-        except TypeError, e:
+            e.addProto(2**32+1, MyProtocol([]))
+        except TypeError as e:
             if e.args == ('Added protocol must fit in 32 bits',):
                 pass
             else:
                 raise
         else:
-            raise AssertionError, 'addProto must raise an exception for bad protocols'
+            raise AssertionError('addProto must raise an exception for bad protocols')
--- twisted/pair/test/test_rawudp.py (original)
+++ twisted/pair/test/test_rawudp.py (refactored)
@@ -12,7 +12,8 @@
     def __init__(self, expecting):
         self.expecting = list(expecting)
 
-    def datagramReceived(self, data, (host, port)):
+    def datagramReceived(self, data, xxx_todo_changeme):
+        (host, port) = xxx_todo_changeme
         assert self.expecting, 'Got a packet when not expecting anymore.'
         expectData, expectHost, expectPort = self.expecting.pop(0)
 
@@ -277,13 +278,13 @@
         e = rawudp.RawUDPProtocol()
         try:
             e.addProto(42, "silliness")
-        except TypeError, e:
+        except TypeError as e:
             if e.args == ('Added protocol must be an instance of DatagramProtocol',):
                 pass
             else:
                 raise
         else:
-            raise AssertionError, 'addProto must raise an exception for bad protocols'
+            raise AssertionError('addProto must raise an exception for bad protocols')
 
 
     def testAddingBadProtos_TooSmall(self):
@@ -291,13 +292,13 @@
         e = rawudp.RawUDPProtocol()
         try:
             e.addProto(-1, protocol.DatagramProtocol())
-        except TypeError, e:
+        except TypeError as e:
             if e.args == ('Added protocol must be positive or zero',):
                 pass
             else:
                 raise
         else:
-            raise AssertionError, 'addProto must raise an exception for bad protocols'
+            raise AssertionError('addProto must raise an exception for bad protocols')
 
 
     def testAddingBadProtos_TooBig(self):
@@ -305,23 +306,23 @@
         e = rawudp.RawUDPProtocol()
         try:
             e.addProto(2**16, protocol.DatagramProtocol())
-        except TypeError, e:
+        except TypeError as e:
             if e.args == ('Added protocol must fit in 16 bits',):
                 pass
             else:
                 raise
         else:
-            raise AssertionError, 'addProto must raise an exception for bad protocols'
+            raise AssertionError('addProto must raise an exception for bad protocols')
 
     def testAddingBadProtos_TooBig2(self):
         """Adding a protocol with a number >=2**16 raises an exception."""
         e = rawudp.RawUDPProtocol()
         try:
             e.addProto(2**16+1, protocol.DatagramProtocol())
-        except TypeError, e:
+        except TypeError as e:
             if e.args == ('Added protocol must fit in 16 bits',):
                 pass
             else:
                 raise
         else:
-            raise AssertionError, 'addProto must raise an exception for bad protocols'
+            raise AssertionError('addProto must raise an exception for bad protocols')
--- twisted/persisted/aot.py (original)
+++ twisted/persisted/aot.py (refactored)
@@ -11,7 +11,7 @@
 this side of Marmalade!
 """
 
-import types, new, string, copy_reg, tokenize, re
+import types, new, string, copyreg, tokenize, re
 
 from twisted.python import reflect, log
 from twisted.persisted import crefutil
@@ -57,18 +57,18 @@
 NoStateObj = _NoStateObj()
 
 _SIMPLE_BUILTINS = [
-    types.StringType, types.UnicodeType, types.IntType, types.FloatType,
-    types.ComplexType, types.LongType, types.NoneType, types.SliceType,
-    types.EllipsisType]
+    bytes, str, int, float,
+    complex, int, type(None), slice,
+    type(Ellipsis)]
 
 try:
-    _SIMPLE_BUILTINS.append(types.BooleanType)
+    _SIMPLE_BUILTINS.append(bool)
 except AttributeError:
     pass
 
 class Instance:
     def __init__(self, className, __stateObj__=NoStateObj, **state):
-        if not isinstance(className, types.StringType):
+        if not isinstance(className, bytes):
             raise TypeError("%s isn't a string!" % className)
         self.klass = className
         if __stateObj__ is not NoStateObj:
@@ -82,7 +82,7 @@
         #XXX make state be foo=bar instead of a dict.
         if self.stateIsDict:
             stateDict = self.state
-        elif isinstance(self.state, Ref) and isinstance(self.state.obj, types.DictType):
+        elif isinstance(self.state, Ref) and isinstance(self.state.obj, dict):
             stateDict = self.state.obj
         else:
             stateDict = None
@@ -160,10 +160,10 @@
 
 def dictToKW(d):
     out = []
-    items = d.items()
+    items = list(d.items())
     items.sort()
     for k,v in items:
-        if not isinstance(k, types.StringType):
+        if not isinstance(k, bytes):
             raise NonFormattableDict("%r ain't a string" % k)
         if not r.match(k):
             raise NonFormattableDict("%r ain't an identifier" % k)
@@ -183,21 +183,21 @@
         if t in _SIMPLE_BUILTINS:
             return repr(obj)
 
-        elif t is types.DictType:
+        elif t is dict:
             out = ['{']
-            for k,v in obj.items():
+            for k,v in list(obj.items()):
                 out.append('\n\0%s: %s,' % (prettify(k), prettify(v)))
             out.append(len(obj) and '\n\0}' or '}')
             return string.join(out, '')
 
-        elif t is types.ListType:
+        elif t is list:
             out = ["["]
             for x in obj:
                 out.append('\n\0%s,' % prettify(x))
             out.append(len(obj) and '\n\0]' or ']')
             return string.join(out, '')
 
-        elif t is types.TupleType:
+        elif t is tuple:
             out = ["("]
             for x in obj:
                 out.append('\n\0%s,' % prettify(x))
@@ -256,11 +256,11 @@
           }
 
     if hasattr(stringOrFile, "read"):
-        exec stringOrFile.read() in ns
+        exec(stringOrFile.read(), ns)
     else:
-        exec stringOrFile in ns
-
-    if ns.has_key('app'):
+        exec(stringOrFile, ns)
+
+    if 'app' in ns:
         return unjellyFromAOT(ns['app'])
     else:
         raise ValueError("%s needs to define an 'app', it didn't!" % stringOrFile)
@@ -381,7 +381,7 @@
             elif c is Copyreg:
                 loadfunc = reflect.namedObject(ao.loadfunc)
                 d = self.unjellyLater(ao.state).addCallback(
-                    lambda result, _l: apply(_l, result), loadfunc)
+                    lambda result, _l: _l(*result), loadfunc)
                 return d
 
         #Types
@@ -389,14 +389,14 @@
         elif t in _SIMPLE_BUILTINS:
             return ao
             
-        elif t is types.ListType:
+        elif t is list:
             l = []
             for x in ao:
                 l.append(None)
                 self.unjellyInto(l, len(l)-1, x)
             return l
         
-        elif t is types.TupleType:
+        elif t is tuple:
             l = []
             tuple_ = tuple
             for x in ao:
@@ -405,9 +405,9 @@
                     tuple_ = crefutil._Tuple
             return tuple_(l)
 
-        elif t is types.DictType:
+        elif t is dict:
             d = {}
-            for k,v in ao.items():
+            for k,v in list(ao.items()):
                 kvd = crefutil._DictKeyAndValue(d)
                 self.unjellyInto(kvd, 0, k)
                 self.unjellyInto(kvd, 1, v)
@@ -424,11 +424,11 @@
             l = [None]
             self.unjellyInto(l, 0, ao)
             for callable, v in self.afterUnjelly:
-                callable(v[0])
+                hasattr(v[0], '__call__')
             return l[0]
         except:
             log.msg("Error jellying object! Stacktrace follows::")
-            log.msg(string.join(map(repr, self.stack), "\n"))
+            log.msg(string.join(list(map(repr, self.stack)), "\n"))
             raise
 #########
 # Jelly #
@@ -478,13 +478,13 @@
             # TODO: make methods 'prefer' not to jelly the object internally,
             # so that the object will show up where it's referenced first NOT
             # by a method.
-            retval = InstanceMethod(obj.im_func.__name__, reflect.qual(obj.im_class),
-                                    self.jellyToAO(obj.im_self))
+            retval = InstanceMethod(obj.__func__.__name__, reflect.qual(obj.__self__.__class__),
+                                    self.jellyToAO(obj.__self__))
             
         elif objType is types.ModuleType:
             retval = Module(obj.__name__)
             
-        elif objType is types.ClassType:
+        elif objType is type:
             retval = Class(reflect.qual(obj))
 
         elif issubclass(objType, type):
@@ -504,7 +504,7 @@
 #mutable inside one. The Ref() class will only print the "Ref(..)" around an
 #object if it has a Reference explicitly attached.
 
-            if self.prepared.has_key(id(obj)):
+            if id(obj) in self.prepared:
                 oldRef = self.prepared[id(obj)]
                 if oldRef.refnum:
                     # it's been referenced already
@@ -519,15 +519,15 @@
             retval = Ref()
             self.prepareForRef(retval, obj)
             
-            if objType is types.ListType:
-                retval.setObj(map(self.jellyToAO, obj)) #hah!
+            if objType is list:
+                retval.setObj(list(map(self.jellyToAO, obj))) #hah!
                 
-            elif objType is types.TupleType:
+            elif objType is tuple:
                 retval.setObj(tuple(map(self.jellyToAO, obj)))
 
-            elif objType is types.DictionaryType:
+            elif objType is dict:
                 d = {}
-                for k,v in obj.items():
+                for k,v in list(obj.items()):
                     d[self.jellyToAO(k)] = self.jellyToAO(v)
                 retval.setObj(d)
 
@@ -538,8 +538,8 @@
                     state = self.jellyToAO(obj.__dict__)
                 retval.setObj(Instance(reflect.qual(obj.__class__), state))
 
-            elif copy_reg.dispatch_table.has_key(objType):
-                unpickleFunc, state = copy_reg.dispatch_table[objType](obj)
+            elif objType in copyreg.dispatch_table:
+                unpickleFunc, state = copyreg.dispatch_table[objType](obj)
                 
                 retval.setObj(Copyreg( reflect.fullFuncName(unpickleFunc),
                                        self.jellyToAO(state)))
--- twisted/persisted/crefutil.py (original)
+++ twisted/persisted/crefutil.py (refactored)
@@ -57,8 +57,8 @@
         NotKnown.__init__(self)
         self.containerType = containerType
         self.l = l
-        self.locs = range(len(l))
-        for idx in xrange(len(l)):
+        self.locs = list(range(len(l)))
+        for idx in range(len(l)):
             if not isinstance(l[idx], NotKnown):
                 self.locs.remove(idx)
             else:
--- twisted/persisted/dirdbm.py (original)
+++ twisted/persisted/dirdbm.py (refactored)
@@ -27,7 +27,7 @@
 import glob
 
 try:
-    import cPickle as pickle
+    import pickle as pickle
 except ImportError:
     import pickle
 
@@ -119,8 +119,8 @@
         @type v: str
         @param v: value to associate with C{k}
         """
-        assert type(k) == types.StringType, "DirDBM key must be a string"
-        assert type(v) == types.StringType, "DirDBM value must be a string"
+        assert type(k) == bytes, "DirDBM key must be a string"
+        assert type(v) == bytes, "DirDBM value must be a string"
         k = self._encode(k)
         
         # we create a new file with extension .new, write the data to it, and
@@ -150,12 +150,12 @@
         @return: The value associated with C{k}
         @raise KeyError: Raised when there is no such key
         """
-        assert type(k) == types.StringType, "DirDBM key must be a string"
+        assert type(k) == bytes, "DirDBM key must be a string"
         path = os.path.join(self.dname, self._encode(k))
         try:
             return self._readFile(path)
         except:
-            raise KeyError, k
+            raise KeyError(k)
 
     def __delitem__(self, k):
         """
@@ -167,7 +167,7 @@
         
         @raise KeyError: Raised when there is no such key
         """
-        assert type(k) == types.StringType, "DirDBM key must be a string"
+        assert type(k) == bytes, "DirDBM key must be a string"
         k = self._encode(k)
         try:    os.remove(os.path.join(self.dname, k))
         except (OSError, IOError): raise KeyError(self._decode(k))
@@ -176,14 +176,14 @@
         """
         @return: a C{list} of filenames (keys).
         """
-        return map(self._decode, os.listdir(self.dname))
+        return list(map(self._decode, os.listdir(self.dname)))
 
     def values(self):
         """
         @return: a C{list} of file-contents (values).
         """
         vals = []
-        keys = self.keys()
+        keys = list(self.keys())
         for key in keys:
             vals.append(self[key])
         return vals
@@ -193,7 +193,7 @@
         @return: a C{list} of 2-tuples containing key/value pairs.
         """
         items = []
-        keys = self.keys()
+        keys = list(self.keys())
         for key in keys:
             items.append((key, self[key]))
         return items
@@ -206,7 +206,7 @@
         @return: A true value if this dirdbm has the specified key, a faluse
         value otherwise.
         """
-        assert type(key) == types.StringType, "DirDBM key must be a string"
+        assert type(key) == bytes, "DirDBM key must be a string"
         key = self._encode(key)
         return os.path.isfile(os.path.join(self.dname, key))
 
@@ -218,7 +218,7 @@
         @param value: The value to associate with key if key is not already
         associated with a value.
         """
-        if not self.has_key(key):
+        if key not in self:
             self[key] = value
             return value
         return self[key]
@@ -233,7 +233,7 @@
         @return: The value associated with C{key} or C{default} if not
         C{self.has_key(key)}
         """
-        if self.has_key(key):
+        if key in self:
             return self[key]
         else:
             return default
@@ -247,7 +247,7 @@
                 
         @return: A true value if C{self.has_key(key)}, a false value otherwise.
         """
-        assert type(key) == types.StringType, "DirDBM key must be a string"
+        assert type(key) == bytes, "DirDBM key must be a string"
         key = self._encode(key)
         return os.path.isfile(os.path.join(self.dname, key))
 
@@ -259,7 +259,7 @@
         @type dict: mapping
         @param dict: A mapping of key/value pairs to add to this dirdbm.
         """
-        for key, val in dict.items():
+        for key, val in list(dict.items()):
             self[key]=val
             
     def copyTo(self, path):
@@ -278,7 +278,7 @@
         
         d = self.__class__(path)
         d.clear()
-        for k in self.keys():
+        for k in list(self.keys()):
             d[k] = self[k]
         return d
 
@@ -286,7 +286,7 @@
         """
         Delete all key/value pairs in this dirdbm.
         """
-        for k in self.keys():
+        for k in list(self.keys()):
             del self[k]
 
     def close(self):
@@ -301,12 +301,12 @@
         @return: Last modification date (seconds since epoch) of entry C{key}
         @raise KeyError: Raised when there is no such key
         """
-        assert type(key) == types.StringType, "DirDBM key must be a string"
+        assert type(key) == bytes, "DirDBM key must be a string"
         path = os.path.join(self.dname, self._encode(key))
         if os.path.isfile(path):
             return os.path.getmtime(path)
         else:
-            raise KeyError, key
+            raise KeyError(key)
 
 
 class Shelf(DirDBM):
--- twisted/persisted/marmalade.py (original)
+++ twisted/persisted/marmalade.py (refactored)
@@ -28,22 +28,22 @@
     instancemethod = PyMethod
 
 import types
-import copy_reg
+import copyreg
 
 #for some reason, __builtins__ == __builtin__.__dict__ in the context where this is used.
 #Can someone tell me why?
-import __builtin__ 
+import builtins 
 
 
 def instance(klass, d):
-    if isinstance(klass, types.ClassType):
+    if isinstance(klass, type):
         return new.instance(klass, d)
     elif isinstance(klass, type):
         o = object.__new__(klass)
         o.__dict__ = d
         return o
     else:
-        raise TypeError, "%s is not a class" % klass
+        raise TypeError("%s is not a class" % klass)
 
 
 def getValueElement(node):
@@ -136,7 +136,7 @@
         elif node.tagName == "float":
             retval = float(node.getAttribute("value"))
         elif node.tagName == "longint":
-            retval = long(node.getAttribute("value"))
+            retval = int(node.getAttribute("value"))
         elif node.tagName == "bool":
             retval = int(node.getAttribute("value"))
             if retval:
@@ -148,14 +148,14 @@
         elif node.tagName == "class":
             retval = namedClass(str(node.getAttribute("name")))
         elif node.tagName == "unicode":
-            retval = unicode(str(node.getAttribute("value")).replace("\\n", "\n").replace("\\t", "\t"), "raw_unicode_escape")
+            retval = str(str(node.getAttribute("value")).replace("\\n", "\n").replace("\\t", "\t"), "raw_unicode_escape")
         elif node.tagName == "function":
             retval = namedObject(str(node.getAttribute("name")))
         elif node.tagName == "method":
             im_name = node.getAttribute("name")
             im_class = namedClass(node.getAttribute("class"))
             im_self = self.unjellyNode(getValueElement(node))
-            if im_class.__dict__.has_key(im_name):
+            if im_name in im_class.__dict__:
                 if im_self is None:
                     retval = getattr(im_class, im_name)
                 elif isinstance(im_self, NotKnown):
@@ -221,7 +221,7 @@
         elif node.tagName == "copyreg":
             nodefunc = namedObject(node.getAttribute("loadfunc"))
             loaddef = self.unjellyLater(getValueElement(node)).addCallback(
-                lambda result, _l: apply(_l, result), nodefunc)
+                lambda result, _l: _l(*result), nodefunc)
             retval = loaddef
         else:
             raise TypeError("Unsupported Node Type: %s" % (node.tagName,))
@@ -260,9 +260,9 @@
         """
         objType = type(obj)
         #immutable (We don't care if these have multiple refs)
-        if objType is types.NoneType:
+        if objType is type(None):
             node = self.document.createElement("None")
-        elif objType is types.StringType:
+        elif objType is bytes:
             node = self.document.createElement("string")
             r = repr(obj)
             if r[0] == '"':
@@ -271,36 +271,36 @@
                 r = r.replace('"', '\\"')
             node.setAttribute("value", r[1:-1])
             # node.appendChild(CDATASection(obj))
-        elif objType is types.IntType:
+        elif objType is int:
             node = self.document.createElement("int")
             node.setAttribute("value", str(obj))
-        elif objType is types.LongType:
+        elif objType is int:
             node = self.document.createElement("longint")
             s = str(obj)
             if s[-1] == 'L':
                 s = s[:-1]
             node.setAttribute("value", s)
-        elif objType is types.FloatType:
+        elif objType is float:
             node = self.document.createElement("float")
             node.setAttribute("value", repr(obj))
         elif objType is types.MethodType:
             node = self.document.createElement("method")
-            node.setAttribute("name", obj.im_func.__name__)
-            node.setAttribute("class", qual(obj.im_class))
+            node.setAttribute("name", obj.__func__.__name__)
+            node.setAttribute("class", qual(obj.__self__.__class__))
             # TODO: make methods 'prefer' not to jelly the object internally,
             # so that the object will show up where it's referenced first NOT
             # by a method.
-            node.appendChild(self.jellyToNode(obj.im_self))
-        elif hasattr(types, 'BooleanType') and objType is types.BooleanType:
+            node.appendChild(self.jellyToNode(obj.__self__))
+        elif hasattr(types, 'BooleanType') and objType is bool:
             node = self.document.createElement("bool")
             node.setAttribute("value", str(int(obj)))
         elif objType is types.ModuleType:
             node = self.document.createElement("module")
             node.setAttribute("name", obj.__name__)
-        elif objType==types.ClassType or issubclass(objType, type):
+        elif objType==type or issubclass(objType, type):
             node = self.document.createElement("class")
             node.setAttribute("name", qual(obj))
-        elif objType is types.UnicodeType:
+        elif objType is str:
             node = self.document.createElement("unicode")
             obj = obj.encode('raw_unicode_escape')
             s = obj.replace("\n", "\\n").replace("\t", "\\t")
@@ -313,7 +313,7 @@
             node.setAttribute("name", fullFuncName(obj))
         else:
             #mutable!
-            if self.prepared.has_key(id(obj)):
+            if id(obj) in self.prepared:
                 oldNode = self.prepared[id(obj)][1]
                 if oldNode.hasAttribute("reference"):
                     # it's been referenced already
@@ -328,24 +328,24 @@
                 return node
             node = self.document.createElement("UNNAMED")
             self.prepareElement(node, obj)
-            if objType is types.ListType or __builtin__.__dict__.has_key('object') and isinstance(obj, NodeList):
+            if objType is list or 'object' in builtins.__dict__ and isinstance(obj, NodeList):
                 node.tagName = "list"
                 for subobj in obj:
                     node.appendChild(self.jellyToNode(subobj))
-            elif objType is types.TupleType:
+            elif objType is tuple:
                 node.tagName = "tuple"
                 for subobj in obj:
                     node.appendChild(self.jellyToNode(subobj))
-            elif objType is types.DictionaryType:
+            elif objType is dict:
                 node.tagName = "dictionary"
-                for k, v in obj.items():
+                for k, v in list(obj.items()):
                     n = self.jellyToNode(k)
                     n.setAttribute("role", "key")
                     n2 = self.jellyToNode(v)
                     node.appendChild(n)
                     node.appendChild(n2)
-            elif copy_reg.dispatch_table.has_key(objType):
-                unpickleFunc, state = copy_reg.dispatch_table[objType](obj)
+            elif objType in copyreg.dispatch_table:
+                unpickleFunc, state = copyreg.dispatch_table[objType](obj)
                 node = self.document.createElement("copyreg")
                 # node.setAttribute("type", objType.__name__)
                 node.setAttribute("loadfunc", fullFuncName(unpickleFunc))
--- twisted/persisted/sob.py (original)
+++ twisted/persisted/sob.py (refactored)
@@ -11,13 +11,13 @@
 
 import os, sys
 try:
-    import cPickle as pickle
+    import pickle as pickle
 except ImportError:
     import pickle
 try:
-    import cStringIO as StringIO
+    import io as StringIO
 except ImportError:
-    import StringIO
+    import io
 from twisted.python import log, runtime
 from twisted.python.hashlib import md5
 from twisted.persisted import styles
@@ -92,7 +92,7 @@
         if passphrase is None:
             dumpFunc(self.original, f)
         else:
-            s = StringIO.StringIO()
+            s = io.StringIO()
             dumpFunc(self.original, s)
             f.write(_encrypt(passphrase, s.getvalue()))
         f.close()
@@ -169,7 +169,7 @@
     else:
         _load, mode = pickle.load, 'rb'
     if passphrase:
-        fp = StringIO.StringIO(_decrypt(passphrase,
+        fp = io.StringIO(_decrypt(passphrase,
                                         open(filename, 'rb').read()))
     else:
         fp = open(filename, mode)
@@ -210,9 +210,9 @@
     if passphrase:
         data = fileObj.read()
         data = _decrypt(passphrase, data)
-        exec data in d, d
-    else:
-        exec fileObj in d, d
+        exec(data, d, d)
+    else:
+        exec(fileObj, d, d)
     value = d[variable]
     return value
 
--- twisted/persisted/styles.py (original)
+++ twisted/persisted/styles.py (refactored)
@@ -10,13 +10,13 @@
 
 # System Imports
 import types
-import copy_reg
+import copyreg
 import copy
 
 try:
-    import cStringIO as StringIO
+    import io as StringIO
 except ImportError:
-    import StringIO
+    import io
 
 # Twisted Imports
 from twisted.python import log
@@ -34,9 +34,9 @@
 
 def pickleMethod(method):
     'support function for copy_reg to pickle method refs'
-    return unpickleMethod, (method.im_func.__name__,
-                             method.im_self,
-                             method.im_class)
+    return unpickleMethod, (method.__func__.__name__,
+                             method.__self__,
+                             method.__self__.__class__)
 
 def unpickleMethod(im_name,
                     im_self,
@@ -46,7 +46,7 @@
         unbound = getattr(im_class,im_name)
         if im_self is None:
             return unbound
-        bound=instancemethod(unbound.im_func,
+        bound=instancemethod(unbound.__func__,
                                  im_self,
                                  im_class)
         return bound
@@ -60,12 +60,12 @@
         log.msg("Attempting fixup with",unbound)
         if im_self is None:
             return unbound
-        bound=instancemethod(unbound.im_func,
+        bound=instancemethod(unbound.__func__,
                                  im_self,
                                  im_self.__class__)
         return bound
 
-copy_reg.pickle(types.MethodType,
+copyreg.pickle(types.MethodType,
                 pickleMethod,
                 unpickleMethod)
 
@@ -75,14 +75,14 @@
 
 def unpickleModule(name):
     'support function for copy_reg to unpickle module refs'
-    if oldModules.has_key(name):
+    if name in oldModules:
         log.msg("Module has moved: %s" % name)
         name = oldModules[name]
         log.msg(name)
     return __import__(name,{},{},'x')
 
 
-copy_reg.pickle(types.ModuleType,
+copyreg.pickle(types.ModuleType,
                 pickleModule,
                 unpickleModule)
 
@@ -91,13 +91,13 @@
     return unpickleStringO, (stringo.getvalue(), stringo.tell())
 
 def unpickleStringO(val, sek):
-    x = StringIO.StringIO()
+    x = io.StringIO()
     x.write(val)
     x.seek(sek)
     return x
 
 if hasattr(StringIO, 'OutputType'):
-    copy_reg.pickle(StringIO.OutputType,
+    copyreg.pickle(io.OutputType,
                     pickleStringO,
                     unpickleStringO)
 
@@ -105,13 +105,13 @@
     return unpickleStringI, (stringi.getvalue(), stringi.tell())
 
 def unpickleStringI(val, sek):
-    x = StringIO.StringIO(val)
+    x = io.StringIO(val)
     x.seek(sek)
     return x
 
 
 if hasattr(StringIO, 'InputType'):
-    copy_reg.pickle(StringIO.InputType,
+    copyreg.pickle(io.InputType,
                 pickleStringI,
                 unpickleStringI)
 
@@ -138,7 +138,7 @@
 
 def doUpgrade():
     global versionedsToUpgrade, upgraded
-    for versioned in versionedsToUpgrade.values():
+    for versioned in list(versionedsToUpgrade.values()):
         requireUpgrade(versioned)
     versionedsToUpgrade = {}
     upgraded = {}
@@ -196,11 +196,11 @@
         bases.reverse()
         bases.append(self.__class__) # don't forget me!!
         for base in bases:
-            if base.__dict__.has_key('persistenceForgets'):
+            if 'persistenceForgets' in base.__dict__:
                 for slot in base.persistenceForgets:
-                    if dct.has_key(slot):
+                    if slot in dct:
                         del dct[slot]
-            if base.__dict__.has_key('persistenceVersion'):
+            if 'persistenceVersion' in base.__dict__:
                 dct['%s.persistenceVersion' % reflect.qual(base)] = base.persistenceVersion
         return dct
 
@@ -213,7 +213,7 @@
         bases.reverse()
         bases.append(self.__class__) # don't forget me!!
         # first let's look for old-skool versioned's
-        if self.__dict__.has_key("persistenceVersion"):
+        if "persistenceVersion" in self.__dict__:
             
             # Hacky heuristic: if more than one class subclasses Versioned,
             # we'll assume that the higher version number wins for the older
@@ -228,7 +228,7 @@
             highestVersion = 0
             highestBase = None
             for base in bases:
-                if not base.__dict__.has_key('persistenceVersion'):
+                if 'persistenceVersion' not in base.__dict__:
                     continue
                 if base.persistenceVersion > highestVersion:
                     highestBase = base
@@ -238,7 +238,7 @@
         for base in bases:
             # ugly hack, but it's what the user expects, really
             if (Versioned not in base.__bases__ and
-                not base.__dict__.has_key('persistenceVersion')):
+                'persistenceVersion' not in base.__dict__):
                 continue
             currentVers = base.persistenceVersion
             pverName = '%s.persistenceVersion' % reflect.qual(base)
--- twisted/persisted/journal/base.py (original)
+++ twisted/persisted/journal/base.py (refactored)
@@ -8,13 +8,13 @@
 
 """Basic classes and interfaces for journal."""
 
-from __future__ import nested_scopes
+
 
 # system imports
 import os, time
 
 try:
-    import cPickle as pickle
+    import pickle as pickle
 except ImportError:
     import pickle
 
--- twisted/persisted/journal/picklelog.py (original)
+++ twisted/persisted/journal/picklelog.py (refactored)
@@ -15,7 +15,7 @@
 from zope.interface import implements
 
 # sibling imports
-import base
+from . import base
 
 
 class DirDBMLog:
@@ -25,7 +25,7 @@
 
     def __init__(self, logPath):
         self.db = dirdbm.Shelf(logPath)
-        indexs = map(int, self.db.keys())
+        indexs = list(map(int, list(self.db.keys())))
         if indexs:
             self.currentIndex = max(indexs)
         else:
--- twisted/persisted/journal/rowjournal.py (original)
+++ twisted/persisted/journal/rowjournal.py (refactored)
@@ -15,17 +15,17 @@
 
 """
 
-from __future__ import nested_scopes
+
 
 # twisted imports
 from twisted.internet import defer
 
 # sibling imports
-import base
+from . import base
 
 
 # constants for command list
-INSERT, DELETE, UPDATE = range(3)
+INSERT, DELETE, UPDATE = list(range(3))
 
 
 class RowJournal(base.Journal):
@@ -65,7 +65,7 @@
     def sync(self):
         """Commit changes to database."""
         if self.syncing:
-            raise ValueError, "sync already in progress"
+            raise ValueError("sync already in progress")
         comandMap = {INSERT : self.reflector.insertRowSQL,
                      UPDATE : self.reflector.updateRowSQL,
                      DELETE : self.reflector.deleteRowSQL}
--- twisted/plugins/cred_file.py (original)
+++ twisted/plugins/cred_file.py (refactored)
@@ -50,7 +50,7 @@
         """
         from twisted.python.filepath import FilePath
         if not argstring.strip():
-            raise ValueError, '%r requires a filename' % self.authType
+            raise ValueError('%r requires a filename' % self.authType)
         elif not FilePath(argstring).isfile():
             self.errorOutput.write('%s: %s\n' % (invalidFileWarning, argstring))
         return FilePasswordDB(argstring)
--- twisted/protocols/amp.py (original)
+++ twisted/protocols/amp.py (refactored)
@@ -162,7 +162,7 @@
 
 import types, warnings
 
-from cStringIO import StringIO
+from io import StringIO
 from struct import pack
 
 from zope.interface import Interface, implements
@@ -448,7 +448,7 @@
         @return: a str encoded according to the rules described in the module
         docstring.
         """
-        i = self.items()
+        i = list(self.items())
         i.sort()
         L = []
         w = L.append
@@ -571,7 +571,7 @@
 
     _failAllReason = None
     _outstandingRequests = None
-    _counter = 0L
+    _counter = 0
     boxSender = None
 
     def __init__(self, locator):
@@ -604,7 +604,7 @@
         @param reason: the Failure instance to pass to those errbacks.
         """
         self._failAllReason = reason
-        OR = self._outstandingRequests.items()
+        OR = list(self._outstandingRequests.items())
         self._outstandingRequests = None # we can never send another request
         for key, value in OR:
             value.errback(reason)
@@ -1361,10 +1361,10 @@
             fatalErrors = {}
             accumulateClassDict(newtype, 'errors', errors)
             accumulateClassDict(newtype, 'fatalErrors', fatalErrors)
-            for v, k in errors.iteritems():
+            for v, k in errors.items():
                 re[k] = v
                 er[v] = k
-            for v, k in fatalErrors.iteritems():
+            for v, k in fatalErrors.items():
                 re[k] = v
                 er[v] = k
             return newtype
@@ -1392,7 +1392,7 @@
         @raise InvalidSignature: if you forgot any required arguments.
         """
         self.structured = kw
-        givenArgs = kw.keys()
+        givenArgs = list(kw.keys())
         forgotten = []
         for name, arg in self.arguments:
             pythonName = _wireNameToPythonIdentifier(name)
@@ -2220,7 +2220,7 @@
     strings (identical to C{strings}).
     """
     myObjects = {}
-    for (k, v) in objects.items():
+    for (k, v) in list(objects.items()):
         myObjects[k] = v
 
     for argname, argparser in arglist:
--- twisted/protocols/basic.py (original)
+++ twisted/protocols/basic.py (refactored)
@@ -19,7 +19,7 @@
 from twisted.internet import protocol, defer, interfaces, error
 from twisted.python import log
 
-LENGTH, DATA, COMMA = range(3)
+LENGTH, DATA, COMMA = list(range(3))
 NUMBER = re.compile('(\d*)(:?)')
 DEBUG = 0
 
@@ -81,11 +81,11 @@
         self.__data = self.__data[m.end():]
         if m.group(1):
             try:
-                self._readerLength = self._readerLength * (10**len(m.group(1))) + long(m.group(1))
+                self._readerLength = self._readerLength * (10**len(m.group(1))) + int(m.group(1))
             except OverflowError:
-                raise NetstringParseError, "netstring too long"
+                raise NetstringParseError("netstring too long")
             if self._readerLength > self.MAX_LENGTH:
-                raise NetstringParseError, "netstring too long"
+                raise NetstringParseError("netstring too long")
         if m.group(2):
             self.__buffer = ''
             self._readerState = DATA
@@ -101,7 +101,7 @@
                 elif self._readerState == LENGTH:
                     self.doLength()
                 else:
-                    raise RuntimeError, "mode is not DATA, COMMA or LENGTH"
+                    raise RuntimeError("mode is not DATA, COMMA or LENGTH")
         except NetstringParseError:
             self.transport.loseConnection()
             self.brokenPeer = 1
--- twisted/protocols/dict.py (original)
+++ twisted/protocols/dict.py (refactored)
@@ -11,7 +11,7 @@
 from twisted.protocols import basic
 from twisted.internet import defer, protocol
 from twisted.python import log
-from StringIO import StringIO
+from io import StringIO
 
 def parseParam(line):
     """Chew one dqstring or atom from beginning of line and return (param, remaningline)"""
@@ -48,10 +48,10 @@
 def makeAtom(line):
     """Munch a string into an 'atom'"""
     # FIXME: proper quoting
-    return filter(lambda x: not (x in map(chr, range(33)+[34, 39, 92])), line)
+    return [x for x in line if not (x in list(map(chr, list(range(33))+[34, 39, 92])))]
 
 def makeWord(s):
-    mustquote = range(33)+[34, 39, 92]
+    mustquote = list(range(33))+[34, 39, 92]
     result = []
     for c in s:
         if ord(c) in mustquote:
@@ -230,7 +230,7 @@
         res = parseText(line)
         if res == None:
             self.mode = "command"
-            self.result = map(l, self.data)
+            self.result = list(map(l, self.data))
             self.data = None
         else:
             self.data.append(line)
@@ -288,9 +288,9 @@
 
     def dictConnected(self):
         if self.factory.queryType == "define":
-            apply(self.sendDefine, self.factory.param)
+            self.sendDefine(*self.factory.param)
         elif self.factory.queryType == "match":
-            apply(self.sendMatch, self.factory.param)
+            self.sendMatch(*self.factory.param)
 
     def defineFailed(self, reason):
         self.factory.d.callback([])
--- twisted/protocols/ftp.py (original)
+++ twisted/protocols/ftp.py (refactored)
@@ -623,7 +623,7 @@
     disconnected = False
 
     # States an FTP can be in
-    UNAUTH, INAUTH, AUTHED, RENAMING = range(4)
+    UNAUTH, INAUTH, AUTHED, RENAMING = list(range(4))
 
     # how long the DTP waits for a connection
     dtpTimeout = 10
@@ -635,7 +635,7 @@
     dtpInstance = None
     binary = True
 
-    passivePortRange = xrange(0, 1)
+    passivePortRange = range(0, 1)
 
     listenFactory = reactor.listenTCP
 
@@ -787,7 +787,8 @@
             reply = USR_LOGGED_IN_PROCEED
         del self._user
 
-        def _cbLogin((interface, avatar, logout)):
+        def _cbLogin(xxx_todo_changeme):
+            (interface, avatar, logout) = xxx_todo_changeme
             assert interface is IFTPShell, "The realm is busted, jerk."
             self.shell = avatar
             self.logout = logout
@@ -832,7 +833,7 @@
 
 
     def ftp_PORT(self, address):
-        addr = map(int, address.split(','))
+        addr = list(map(int, address.split(',')))
         ip = '%d.%d.%d.%d' % tuple(addr[:4])
         port = addr[4] << 8 | addr[5]
 
@@ -887,7 +888,7 @@
 
         try:
             segments = toSegments(self.workingDirectory, path)
-        except InvalidPath, e:
+        except InvalidPath as e:
             return defer.fail(FileNotFoundError(path))
 
         d = self.shell.list(
@@ -905,7 +906,7 @@
 
         try:
             segments = toSegments(self.workingDirectory, path)
-        except InvalidPath, e:
+        except InvalidPath as e:
             return defer.fail(FileNotFoundError(path))
 
         def cbList(results):
@@ -939,7 +940,7 @@
     def ftp_CWD(self, path):
         try:
             segments = toSegments(self.workingDirectory, path)
-        except InvalidPath, e:
+        except InvalidPath as e:
             # XXX Eh, what to fail with here?
             return defer.fail(FileNotFoundError(path))
 
@@ -1087,7 +1088,8 @@
         except InvalidPath:
             return defer.fail(FileNotFoundError(path))
 
-        def cbStat((size,)):
+        def cbStat(xxx_todo_changeme1):
+            (size,) = xxx_todo_changeme1
             return (FILE_STATUS, str(size))
 
         return self.shell.stat(newsegs, ('size',)).addCallback(cbStat)
@@ -1099,7 +1101,8 @@
         except InvalidPath:
             return defer.fail(FileNotFoundError(path))
 
-        def cbStat((modified,)):
+        def cbStat(xxx_todo_changeme2):
+            (modified,) = xxx_todo_changeme2
             return (FILE_STATUS, time.strftime('%Y%m%d%H%M%S', time.gmtime(modified)))
 
         return self.shell.stat(newsegs, ('modified',)).addCallback(cbStat)
@@ -1243,7 +1246,7 @@
 
     welcomeMessage = "Twisted %s FTP Server" % (copyright.version,)
 
-    passivePortRange = xrange(0, 1)
+    passivePortRange = range(0, 1)
 
     def __init__(self, portal=None, userAnonymous='anonymous'):
         self.portal = portal
@@ -1556,7 +1559,7 @@
             return defer.fail(IsADirectoryError(path))
         try:
             f = p.open('rb')
-        except (IOError, OSError), e:
+        except (IOError, OSError) as e:
             return errnoToFailure(e.errno, path)
         except:
             return defer.fail()
@@ -1581,7 +1584,7 @@
         # For now, just see if we can os.listdir() it
         try:
             p.listdir()
-        except (IOError, OSError), e:
+        except (IOError, OSError) as e:
             return errnoToFailure(e.errno, path)
         except:
             return defer.fail()
@@ -1594,7 +1597,7 @@
         if p.isdir():
             try:
                 statResult = self._statNode(p, keys)
-            except (IOError, OSError), e:
+            except (IOError, OSError) as e:
                 return errnoToFailure(e.errno, path)
             except:
                 return defer.fail()
@@ -1632,7 +1635,7 @@
             if keys:
                 try:
                     ent.extend(self._statNode(filePath, keys))
-                except (IOError, OSError), e:
+                except (IOError, OSError) as e:
                     return errnoToFailure(e.errno, fileName)
                 except:
                     return defer.fail()
@@ -1712,7 +1715,7 @@
         p = self._path(path)
         try:
             p.makedirs()
-        except (IOError, OSError), e:
+        except (IOError, OSError) as e:
             return errnoToFailure(e.errno, path)
         except:
             return defer.fail()
@@ -1729,7 +1732,7 @@
             return defer.fail(IsNotADirectoryError(path))
         try:
             os.rmdir(p.path)
-        except (IOError, OSError), e:
+        except (IOError, OSError) as e:
             return errnoToFailure(e.errno, path)
         except:
             return defer.fail()
@@ -1746,7 +1749,7 @@
             return defer.fail(IsADirectoryError(path))
         try:
             p.remove()
-        except (IOError, OSError), e:
+        except (IOError, OSError) as e:
             return errnoToFailure(e.errno, path)
         except:
             return defer.fail()
@@ -1759,7 +1762,7 @@
         tp = self._path(toPath)
         try:
             os.rename(fp.path, tp.path)
-        except (IOError, OSError), e:
+        except (IOError, OSError) as e:
             return errnoToFailure(e.errno, fromPath)
         except:
             return defer.fail()
@@ -1775,7 +1778,7 @@
             return defer.fail(IsADirectoryError(path))
         try:
             fObj = p.open('wb')
-        except (IOError, OSError), e:
+        except (IOError, OSError) as e:
             return errnoToFailure(e.errno, path)
         except:
             return defer.fail()
@@ -2612,7 +2615,7 @@
                 # The only valid code is 257
                 if int(result[0].split(' ', 1)[0]) != 257:
                     raise ValueError
-            except (IndexError, ValueError), e:
+            except (IndexError, ValueError) as e:
                 return failure.Failure(CommandFailed(result))
             path = parsePWDResponse(result[0])
             if path is None:
--- twisted/protocols/htb.py (original)
+++ twisted/protocols/htb.py (refactored)
@@ -16,7 +16,7 @@
 @author: Kevin Turner
 """
 
-from __future__ import nested_scopes
+
 
 __version__ = '$Revision: 1.5 $'[11:-2]
 
@@ -91,7 +91,7 @@
         else:
             now = time()
             deltaT = now - self.lastDrip
-            self.content = long(max(0, self.content - deltaT * self.rate))
+            self.content = int(max(0, self.content - deltaT * self.rate))
             self.lastDrip = now
             return False
 
@@ -157,7 +157,7 @@
 
     def sweep(self):
         """I throw away references to empty buckets."""
-        for key, bucket in self.buckets.items():
+        for key, bucket in list(self.buckets.items()):
             if (bucket._refcount == 0) and bucket.drip():
                 del self.buckets[key]
 
--- twisted/protocols/ident.py (original)
+++ twisted/protocols/ident.py (refactored)
@@ -9,7 +9,7 @@
 @author: Jp Calderone
 """
 
-from __future__ import generators
+
 
 import struct
 
@@ -76,7 +76,7 @@
             self.invalidQuery()
         else:
             try:
-                portOnServer, portOnClient = map(int, parts)
+                portOnServer, portOnClient = list(map(int, parts))
             except ValueError:
                 self.invalidQuery()
             else:
@@ -96,7 +96,8 @@
             ).addErrback(self._ebLookup, portOnServer, portOnClient
             )
 
-    def _cbLookup(self, (sysName, userId), sport, cport):
+    def _cbLookup(self, xxx_todo_changeme, sport, cport):
+        (sysName, userId) = xxx_todo_changeme
         self.sendLine('%d, %d : USERID : %s : %s' % (sport, cport, sysName, userId))
 
     def _ebLookup(self, failure, sport, cport):
@@ -212,7 +213,7 @@
         if len(parts) != 3:
             deferred.errback(IdentError(line))
         else:
-            ports, type, addInfo = map(str.strip, parts)
+            ports, type, addInfo = list(map(str.strip, parts))
             if type == 'ERROR':
                 for et in self.errorTypes:
                     if et.identDescription == addInfo:
--- twisted/protocols/loopback.py (original)
+++ twisted/protocols/loopback.py (refactored)
@@ -40,7 +40,7 @@
             d.callback(None)
 
 
-    def __nonzero__(self):
+    def __bool__(self):
         return bool(self._queue)
 
 
--- twisted/protocols/memcache.py (original)
+++ twisted/protocols/memcache.py (refactored)
@@ -90,7 +90,7 @@
         """
         self.command = command
         self._deferred = Deferred()
-        for k, v in kwargs.items():
+        for k, v in list(kwargs.items()):
             setattr(self, k, v)
 
 
--- twisted/protocols/policies.py (original)
+++ twisted/protocols/policies.py (refactored)
@@ -124,7 +124,7 @@
         ProtocolWrapper.write(self, data)
 
     def writeSequence(self, seq):
-        self.factory.registerWritten(reduce(operator.add, map(len, seq)))
+        self.factory.registerWritten(reduce(operator.add, list(map(len, seq))))
         ProtocolWrapper.writeSequence(self, seq)
 
     def dataReceived(self, data):
@@ -165,7 +165,7 @@
 
     protocol = ThrottlingProtocol
 
-    def __init__(self, wrappedFactory, maxConnectionCount=sys.maxint,
+    def __init__(self, wrappedFactory, maxConnectionCount=sys.maxsize,
                  readLimit=None, writeLimit=None):
         WrappingFactory.__init__(self, wrappedFactory)
         self.connectionCount = 0
@@ -230,7 +230,7 @@
         Throttle reads on all protocols.
         """
         log.msg("Throttling reads on %s" % self)
-        for p in self.protocols.keys():
+        for p in list(self.protocols.keys()):
             p.throttleReads()
 
 
@@ -240,7 +240,7 @@
         """
         self.unthrottleReadsID = None
         log.msg("Stopped throttling reads on %s" % self)
-        for p in self.protocols.keys():
+        for p in list(self.protocols.keys()):
             p.unthrottleReads()
 
 
@@ -249,7 +249,7 @@
         Throttle writes on all protocols.
         """
         log.msg("Throttling writes on %s" % self)
-        for p in self.protocols.keys():
+        for p in list(self.protocols.keys()):
             p.throttleWrites()
 
 
@@ -259,7 +259,7 @@
         """
         self.unthrottleWritesID = None
         log.msg("Stopped throttling writes on %s" % self)
-        for p in self.protocols.keys():
+        for p in list(self.protocols.keys()):
             p.unthrottleWrites()
 
 
--- twisted/protocols/postfix.py (original)
+++ twisted/protocols/postfix.py (refactored)
@@ -15,16 +15,16 @@
 from twisted.internet import protocol, defer
 from twisted.python import log
 import UserDict
-import urllib
+import urllib.request, urllib.parse, urllib.error
 
 # urllib's quote functions just happen to match
 # the postfix semantics.
 
 def quote(s):
-    return urllib.quote(s)
+    return urllib.parse.quote(s)
 
 def unquote(s):
-    return urllib.unquote(s)
+    return urllib.parse.unquote(s)
 
 class PostfixTCPMapServer(basic.LineReceiver, policies.TimeoutMixin):
     """Postfix mail transport agent TCP map protocol implementation.
--- twisted/protocols/shoutcast.py (original)
+++ twisted/protocols/shoutcast.py (refactored)
@@ -102,16 +102,16 @@
 
         Will only be called on non-empty metadata.
         """
-        raise NotImplementedError, "implement in subclass"
+        raise NotImplementedError("implement in subclass")
     
     def gotMP3Data(self, data):
         """Called with chunk of MP3 data."""
-        raise NotImplementedError, "implement in subclass"
+        raise NotImplementedError("implement in subclass")
 
 
 if __name__ == '__main__':
     class Test(ShoutcastClient):
-        def gotMetaData(self, data): print "meta:", data
+        def gotMetaData(self, data): print("meta:", data)
         def gotMP3Data(self, data): pass
     
     from twisted.internet import protocol, reactor
--- twisted/protocols/sip.py (original)
+++ twisted/protocols/sip.py (refactored)
@@ -44,7 +44,7 @@
                 }
 
 longHeaders = {}
-for k, v in shortHeaders.items():
+for k, v in list(shortHeaders.items()):
     longHeaders[v] = k
 del k, v
 
@@ -221,7 +221,7 @@
     result = {}
     pname, pversion, transport = protocolinfo.split("/")
     if pname != "SIP" or pversion != "2.0":
-        raise ValueError, "wrong protocol or version: %r" % value
+        raise ValueError("wrong protocol or version: %r" % value)
     result["transport"] = transport
     if ":" in by:
         host, port = by.split(":")
@@ -296,7 +296,7 @@
             w(";%s" % v)
         if self.headers:
             w("?")
-            w("&".join([("%s=%s" % (specialCases.get(h) or dashCapitalize(h), v)) for (h, v) in self.headers.items()]))
+            w("&".join([("%s=%s" % (specialCases.get(h) or dashCapitalize(h), v)) for (h, v) in list(self.headers.items())]))
         return "".join(l)
 
     def __str__(self):
@@ -437,12 +437,12 @@
     
     def creationFinished(self):
         if (self.length != None) and (self.length != len(self.body)):
-            raise ValueError, "wrong body length"
+            raise ValueError("wrong body length")
         self.finished = 1
 
     def toString(self):
         s = "%s\r\n" % self._getHeaderLine()
-        for n, vs in self.headers.items():
+        for n, vs in list(self.headers.items()):
             for v in vs:
                 s += "%s: %s\r\n" % (specialCases.get(n) or dashCapitalize(n), v)
         s += "\r\n"
@@ -535,7 +535,7 @@
             self.reset()
         else:
             # we have enough data and message wasn't finished? something is wrong
-            raise RuntimeError, "this should never happen"
+            raise RuntimeError("this should never happen")
     
     def dataReceived(self, data):
         try:
@@ -655,8 +655,9 @@
                 self.handle_response(m, addr)
         self.messages[:] = []
 
-    def _fixupNAT(self, message, (srcHost, srcPort)):
+    def _fixupNAT(self, message, xxx_todo_changeme):
         # RFC 2543 6.40.2,
+        (srcHost, srcPort) = xxx_todo_changeme
         senderVia = parseViaHeader(message.headers["via"][0])
         if senderVia.host != srcHost:            
             senderVia.received = srcHost
@@ -694,7 +695,7 @@
         @param message: The message to send.
         """
         if destURL.transport not in ("udp", None):
-            raise RuntimeError, "only UDP currently supported"
+            raise RuntimeError("only UDP currently supported")
         if self.debug:
             log.msg("Sending %r to %r" % (message.toString(), destURL))
         self.transport.write(message.toString(), (destURL.host, destURL.port or self.PORT))
@@ -787,7 +788,7 @@
             f = self.handle_request_default
         try:
             d = f(message, addr)
-        except SIPError, e:
+        except SIPError as e:
             self.deliverResponse(self.responseFromRequest(e.code, message))
         except:
             log.err()
@@ -798,7 +799,7 @@
                     self.deliverResponse(self.responseFromRequest(e.code, message))
                 )
         
-    def handle_request_default(self, message, (srcHost, srcPort)):
+    def handle_request_default(self, message, xxx_todo_changeme1):
         """Default request handler.
         
         Default behaviour for OPTIONS and unknown methods for proxies
@@ -807,6 +808,7 @@
         Since at the moment we are stateless proxy, thats basically
         everything.
         """
+        (srcHost, srcPort) = xxx_todo_changeme1
         def _mungContactHeader(uri, message):
             message.headers['contact'][0] = uri.toString()            
             return self.sendMessage(uri, message)
@@ -958,12 +960,12 @@
         self.outstanding = {}
     
     def generateNonce(self):
-        c = tuple([random.randrange(sys.maxint) for _ in range(3)])
+        c = tuple([random.randrange(sys.maxsize) for _ in range(3)])
         c = '%d%d%d' % c
         return c
 
     def generateOpaque(self):
-        return str(random.randrange(sys.maxint))
+        return str(random.randrange(sys.maxsize))
 
     def getChallenge(self, peer):
         c = self.generateNonce()
@@ -1008,32 +1010,34 @@
         Proxy.__init__(self, *args, **kw)
         self.liveChallenges = {}
         
-    def handle_ACK_request(self, message, (host, port)):
+    def handle_ACK_request(self, message, xxx_todo_changeme2):
         # XXX
         # ACKs are a client's way of indicating they got the last message
         # Responding to them is not a good idea.
         # However, we should keep track of terminal messages and re-transmit
         # if no ACK is received.
+        (host, port) = xxx_todo_changeme2
         pass
 
-    def handle_REGISTER_request(self, message, (host, port)):
+    def handle_REGISTER_request(self, message, xxx_todo_changeme3):
         """Handle a registration request.
 
         Currently registration is not proxied.
         """
+        (host, port) = xxx_todo_changeme3
         if self.portal is None:
             # There is no portal.  Let anyone in.
             self.register(message, host, port)
         else:
             # There is a portal.  Check for credentials.
-            if not message.headers.has_key("authorization"):
+            if "authorization" not in message.headers:
                 return self.unauthorized(message, host, port)
             else:
                 return self.login(message, host, port)
 
     def unauthorized(self, message, host, port):
         m = self.responseFromRequest(401, message)
-        for (scheme, auth) in self.authorizers.iteritems():
+        for (scheme, auth) in self.authorizers.items():
             chal = auth.getChallenge((host, port))
             if chal is None:
                 value = '%s realm="%s"' % (scheme.title(), self.host)
@@ -1064,8 +1068,9 @@
         else:
             self.deliverResponse(self.responseFromRequest(501, message))
 
-    def _cbLogin(self, (i, a, l), message, host, port):
+    def _cbLogin(self, xxx_todo_changeme4, message, host, port):
         # It's stateless, matey.  What a joke.
+        (i, a, l) = xxx_todo_changeme4
         self.register(message, host, port)
     
     def _ebLogin(self, failure, message, host, port):
@@ -1076,7 +1081,7 @@
         """Allow all users to register"""
         name, toURL, params = parseAddress(message.headers["to"][0], clean=1)
         contact = None
-        if message.headers.has_key("contact"):
+        if "contact" in message.headers:
             contact = message.headers["contact"][0]
 
         if message.headers.get("expires", [None])[0] == "0":
@@ -1145,7 +1150,7 @@
     def getAddress(self, userURI):
         if userURI.host != self.domain:
             return defer.fail(LookupError("unknown domain"))
-        if self.users.has_key(userURI.username):
+        if userURI.username in self.users:
             dc, url = self.users[userURI.username]
             return defer.succeed(url)
         else:
@@ -1154,7 +1159,7 @@
     def getRegistrationInfo(self, userURI):
         if userURI.host != self.domain:
             return defer.fail(LookupError("unknown domain"))
-        if self.users.has_key(userURI.username):
+        if userURI.username in self.users:
             dc, url = self.users[userURI.username]
             return defer.succeed(Registration(int(dc.getTime() - time.time()), url))
         else:
@@ -1177,7 +1182,7 @@
         if logicalURL.host != self.domain:
             log.msg("Registration for domain we don't handle.")
             return defer.fail(RegistrationError(404))
-        if self.users.has_key(logicalURL.username):
+        if logicalURL.username in self.users:
             dc, old = self.users[logicalURL.username]
             dc.reset(3600)
         else:
--- twisted/protocols/socks.py (original)
+++ twisted/protocols/socks.py (refactored)
@@ -74,7 +74,7 @@
             try:
                 version,code,port=struct.unpack("!BBH",head[:4])
             except struct.error:
-                raise RuntimeError, "struct error with head='%s' and buf='%s'"%(repr(head),repr(self.buf))
+                raise RuntimeError("struct error with head='%s' and buf='%s'"%(repr(head),repr(self.buf)))
             user,self.buf=string.split(self.buf,"\000",1)
             if head[4:7]=="\000\000\000": # domain is after
                 server,self.buf=string.split(self.buf,'\000',1)
@@ -93,7 +93,7 @@
                 d = self.listenClass(0, SOCKSv4IncomingFactory, self, ip)
                 d.addCallback(lambda (h, p), self=self: self.makeReply(90, 0, p, h))
             else:
-                raise RuntimeError, "Bad Connect Code: %s" % code
+                raise RuntimeError("Bad Connect Code: %s" % code)
             assert self.buf=="","hmm, still stuff in buffer... %s" % repr(self.buf)
 
     def connectionLost(self, reason):
@@ -130,7 +130,7 @@
                                         their_peer.host,their_peer.port))
         while data:
             p,data=data[:16],data[16:]
-            f.write(string.join(map(lambda x:'%02X'%ord(x),p),' ')+' ')
+            f.write(string.join(['%02X'%ord(x) for x in p],' ')+' ')
             f.write((16-len(p))*3*' ')
             for c in p:
                 if len(repr(c))>3: f.write('.')
--- twisted/protocols/stateful.py (original)
+++ twisted/protocols/stateful.py (refactored)
@@ -7,9 +7,9 @@
 from twisted.internet import protocol
 
 try:
-    from cStringIO import StringIO
+    from io import StringIO
 except ImportError:
-    from StringIO import StringIO
+    from io import StringIO
 
 class StatefulProtocol(protocol.Protocol):
     """A Protocol that stores state for you.
--- twisted/protocols/telnet.py (original)
+++ twisted/protocols/telnet.py (refactored)
@@ -16,9 +16,9 @@
 
 # System Imports
 try:
-    from cStringIO import StringIO
+    from io import StringIO
 except ImportError:
-    from StringIO import StringIO
+    from io import StringIO
 
 # Twisted Imports
 from twisted import copyright
@@ -139,7 +139,7 @@
     }
 
 def multireplace(st, dct):
-    for k, v in dct.items():
+    for k, v in list(dct.items()):
         st = st.replace(k, v)
     return st
 
--- twisted/protocols/gps/nmea.py (original)
+++ twisted/protocols/gps/nmea.py (refactored)
@@ -71,7 +71,7 @@
         if (not dispatch) and (not self.ignore_unknown_sentencetypes):
             raise InvalidSentence("sentencetype %r" % (sentencetype,))
         if not self.ignore_checksum_mismatch:
-            checksum, calculated_checksum = int(checksum, 16), reduce(operator.xor, map(ord, strmessage))
+            checksum, calculated_checksum = int(checksum, 16), reduce(operator.xor, list(map(ord, strmessage)))
             if checksum != calculated_checksum:
                 raise InvalidChecksum("Given 0x%02X != 0x%02X" % (checksum, calculated_checksum))
         handler = getattr(self, "handle_%s" % dispatch, None)
@@ -82,7 +82,7 @@
         # return handler(*decoder(*message))
         try:
             decoded = decoder(*message)
-        except Exception, e:
+        except Exception as e:
             raise InvalidSentence("%r is not a valid %s (%s) sentence" % (line, sentencetype, dispatch))
         return handler(*decoded)
 
@@ -137,7 +137,7 @@
         )
 
     def _decode_utc(self, utc):
-        utc_hh, utc_mm, utc_ss = map(float, (utc[:2], utc[2:4], utc[4:]))
+        utc_hh, utc_mm, utc_ss = list(map(float, (utc[:2], utc[2:4], utc[4:])))
         return utc_hh * 3600.0 + utc_mm * 60.0 + utc_ss
 
     def _decode_latlon(self, latitude, ns, longitude, ew):
@@ -150,7 +150,7 @@
         return (latitude, longitude)
 
     def decode_activesatellites(self, mode1, mode2, *args):
-        satellites, (pdop, hdop, vdop) = args[:12], map(float, args[12:])
+        satellites, (pdop, hdop, vdop) = args[:12], list(map(float, args[12:]))
         satlist = []
         for n in satellites:
             if n:
--- twisted/protocols/gps/rockwell.py (original)
+++ twisted/protocols/gps/rockwell.py (refactored)
@@ -189,7 +189,7 @@
   def decode_id(self, message):
     assert len(message) == 106, "Receiver ID Message should be 59 words total (106 byte message)"
     ticks, msgseq, channels, software_version, software_date, options_list, reserved = struct.unpack('<Lh20s20s20s20s20s', message)
-    channels, software_version, software_date, options_list = map(lambda s: s.split('\0')[0], (channels, software_version, software_date, options_list))
+    channels, software_version, software_date, options_list = [s.split('\0')[0] for s in (channels, software_version, software_date, options_list)]
     software_version = float(software_version)
     channels = int(channels) # 0-12 .. but ALWAYS 12, so we ignore.
     options_list = int(options_list[:4], 16) # only two bitflags, others are reserved
@@ -216,12 +216,12 @@
   def decode_satellites(self, message):
     assert len(message) == 90, "Visible Satellites Message should be 51 words total (90 byte message)"
     ticks, msgseq, gdop, pdop, hdop, vdop, tdop, numsatellites = struct.unpack('<LhhhhhhH', message[:18])
-    gdop, pdop, hdop, vdop, tdop = map(lambda n: float(n) * 0.01, (gdop, pdop, hdop, vdop, tdop))
+    gdop, pdop, hdop, vdop, tdop = [float(n) * 0.01 for n in (gdop, pdop, hdop, vdop, tdop)]
     satellites = []
     message = message[18:]
     for i in range(numsatellites):
       prn, azi, elev = struct.unpack('<Hhh', message[6 * i:6 * (i + 1)])
-      azi, elev = map(lambda n: (float(n) * 0.0180 / math.pi), (azi, elev))
+      azi, elev = [(float(n) * 0.0180 / math.pi) for n in (azi, elev)]
       satellites.push((prn, azi, elev))
     # ((PRN [0, 32], azimuth +=[0.0, 180.0] deg, elevation +-[0.0, 90.0] deg)) satellite info (0-12)
     # (geometric, position, horizontal, vertical, time) dilution of precision 
--- twisted/python/_release.py (original)
+++ twisted/python/_release.py (refactored)
@@ -160,7 +160,7 @@
         based on live python modules.
         """
         namespace = {}
-        execfile(self.directory.child("_version.py").path, namespace)
+        exec(open(self.directory.child("_version.py").path).read(), namespace)
         return namespace["version"]
 
 
@@ -251,7 +251,7 @@
     f = open(filename+'.bak')
     d = f.read()
     f.close()
-    for k,v in oldToNew.items():
+    for k,v in list(oldToNew.items()):
         d = d.replace(k, v)
     f = open(filename + '.new', 'w')
     f.write(d)
--- twisted/python/compat.py (original)
+++ twisted/python/compat.py (refactored)
@@ -120,7 +120,7 @@
 
         def __init__(self, *args):
             from OpenSSL import SSL as _ssl
-            self._ssl_conn = apply(_ssl.Connection, args)
+            self._ssl_conn = _ssl.Connection(*args)
             from threading import _RLock
             self._lock = _RLock()
 
@@ -135,12 +135,12 @@
                   'set_connect_state', 'set_accept_state',
                   'connect_ex', 'sendall'):
 
-            exec """def %s(self, *args):
+            exec("""def %s(self, *args):
                 self._lock.acquire()
                 try:
                     return apply(self._ssl_conn.%s, args)
                 finally:
-                    self._lock.release()\n""" % (f, f)
+                    self._lock.release()\n""" % (f, f))
 sys.modules['OpenSSL.tsafe'] = tsafe
 
 import operator
--- twisted/python/components.py (original)
+++ twisted/python/components.py (refactored)
@@ -261,7 +261,7 @@
         @return: a list of the interfaces that were removed.
         """
         l = []
-        for k, v in self._adapterCache.items():
+        for k, v in list(self._adapterCache.items()):
             if v is component:
                 del self._adapterCache[k]
                 l.append(reflect.namedObject(k))
@@ -284,7 +284,7 @@
         True on your adapter class.
         """
         k = reflect.qual(interface)
-        if self._adapterCache.has_key(k):
+        if k in self._adapterCache:
             return self._adapterCache[k]
         else:
             adapter = interface.__adapt__(self)
@@ -309,7 +309,7 @@
         Componentized.__init__(self)
 
     def __repr__(self):
-        from cStringIO import StringIO
+        from io import StringIO
         from pprint import pprint
         sio = StringIO()
         pprint(self._adapterCache, sio)
--- twisted/python/dispatch.py (original)
+++ twisted/python/dispatch.py (refactored)
@@ -33,7 +33,7 @@
         from twisted.python import reflect
         d = {}
         reflect.accumulateMethods(obj, d, self.prefix)
-        for k,v in d.items():
+        for k,v in list(d.items()):
             self.registerHandler(k, v)
 
 
--- twisted/python/dist.py (original)
+++ twisted/python/dist.py (refactored)
@@ -116,7 +116,7 @@
     else:
         vfile = os.path.join(base, proj, '_version.py')
     ns = {'__name__': 'Nothing to see here'}
-    execfile(vfile, ns)
+    exec(open(vfile).read(), ns)
     return ns['version'].base()
 
 
@@ -247,8 +247,8 @@
     thingies = os.listdir(scriptdir)
     if '.svn' in thingies:
         thingies.remove('.svn')
-    return filter(os.path.isfile,
-                  [os.path.join(scriptdir, x) for x in thingies])
+    return list(filter(os.path.isfile,
+                  [os.path.join(scriptdir, x) for x in thingies]))
 
 
 ## Helpers and distutil tweaks
@@ -279,7 +279,7 @@
             if not fpath.endswith(".py"):
                 try:
                     os.unlink(fpath + ".py")
-                except EnvironmentError, e:
+                except EnvironmentError as e:
                     if e.args[1]=='No such file or directory':
                         pass
                 os.rename(fpath, fpath + ".py")
--- twisted/python/dxprofile.py (original)
+++ twisted/python/dxprofile.py (refactored)
@@ -11,7 +11,7 @@
 and optionally DXPAIRS, defined to be useful.
 """
 
-import sys, types, xmlrpclib, warnings
+import sys, types, xmlrpc.client, warnings
 
 
 warnings.warn("twisted.python.dxprofile is deprecated since Twisted 8.0.",
@@ -26,7 +26,7 @@
     runlen = 1
     result = []
     try:
-        previous = iterable.next()
+        previous = next(iterable)
     except StopIteration:
         return []
     for element in iterable:
@@ -34,12 +34,12 @@
             runlen = runlen + 1
             continue
         else:
-            if isinstance(previous, (types.ListType, types.TupleType)):
+            if isinstance(previous, (list, tuple)):
                 previous = rle(previous)
             result.append([previous, runlen])
         previous = element
         runlen = 1
-    if isinstance(previous, (types.ListType, types.TupleType)):
+    if isinstance(previous, (list, tuple)):
         previous = rle(previous)
     result.append([previous, runlen])
     return result
@@ -52,5 +52,5 @@
     for analysis.
     """
     if hasattr(sys, 'getdxp') and appname:
-        dxp = xmlrpclib.ServerProxy("http://manatee.mojam.com:7304")
+        dxp = xmlrpc.client.ServerProxy("http://manatee.mojam.com:7304")
         dxp.add_dx_info(appname, email, sys.version_info[:3], rle(sys.getdxp()))
--- twisted/python/failure.py (original)
+++ twisted/python/failure.py (refactored)
@@ -16,7 +16,7 @@
 import linecache
 import inspect
 import opcode
-from cStringIO import StringIO
+from io import StringIO
 
 from twisted.python import reflect
 
@@ -40,7 +40,7 @@
     @type detail: string
     """
     if detail not in ('default', 'brief', 'verbose'):
-        raise ValueError, "Detail must be default, brief, or verbose. (not %r)" % (detail,)
+        raise ValueError("Detail must be default, brief, or verbose. (not %r)" % (detail,))
     w = write
     if detail == "brief":
         for method, filename, lineno, localVars, globalVars in frames:
@@ -163,7 +163,7 @@
         self.type = self.value = tb = None
 
         #strings Exceptions/Failures are bad, mmkay?
-        if isinstance(exc_value, (str, unicode)) and exc_type is None:
+        if isinstance(exc_value, (str, str)) and exc_type is None:
             import warnings
             warnings.warn(
                 "Don't pass strings (like %r) to failure.Failure (replacing with a DefaultException)." %
@@ -238,14 +238,14 @@
             else:
                 globalz = f.f_globals.copy()
             for d in globalz, localz:
-                if d.has_key("__builtins__"):
+                if "__builtins__" in d:
                     del d["__builtins__"]
             stack.insert(0, [
                 f.f_code.co_name,
                 f.f_code.co_filename,
                 f.f_lineno,
-                localz.items(),
-                globalz.items(),
+                list(localz.items()),
+                list(globalz.items()),
                 ])
             f = f.f_back
 
@@ -257,20 +257,20 @@
             else:
                 globalz = f.f_globals.copy()
             for d in globalz, localz:
-                if d.has_key("__builtins__"):
+                if "__builtins__" in d:
                     del d["__builtins__"]
 
             frames.append([
                 f.f_code.co_name,
                 f.f_code.co_filename,
                 tb.tb_lineno,
-                localz.items(),
-                globalz.items(),
+                list(localz.items()),
+                list(globalz.items()),
                 ])
             tb = tb.tb_next
         if inspect.isclass(self.type) and issubclass(self.type, Exception):
             parentCs = reflect.allYourBase(self.type)
-            self.parents = map(reflect.qual, parentCs)
+            self.parents = list(map(reflect.qual, parentCs))
             self.parents.append(reflect.qual(self.type))
         else:
             self.parents = [self.type]
@@ -323,7 +323,7 @@
         raise the original exception, preserving traceback
         information if available.
         """
-        raise self.type, self.value, self.tb
+        raise self.type(self.value).with_traceback(self.tb)
 
 
     def throwExceptionIntoGenerator(self, g):
@@ -335,7 +335,7 @@
         @raise StopIteration: If there are no more values in the generator.
         @raise anything else: Anything that the generator raises.
         """
-        return g.throw(self.type, self.value, self.tb)
+        return g.throw(self.type(self.value).with_traceback(self.tb))
 
 
     def _findFailure(cls):
@@ -361,7 +361,7 @@
         # the tracebacks) here when it is used is not that big a deal.
 
         # handle raiseException-originated exceptions
-        if lastFrame.f_code is cls.raiseException.func_code:
+        if lastFrame.f_code is cls.raiseException.__code__:
             return lastFrame.f_locals.get('self')
 
         # handle throwExceptionIntoGenerator-originated exceptions
@@ -382,7 +382,7 @@
         # second last item):
         if secondLastTb:
             frame = secondLastTb.tb_frame
-            if frame.f_code is cls.throwExceptionIntoGenerator.func_code:
+            if frame.f_code is cls.throwExceptionIntoGenerator.__code__:
                 return frame.f_locals.get('self')
 
         # if the exception was caught below the generator.throw
@@ -391,7 +391,7 @@
         # generator frame itself, thus its caller is
         # throwExceptionIntoGenerator).
         frame = tb.tb_frame.f_back
-        if frame and frame.f_code is cls.throwExceptionIntoGenerator.func_code:
+        if frame and frame.f_code is cls.throwExceptionIntoGenerator.__code__:
             return frame.f_locals.get('self')
 
     _findFailure = classmethod(_findFailure)
@@ -510,7 +510,7 @@
             # qual() doesn't make any sense on a string, so check for this
             # case here and just write out the string if that's what we
             # have.
-            if isinstance(self.type, (str, unicode)):
+            if isinstance(self.type, (str, str)):
                 w(self.type + "\n")
             else:
                 w("%s: %s\n" % (reflect.qual(self.type),
@@ -538,11 +538,11 @@
 DO_POST_MORTEM = True
 
 def _debuginit(self, exc_value=None, exc_type=None, exc_tb=None,
-             Failure__init__=Failure.__init__.im_func):
+             Failure__init__=Failure.__init__.__func__):
     if (exc_value, exc_type, exc_tb) == (None, None, None):
         exc = sys.exc_info()
         if not exc[0] == self.__class__ and DO_POST_MORTEM:
-            print "Jumping into debugger for post-mortem of exception '%s':" % exc[1]
+            print("Jumping into debugger for post-mortem of exception '%s':" % exc[1])
             import pdb
             pdb.post_mortem(exc[2])
     Failure__init__(self, exc_value, exc_type, exc_tb)
@@ -554,4 +554,4 @@
 
 # Sibling imports - at the bottom and unqualified to avoid unresolvable
 # circularity
-import log
+from . import log
--- twisted/python/filepath.py (original)
+++ twisted/python/filepath.py (refactored)
@@ -51,7 +51,7 @@
     @return: C{n} bytes of random data.
     @rtype: str
     """
-    randomData = [random.randrange(256) for n in xrange(n)]
+    randomData = [random.randrange(256) for n in range(n)]
     return ''.join(map(chr, randomData))
 
 
@@ -151,7 +151,7 @@
         """
         try:
             subnames = self.listdir()
-        except WindowsError, winErrObj:
+        except WindowsError as winErrObj:
             # WindowsError is an OSError subclass, so if not for this clause
             # the OSError clause below would be handling these.  Windows error
             # codes aren't the same as POSIX error codes, so we need to handle
@@ -181,14 +181,14 @@
                                 ERROR_DIRECTORY):
                 raise
             raise _WindowsUnlistableError(winErrObj)
-        except OSError, ose:
+        except OSError as ose:
             if ose.errno not in (errno.ENOENT, errno.ENOTDIR):
                 # Other possible errors here, according to linux manpages:
                 # EACCES, EMIFLE, ENFILE, ENOMEM.  None of these seem like the
                 # sort of thing which should be handled normally. -glyph
                 raise
             raise UnlistableError(ose)
-        return map(self.child, subnames)
+        return list(map(self.child, subnames))
 
     def walk(self, descend=None):
         """
@@ -317,7 +317,7 @@
 
     def __getstate__(self):
         d = self.__dict__.copy()
-        if d.has_key('statinfo'):
+        if 'statinfo' in d:
             del d['statinfo']
         return d
 
@@ -607,7 +607,7 @@
         """
         import glob
         path = self.path[-1] == '/' and self.path + pattern or slash.join([self.path, pattern])
-        return map(self.clonePath, glob.glob(path))
+        return list(map(self.clonePath, glob.glob(path)))
 
     def basename(self):
         return basename(self.path)
@@ -756,7 +756,7 @@
         try:
             os.rename(self.path, destination.path)
             self.restat(False)
-        except OSError, ose:
+        except OSError as ose:
             if ose.errno == errno.EXDEV:
                 # man 2 rename, ubuntu linux 5.10 "breezy":
 
--- twisted/python/finalize.py (original)
+++ twisted/python/finalize.py (refactored)
@@ -24,7 +24,7 @@
 
 if __name__ == '__main__':
     def fin():
-        print 'I am _so_ dead.'
+        print('I am _so_ dead.')
 
     class Finalizeable:
         """
@@ -43,4 +43,4 @@
     del f
     import gc
     gc.collect()
-    print 'deled'
+    print('deled')
--- twisted/python/formmethod.py (original)
+++ twisted/python/formmethod.py (refactored)
@@ -59,7 +59,7 @@
 
     def coerce(self, val):
         """Convert the value to the correct format."""
-        raise NotImplementedError, "implement in subclass"
+        raise NotImplementedError("implement in subclass")
 
 
 class String(Argument):
@@ -79,9 +79,9 @@
     def coerce(self, val):
         s = str(val)
         if len(s) < self.min:
-            raise InputError, "Value must be at least %s characters long" % self.min
+            raise InputError("Value must be at least %s characters long" % self.min)
         if self.max != None and len(s) > self.max:
-            raise InputError, "Value must be at most %s characters long" % self.max
+            raise InputError("Value must be at most %s characters long" % self.max)
         return str(val)
 
 
@@ -100,12 +100,12 @@
     
     def coerce(self, vals):
         if len(vals) != 2 or vals[0] != vals[1]:
-            raise InputError, "Please enter the same password twice."
+            raise InputError("Please enter the same password twice.")
         s = str(vals[0])
         if len(s) < self.min:
-            raise InputError, "Value must be at least %s characters long" % self.min
+            raise InputError("Value must be at least %s characters long" % self.min)
         if self.max != None and len(s) > self.max:
-            raise InputError, "Value must be at most %s characters long" % self.max
+            raise InputError("Value must be at most %s characters long" % self.max)
         return s
 
 
@@ -137,7 +137,7 @@
         try:
             return int(val)
         except ValueError:
-            raise InputError, "%s is not valid, please enter a whole number, e.g. 10" % val
+            raise InputError("%s is not valid, please enter a whole number, e.g. 10" % val)
 
 
 class IntegerRange(Integer):
@@ -154,9 +154,9 @@
         if self.allowNone and result == None:
             return result
         if result < self.min:
-            raise InputError, "Value %s is too small, it should be at least %s" % (result, self.min)
+            raise InputError("Value %s is too small, it should be at least %s" % (result, self.min))
         if result > self.max:
-            raise InputError, "Value %s is too large, it should be at most %s" % (result, self.max)
+            raise InputError("Value %s is too large, it should be at most %s" % (result, self.max))
         return result
 
 
@@ -181,7 +181,7 @@
         try:
             return float(val)
         except ValueError:
-            raise InputError, "Invalid float: %s" % val
+            raise InputError("Invalid float: %s" % val)
 
 
 class Choice(Argument):
@@ -267,7 +267,7 @@
         elif file:
             return file
         else:
-            raise InputError, "Invalid File"
+            raise InputError("Invalid File")
 
 def positiveInt(x):
     x = int(x)
@@ -292,20 +292,20 @@
             return None
         
         try:
-            year, month, day = map(positiveInt, args)
+            year, month, day = list(map(positiveInt, args))
         except ValueError:
-            raise InputError, "Invalid date"
+            raise InputError("Invalid date")
         if (month, day) == (2, 29):
             if not calendar.isleap(year):
-                raise InputError, "%d was not a leap year" % year
+                raise InputError("%d was not a leap year" % year)
             else:
                 return year, month, day
         try:
             mdays = calendar.mdays[month]
         except IndexError:
-            raise InputError, "Invalid date"
+            raise InputError("Invalid date")
         if day > mdays:
-            raise InputError, "Invalid date"
+            raise InputError("Invalid date")
         return year, month, day
 
 
--- twisted/python/hook.py (original)
+++ twisted/python/hook.py (refactored)
@@ -155,12 +155,12 @@
             for postMethod in getattr(klass, POST(klass, name)):
                 postMethod(*args, **kw)
     try:
-        newfunc.func_name = name
+        newfunc.__name__ = name
     except TypeError:
         # Older python's don't let you do this
         pass
 
-    oldfunc = getattr(klass, name).im_func
+    oldfunc = getattr(klass, name).__func__
     setattr(klass, ORIG(klass, name), oldfunc)
     setattr(klass, PRE(klass, name), [])
     setattr(klass, POST(klass, name), [])
--- twisted/python/htmlizer.py (original)
+++ twisted/python/htmlizer.py (refactored)
@@ -3,7 +3,7 @@
 
 #
 import tokenize, cgi, keyword
-import reflect
+from . import reflect
 
 class TokenPrinter:
 
@@ -13,10 +13,12 @@
     def __init__(self, writer):
         self.writer = writer
 
-    def printtoken(self, type, token, (srow, scol), (erow, ecol), line):
+    def printtoken(self, type, token, xxx_todo_changeme, xxx_todo_changeme1, line):
         #print "printtoken(%r,%r,%r,(%r,%r),(%r,%r),%r), row=%r,col=%r" % (
         #    self, type, token, srow,scol, erow,ecol, line,
         #    self.currentLine, self.currentCol)
+        (srow, scol) = xxx_todo_changeme
+        (erow, ecol) = xxx_todo_changeme1
         if self.currentLine < srow:
             self.writer('\n'*(srow-self.currentLine))
             self.currentLine, self.currentCol = srow, 0
@@ -81,7 +83,7 @@
 
 def main():
     import sys
-    filter(open(sys.argv[1]), sys.stdout)
+    list(filter(open(sys.argv[1]), sys.stdout))
 
 if __name__ == '__main__':
    main()
--- twisted/python/lockfile.py (original)
+++ twisted/python/lockfile.py (refactored)
@@ -14,7 +14,7 @@
 from time import time as _uniquefloat
 
 def unique():
-    return str(long(_uniquefloat() * 1000))
+    return str(int(_uniquefloat() * 1000))
 
 from os import rename
 try:
@@ -36,7 +36,7 @@
     def kill(pid, signal):
         try:
             OpenProcess(0, 0, pid)
-        except pywintypes.error, e:
+        except pywintypes.error as e:
             if e.args[0] == ERROR_ACCESS_DENIED:
                 return
             elif e.args[0] == ERROR_INVALID_PARAMETER:
@@ -64,7 +64,7 @@
     def readlink(filename):
         try:
             fObj = _open(os.path.join(filename,'symlink'), 'rb')
-        except IOError, e:
+        except IOError as e:
             if e.errno == errno.ENOENT or e.errno == errno.EIO:
                 raise OSError(e.errno, None)
             raise
@@ -119,7 +119,7 @@
         while True:
             try:
                 symlink(str(os.getpid()), self.name)
-            except OSError, e:
+            except OSError as e:
                 if _windows and e.errno in (errno.EACCES, errno.EIO):
                     # The lock is in the middle of being deleted because we're
                     # on Windows where lock removal isn't atomic.  Give up, we
@@ -128,13 +128,13 @@
                 if e.errno == errno.EEXIST:
                     try:
                         pid = readlink(self.name)
-                    except OSError, e:
+                    except OSError as e:
                         if e.errno == errno.ENOENT:
                             # The lock has vanished, try to claim it in the
                             # next iteration through the loop.
                             continue
                         raise
-                    except IOError, e:
+                    except IOError as e:
                         if _windows and e.errno == errno.EACCES:
                             # The lock is in the middle of being
                             # deleted because we're on Windows where
@@ -145,13 +145,13 @@
                         raise
                     try:
                         kill(int(pid), 0)
-                    except OSError, e:
+                    except OSError as e:
                         if e.errno == errno.ESRCH:
                             # The owner has vanished, try to claim it in the next
                             # iteration through the loop.
                             try:
                                 rmlink(self.name)
-                            except OSError, e:
+                            except OSError as e:
                                 if e.errno == errno.ENOENT:
                                     # Another process cleaned up the lock.
                                     # Race them to acquire it in the next
--- twisted/python/log.py (original)
+++ twisted/python/log.py (refactored)
@@ -6,7 +6,7 @@
 Logging and metrics infrastructure.
 """
 
-from __future__ import division
+
 
 import sys
 import time
@@ -258,7 +258,7 @@
         @param other: A callable object that will be called with each new log
             message (a dict).
         """
-        assert callable(other)
+        assert hasattr(other, '__call__')
         self.observers.append(other)
 
     def removeObserver(self, other):
@@ -287,7 +287,7 @@
         actualEventDict.update(kw)
         actualEventDict['message'] = message
         actualEventDict['time'] = time.time()
-        for i in xrange(len(self.observers) - 1, -1, -1):
+        for i in range(len(self.observers) - 1, -1, -1):
             try:
                 self.observers[i](actualEventDict)
             except KeyboardInterrupt:
--- twisted/python/logfile.py (original)
+++ twisted/python/logfile.py (refactored)
@@ -65,7 +65,7 @@
         else:
             if self.defaultMode is not None:
                 # Set the lowest permissions
-                oldUmask = os.umask(0777)
+                oldUmask = os.umask(0o777)
                 try:
                     self._file = file(self.path, "w+", 1)
                 finally:
@@ -164,7 +164,7 @@
         """
         filename = "%s.%d" % (self.path, identifier)
         if not os.path.exists(filename):
-            raise ValueError, "no such logfile exists"
+            raise ValueError("no such logfile exists")
         return LogReader(filename)
 
     def write(self, data):
@@ -252,7 +252,7 @@
             return self.getCurrentLog()
         filename = "%s.%s" % (self.path, self.suffix(identifier))
         if not os.path.exists(filename):
-            raise ValueError, "no such logfile exists"
+            raise ValueError("no such logfile exists")
         return LogReader(filename)
 
     def write(self, data):
--- twisted/python/modules.py (original)
+++ twisted/python/modules.py (refactored)
@@ -644,7 +644,7 @@
             for hook in self.sysPathHooks:
                 try:
                     importr = hook(pathName)
-                except ImportError, ie:
+                except ImportError as ie:
                     pass
             if importr is _nothing: # still
                 importr = None
--- twisted/python/otp.py (original)
+++ twisted/python/otp.py (refactored)
@@ -36,7 +36,7 @@
 
 def stringToLong(s):
     """ Convert digest to long """
-    result = 0L
+    result = 0
     for byte in s:
         result = (256 * result) + ord(byte)
     return result
@@ -44,8 +44,8 @@
 def stringToDWords(s):
     """ Convert digest to a list of four 32-bits words """
     result = []
-    for a in xrange(len(s) / 4):
-        tmp = 0L
+    for a in range(len(s) / 4):
+        tmp = 0
         for byte in s[-4:]:
             tmp = (256 * tmp) + ord(byte)
         result.append(tmp)
@@ -55,9 +55,9 @@
 def longToString(l):
     """ Convert long to digest """
     result = ""
-    while l > 0L:
+    while l > 0:
         result = chr(l % 256) + result
-        l = l / 256L
+        l = l / 256
     return result
 
 from twisted.python.hashlib import md5, sha1
@@ -111,10 +111,10 @@
         p0 = regs[0] ^ regs[2]
         p1 = regs[1] ^ regs[3]
         S = ''
-        for a in xrange(4):
+        for a in range(4):
             S = chr(p0 & 0xFF) + S
             p0 = p0 >> 8
-        for a in xrange(4):
+        for a in range(4):
             S = chr(p1 & 0xFF) + S
             p1 = p1 >> 8
         return S
@@ -126,10 +126,10 @@
         p1 = regs[1] ^ regs[3]
         p0 = regs[0] ^ regs[4]
         S = ''
-        for a in xrange(4):
+        for a in range(4):
             S = chr(p0 & 0xFF) + S
             p0 = p0 >> 8
-        for a in xrange(4):
+        for a in range(4):
             S = chr(p1 & 0xFF) + S
             p1 = p1 >> 8
         return S
@@ -144,14 +144,14 @@
         Run through makeReadable to get a 6 word pass-phrase"""
         seed = string.lower(seed)
         otp = self.hashUpdate(seed + passwd)
-        for a in xrange(sequence):
+        for a in range(sequence):
             otp = self.hashUpdate(otp)
         return otp
 
     def calculateParity(self, otp):
         "Calculate the parity from a 64bit OTP"
         parity = 0
-        for i in xrange(0, 64, 2):
+        for i in range(0, 64, 2):
             parity = parity + otp & 0x3
             otp = otp >> 2
         return parity
@@ -161,7 +161,7 @@
         digest = stringToLong(otp)
         list = []
         parity = self.calculateParity(digest)
-        for i in xrange(4,-1, -1):
+        for i in range(4,-1, -1):
             list.append(dict[(digest >> (i * 11 + 9)) & 0x7FF])
         list.append(dict[(digest << 2) & 0x7FC | (parity & 0x03)])
         return string.join(list)
@@ -175,14 +175,14 @@
         I will raise Unauthorized if the parity is wrong
         TODO: Add support for hex (MUST) and the '2nd scheme'(SHOULD)"""
         words = string.split(phrase)
-        for i in xrange(len(words)):
+        for i in range(len(words)):
             words[i] = string.upper(words[i])
-        b = 0L
-        for i in xrange(0,5):
-            b = b | ((long(dict.index(words[i])) << ((4-i)*11L+9L)))
+        b = 0
+        for i in range(0,5):
+            b = b | ((int(dict.index(words[i])) << ((4-i)*11+9)))
         tmp = dict.index(words[5])
         b = b | (tmp & 0x7FC ) >> 2
-        if (tmp & 3) <> self.calculateParity(b):
+        if (tmp & 3) != self.calculateParity(b):
             raise Unauthorized("Parity error")
         digest = longToString(b)
         return digest
@@ -231,7 +231,7 @@
                 return "ok"
             else:
                 raise Unauthorized("Failed")
-        except Unauthorized, msg:
+        except Unauthorized as msg:
             raise Unauthorized(msg)
 
 #
--- twisted/python/plugin.py (original)
+++ twisted/python/plugin.py (refactored)
@@ -2,7 +2,7 @@
 # See LICENSE for details.
 
 
-from __future__ import nested_scopes
+
 
 # System Imports
 import sys
@@ -15,7 +15,7 @@
 from twisted.python import util
 
 # Sibling Imports
-from reflect import namedModule
+from .reflect import namedModule
 
 try:
     from os.path import realpath as cacheTransform
@@ -28,7 +28,7 @@
     def __init__(self, name, module, **kw):
         self.name = name
         self.module = module
-        for key, value in kw.items():
+        for key, value in list(kw.items()):
             setattr(self, key, value)
 
     def isLoaded(self):
@@ -38,7 +38,7 @@
         @return: A true value if the module for this plugin has been loaded,
         false otherwise.
         """
-        return sys.modules.has_key(self.module)
+        return self.module in sys.modules
 
     def load(self):
         """Load the module for this plugin.
@@ -111,13 +111,13 @@
     @rtype: C{list} of C{str}
     @return: A list of the plugin.tml files found.
     """
-    if isinstance(debugInspection, types.IntType):
+    if isinstance(debugInspection, int):
         warnings.warn(
             "int parameter for debugInspection is deprecated, pass None or "
             "a function that takes a single argument instead.",
             DeprecationWarning, 2
         )
-    if isinstance(showProgress, types.IntType):
+    if isinstance(showProgress, int):
         warnings.warn(
             "int parameter for showProgress is deprecated, pass None or "
             "a function that takes a single argument instead.",
@@ -148,16 +148,18 @@
     progress = 0.0
     increments = 1.0 / len(paths)
 
-    for (index, d) in zip(range(len(paths)), paths):
+    for (index, d) in zip(list(range(len(paths))), paths):
         showProgress(progress)
-        if loaded.has_key(d):
+        if d in loaded:
             debugInspection('Already saw ' + d)
             continue
         else:
             debugInspection('Recursing through ' + d)
         try:
             subDirs = os.listdir(d)
-        except OSError, (err, s):
+        except OSError as xxx_todo_changeme:
+            # Permission denied, carry on
+            (err, s) = xxx_todo_changeme.args
             # Permission denied, carry on
             if err == errno.EACCES:
                 debugInspection('Permission denied on ' + d)
@@ -170,7 +172,7 @@
                 continue
             incr = increments * (1.0 / len(subDirs))
             for plugindir in subDirs:
-                if seenNames.has_key(plugindir):
+                if plugindir in seenNames:
                     debugInspection('Seen %s already' % plugindir)
                     continue
                 tmlname = join((d, plugindir, "plugins.tml"))
@@ -216,13 +218,13 @@
     @rtype: C{list}
     @return: A list of the C{PlugIn} objects found.
     """
-    if isinstance(debugInspection, types.IntType):
+    if isinstance(debugInspection, int):
         warnings.warn(
             "int parameter for debugInspection is deprecated, pass None or "
             "a function that takes a single argument instead.",
             DeprecationWarning, 4
         )
-    if isinstance(showProgress, types.IntType):
+    if isinstance(showProgress, int):
         warnings.warn(
             "int parameter for showProgress is deprecated, pass None or "
             "a function that takes a single argument instead.",
@@ -237,15 +239,15 @@
     increments = 1.0 / len(fileList)
     progress = 0.0
 
-    for (index, tmlFile) in zip(range(len(fileList)), fileList):
+    for (index, tmlFile) in zip(list(range(len(fileList))), fileList):
         showProgress(progress)
         debugInspection("Loading from " + tmlFile)
         pname = os.path.split(os.path.abspath(tmlFile))[-2]
         dropin = DropIn(pname)
         ns = {'register': dropin.register, '__file__': tmlFile}
         try:
-            execfile(tmlFile, ns)
-        except (IOError, OSError), e:
+            exec(open(tmlFile).read(), ns)
+        except (IOError, OSError) as e:
             # guess we don't have permissions for that
             debugInspection("Error loading: %s" % e)
             continue
@@ -294,13 +296,13 @@
     return _getPlugIns(plugInType, debugInspection, showProgress)
 
 def _getPlugIns(plugInType, debugInspection=None, showProgress=None):
-    if isinstance(debugInspection, types.IntType):
+    if isinstance(debugInspection, int):
         warnings.warn(
             "int parameter for debugInspection is deprecated, pass None or "
             "a function that takes a single argument instead.",
             DeprecationWarning, 3
         )
-    if isinstance(showProgress, types.IntType):
+    if isinstance(showProgress, int):
         warnings.warn(
             "int parameter for showProgress is deprecated, pass None or "
             "a function that takes a single argument instead.",
--- twisted/python/procutils.py (original)
+++ twisted/python/procutils.py (refactored)
@@ -29,7 +29,7 @@
     order in which they were found.
     """
     result = []
-    exts = filter(None, os.environ.get('PATHEXT', '').split(os.pathsep))
+    exts = [_f for _f in os.environ.get('PATHEXT', '').split(os.pathsep) if _f]
     path = os.environ.get('PATH', None)
     if path is None:
         return []
--- twisted/python/randbytes.py (original)
+++ twisted/python/randbytes.py (refactored)
@@ -59,7 +59,7 @@
         """
         try:
             return os.urandom(nbytes)
-        except (AttributeError, NotImplementedError), e:
+        except (AttributeError, NotImplementedError) as e:
             raise SourceNotAvailable(e)
 
 
@@ -141,7 +141,7 @@
         Wrapper around C{random.randrange}.
         """
         bytes = ""
-        for i in xrange(nbytes):
+        for i in range(nbytes):
             bytes += chr(random.randrange(0, 255))
         return bytes
 
--- twisted/python/rebuild.py (original)
+++ twisted/python/rebuild.py (refactored)
@@ -47,15 +47,15 @@
         if t == types.FunctionType:
             return latestFunction(anObject)
         elif t == types.MethodType:
-            if anObject.im_self is None:
-                return getattr(anObject.im_class, anObject.__name__)
+            if anObject.__self__ is None:
+                return getattr(anObject.__self__.__class__, anObject.__name__)
             else:
-                return getattr(anObject.im_self, anObject.__name__)
+                return getattr(anObject.__self__, anObject.__name__)
         elif t == types.InstanceType:
             # Kick it, if it's out of date.
             getattr(anObject, 'nothing', None)
             return anObject
-        elif t == types.ClassType:
+        elif t == type:
             return latestClass(anObject)
         else:
             log.msg('warning returning anObject!')
@@ -69,7 +69,7 @@
     """
     # This may be CPython specific, since I believe jython instantiates a new
     # module upon reload.
-    dictID = id(oldFunc.func_globals)
+    dictID = id(oldFunc.__globals__)
     module = _modDictIDMap.get(dictID)
     if module is None:
         return oldFunc
@@ -152,8 +152,8 @@
     values = {}
     if doLog:
         log.msg('  (scanning %s): ' % str(module.__name__))
-    for k, v in d.items():
-        if type(v) == types.ClassType:
+    for k, v in list(d.items()):
+        if type(v) == type:
             # Failure condition -- instances of classes with buggy
             # __hash__/__cmp__ methods referenced at the module level...
             if v.__module__ == module.__name__:
@@ -162,7 +162,7 @@
                     log.logfile.write("c")
                     log.logfile.flush()
         elif type(v) == types.FunctionType:
-            if v.func_globals is module.__dict__:
+            if v.__globals__ is module.__dict__:
                 functions[v] = 1
                 if doLog:
                     log.logfile.write("f")
@@ -177,9 +177,9 @@
     values.update(classes)
     values.update(functions)
     fromOldModule = values.has_key
-    newclasses = newclasses.keys()
-    classes = classes.keys()
-    functions = functions.keys()
+    newclasses = list(newclasses.keys())
+    classes = list(classes.keys())
+    functions = list(functions.keys())
 
     if doLog:
         log.msg('')
@@ -218,7 +218,7 @@
         log.msg('')
         log.msg('  (fixing   %s): ' % str(module.__name__))
     modcount = 0
-    for mk, mod in sys.modules.items():
+    for mk, mod in list(sys.modules.items()):
         modcount = modcount + 1
         if mod == module or mod is None:
             continue
@@ -228,13 +228,13 @@
             continue
         changed = 0
 
-        for k, v in mod.__dict__.items():
+        for k, v in list(mod.__dict__.items()):
             try:
                 hash(v)
             except TypeError:
                 continue
             if fromOldModule(v):
-                if type(v) == types.ClassType:
+                if type(v) == type:
                     if doLog:
                         log.logfile.write("c")
                         log.logfile.flush()
@@ -248,7 +248,7 @@
                 setattr(mod, k, nv)
             else:
                 # Replace bases of non-module classes just to be sure.
-                if type(v) == types.ClassType:
+                if type(v) == type:
                     for base in v.__bases__:
                         if fromOldModule(base):
                             latestClass(v)
--- twisted/python/reflect.py (original)
+++ twisted/python/reflect.py (refactored)
@@ -26,9 +26,9 @@
 
 
 try:
-    from cStringIO import StringIO
+    from io import StringIO
 except ImportError:
-    from StringIO import StringIO
+    from io import StringIO
 
 from twisted.python.util import unsignedID
 
@@ -46,7 +46,7 @@
         self(**kw)
 
     def __call__(self,**kw):
-        for key,val in kw.items():
+        for key,val in list(kw.items()):
             setattr(self,key,val)
         return self
 
@@ -77,12 +77,12 @@
         type.__init__(self, name, bases, d)
         accessors = {}
         prefixs = ["get_", "set_", "del_"]
-        for k in d.keys():
+        for k in list(d.keys()):
             v = getattr(self, k)
             for i in range(3):
                 if k.startswith(prefixs[i]):
                     accessors.setdefault(k[4:], [None, None, None])[i] = v
-        for name, (getter, setter, deler) in accessors.items():
+        for name, (getter, setter, deler) in list(accessors.items()):
             # create default behaviours for the property - if we leave
             # the getter as None we won't be able to getattr, etc..
             if getter is None:
@@ -108,7 +108,7 @@
             setattr(self, name, property(getter, setter, deler, ""))
 
 
-class PropertyAccessor(object):
+class PropertyAccessor(object, metaclass=AccessorType):
     """A mixin class for Python 2.2 that uses AccessorType.
 
     This provides compatability with the pre-2.2 Accessor mixin, up
@@ -131,12 +131,6 @@
     whereas in original Accessor the class attribute or instance attribute
     would override the getter method.
     """
-    # addendum to above:
-    # The behaviour of Accessor is wrong IMHO, and I've found bugs
-    # caused by it.
-    #  -- itamar
-
-    __metaclass__ = AccessorType
 
     def reallySet(self, k, v):
         self.__dict__[k] = v
@@ -259,11 +253,11 @@
         "[v2.5] Use inspect.getargspec instead of twisted.python.reflect.funcinfo",
         DeprecationWarning,
         stacklevel=2)
-    code=function.func_code
-    name=function.func_name
+    code=function.__code__
+    name=function.__name__
     argc=code.co_argcount
     argv=code.co_varnames[:argc]
-    defaults=function.func_defaults
+    defaults=function.__defaults__
 
     out = []
 
@@ -297,7 +291,7 @@
 
 
 def getcurrent(clazz):
-    assert type(clazz) == types.ClassType, 'must be a class...'
+    assert type(clazz) == type, 'must be a class...'
     module = namedModule(clazz.__module__)
     currclass = getattr(module, clazz.__name__, None)
     if currclass is None:
@@ -317,7 +311,7 @@
 
 # I should really have a better name for this...
 def isinst(inst,clazz):
-    if type(inst) != types.InstanceType or type(clazz)!= types.ClassType:
+    if type(inst) != types.InstanceType or type(clazz)!= type:
         return isinstance(inst,clazz)
     cl = inst.__class__
     cl2 = getcurrent(cl)
@@ -402,7 +396,7 @@
                 execName = excTraceback.tb_frame.f_globals["__name__"]
                 if (execName is None or # python 2.4+, post-cleanup
                     execName == importName): # python 2.3, no cleanup
-                    raise excType, excValue, excTraceback
+                    raise excType(excValue).with_traceback(excTraceback)
                 excTraceback = excTraceback.tb_next
             raise _NoModuleFound()
     except:
@@ -481,7 +475,7 @@
 
     This allows you to create macro-like behaviors in python.
     """
-    if not identifiers.has_key('name'):
+    if 'name' not in identifiers:
         identifiers['name'] = name
     source = source % identifiers
     codeplace = "<%s (macro)>" % filename
@@ -490,7 +484,7 @@
     # shield your eyes!
     sm = sys.modules
     tprm = "twisted.python.reflect.macros"
-    if not sm.has_key(tprm):
+    if tprm not in sm:
         macros = new.module(tprm)
         sm[tprm] = macros
         macros.count = 0
@@ -510,7 +504,7 @@
     # would be useful if you were foolishly trying to pickle a wrapped function
     # directly from a class that had been hooked.
 
-    exec code in dict, dict
+    exec(code, dict, dict)
     return dict[name]
 
 
@@ -598,7 +592,7 @@
     """
     dct = {}
     addMethodNamesToDict(classObj, dct, prefix)
-    return dct.keys()
+    return list(dct.keys())
 
 
 def addMethodNamesToDict(classObj, dict, prefix, baseClass=None):
@@ -616,7 +610,7 @@
         addMethodNamesToDict(base, dict, prefix, baseClass)
 
     if baseClass is None or baseClass in classObj.__bases__:
-        for name, method in classObj.__dict__.items():
+        for name, method in list(classObj.__dict__.items()):
             optName = name[len(prefix):]
             if ((type(method) is types.FunctionType)
                 and (name[:len(prefix)] == prefix)
@@ -629,7 +623,7 @@
     """
     dct = {}
     accumulateMethods(obj, dct, prefix)
-    return dct.values()
+    return list(dct.values())
 
 
 def accumulateMethods(obj, dict, prefix='', curClass=None):
@@ -643,7 +637,7 @@
     for base in curClass.__bases__:
         accumulateMethods(obj, dict, prefix, base)
 
-    for name, method in curClass.__dict__.items():
+    for name, method in list(curClass.__dict__.items()):
         optName = name[len(prefix):]
         if ((type(method) is types.FunctionType)
             and (name[:len(prefix)] == prefix)
@@ -737,34 +731,34 @@
             return
         maxDepth -= 1
     seen[id(start)] = start
-    if isinstance(start, types.DictionaryType):
+    if isinstance(start, dict):
         r = []
-        for k, v in start.items():
+        for k, v in list(start.items()):
             objgrep(k, goal, eq, path+'{'+repr(v)+'}', paths, seen, showUnknowns, maxDepth)
             objgrep(v, goal, eq, path+'['+repr(k)+']', paths, seen, showUnknowns, maxDepth)
     elif isinstance(start, (list, tuple, deque)):
-        for idx in xrange(len(start)):
+        for idx in range(len(start)):
             objgrep(start[idx], goal, eq, path+'['+str(idx)+']', paths, seen, showUnknowns, maxDepth)
     elif isinstance(start, types.MethodType):
-        objgrep(start.im_self, goal, eq, path+'.im_self', paths, seen, showUnknowns, maxDepth)
-        objgrep(start.im_func, goal, eq, path+'.im_func', paths, seen, showUnknowns, maxDepth)
-        objgrep(start.im_class, goal, eq, path+'.im_class', paths, seen, showUnknowns, maxDepth)
+        objgrep(start.__self__, goal, eq, path+'.im_self', paths, seen, showUnknowns, maxDepth)
+        objgrep(start.__func__, goal, eq, path+'.im_func', paths, seen, showUnknowns, maxDepth)
+        objgrep(start.__self__.__class__, goal, eq, path+'.im_class', paths, seen, showUnknowns, maxDepth)
     elif hasattr(start, '__dict__'):
-        for k, v in start.__dict__.items():
+        for k, v in list(start.__dict__.items()):
             objgrep(v, goal, eq, path+'.'+k, paths, seen, showUnknowns, maxDepth)
         if isinstance(start, types.InstanceType):
             objgrep(start.__class__, goal, eq, path+'.__class__', paths, seen, showUnknowns, maxDepth)
     elif isinstance(start, weakref.ReferenceType):
         objgrep(start(), goal, eq, path+'()', paths, seen, showUnknowns, maxDepth)
-    elif (isinstance(start, types.StringTypes+
-                    (types.IntType, types.FunctionType,
-                     types.BuiltinMethodType, RegexType, types.FloatType,
-                     types.NoneType, types.FileType)) or
+    elif (isinstance(start, str+
+                    (int, types.FunctionType,
+                     types.BuiltinMethodType, RegexType, float,
+                     type(None), types.FileType)) or
           type(start).__name__ in ('wrapper_descriptor', 'method_descriptor',
                                    'member_descriptor', 'getset_descriptor')):
         pass
     elif showUnknowns:
-        print 'unknown type', type(start), start
+        print('unknown type', type(start), start)
     return paths
 
 
@@ -807,7 +801,7 @@
         moduleName = obj.__module__
         return "%s.%s" % (moduleName, name)
     elif inspect.ismethod(obj):
-        className = fullyQualifiedName(obj.im_class)
+        className = fullyQualifiedName(obj.__self__.__class__)
         return "%s.%s" % (className, name)
     return name
 
--- twisted/python/release.py (original)
+++ twisted/python/release.py (refactored)
@@ -37,10 +37,10 @@
     ask before running it.  If the command returns something other
     than 0, I'll raise CommandFailed(command).
     """
-    print "--$", command
+    print("--$", command)
 
     if prompt:
-        if raw_input("run ?? ").startswith('n'):
+        if input("run ?? ").startswith('n'):
             return
     if null:
         command = "%s > /dev/null" % command
--- twisted/python/roots.py (original)
+++ twisted/python/roots.py (refactored)
@@ -141,7 +141,7 @@
 
         See getStaticEntity.
         """
-        return self.entities.items()
+        return list(self.entities.items())
 
     def listDynamicEntities(self, request):
         """A list of all name, entity that I can generate on demand.
@@ -162,7 +162,7 @@
 
         See getStaticEntity.
         """
-        return self.entities.keys()
+        return list(self.entities.keys())
 
 
     def listDynamicNames(self):
--- twisted/python/runtime.py (original)
+++ twisted/python/runtime.py (refactored)
@@ -12,9 +12,9 @@
 
 def shortPythonVersion():
     hv = sys.hexversion
-    major = (hv & 0xff000000L) >> 24
-    minor = (hv & 0x00ff0000L) >> 16
-    teeny = (hv & 0x0000ff00L) >> 8
+    major = (hv & 0xff000000) >> 24
+    minor = (hv & 0x00ff0000) >> 16
+    teeny = (hv & 0x0000ff00) >> 8
     return "%s.%s.%s" % (major,minor,teeny)
 
 knownPlatforms = {
@@ -56,11 +56,11 @@
     def isWinNT(self):
         """Are we running in Windows NT?"""
         if self.getType() == 'win32':
-            import _winreg
+            import winreg
             try:
-                k=_winreg.OpenKeyEx(_winreg.HKEY_LOCAL_MACHINE,
+                k=winreg.OpenKeyEx(winreg.HKEY_LOCAL_MACHINE,
                                     r'Software\Microsoft\Windows NT\CurrentVersion')
-                _winreg.QueryValueEx(k, 'SystemRoot')
+                winreg.QueryValueEx(k, 'SystemRoot')
                 return 1
             except WindowsError:
                 return 0
--- twisted/python/shortcut.py (original)
+++ twisted/python/shortcut.py (refactored)
@@ -46,11 +46,11 @@
             shell.CLSID_ShellLink, None,
             pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink
         )
-        data = map(None, 
+        data = list(map(None, 
                    ['"%s"' % os.path.abspath(path), arguments, description,
                     os.path.abspath(workingdir), os.path.abspath(iconpath)], 
                    ("SetPath", "SetArguments", "SetDescription",
-                   "SetWorkingDirectory") )
+                   "SetWorkingDirectory") ))
         for value, function in data:
             if value and function:
                 # call function on each non-null value
@@ -72,5 +72,5 @@
     def __getattr__( self, name ):
         if name != "_base":
             return getattr(self._base, name)
-        raise AttributeError, "%s instance has no attribute %s" % \
-                (self.__class__.__name__, name)
+        raise AttributeError("%s instance has no attribute %s" % \
+                (self.__class__.__name__, name))
--- twisted/python/syslog.py (original)
+++ twisted/python/syslog.py (refactored)
@@ -4,7 +4,7 @@
 #
 syslog = __import__('syslog')
 
-import log
+from . import log
 
 class SyslogObserver:
     def __init__(self, prefix):
@@ -13,9 +13,9 @@
     def emit(self, eventDict):
         edm = eventDict['message']
         if not edm:
-            if eventDict['isError'] and eventDict.has_key('failure'):
+            if eventDict['isError'] and 'failure' in eventDict:
                 text = eventDict['failure'].getTraceback()
-            elif eventDict.has_key('format'):
+            elif 'format' in eventDict:
                 text = eventDict['format'] % eventDict
             else:
                 # we don't know how to log this
--- twisted/python/text.py (original)
+++ twisted/python/text.py (refactored)
@@ -22,9 +22,9 @@
     braces = ''
     sl = []
 
-    if type(object) is types.DictType:
+    if type(object) is dict:
         braces = '{}'
-        for key, value in object.items():
+        for key, value in list(object.items()):
             value = stringyString(value, indentation + '   ')
             if isMultiline(value):
                 if endsInNewline(value):
@@ -35,8 +35,8 @@
                 sl.append("%s %s: %s" % (indentation, key,
                                          value[len(indentation) + 3:]))
 
-    elif type(object) in (types.TupleType, types.ListType):
-        if type(object) is types.TupleType:
+    elif type(object) in (tuple, list):
+        if type(object) is tuple:
             braces = '()'
         else:
             braces = '[]'
@@ -45,8 +45,8 @@
             element = stringyString(element, indentation + ' ')
             sl.append(string.rstrip(element) + ',')
     else:
-        sl[:] = map(lambda s, i=indentation: i+s,
-                    string.split(str(object),'\n'))
+        sl[:] = list(map(lambda s, i=indentation: i+s,
+                    string.split(str(object),'\n')))
 
     if not sl:
         sl.append(indentation)
@@ -87,7 +87,7 @@
     lines = string.split(docstring,'\n')
 
     leading = 0
-    for l in xrange(1,len(lines)):
+    for l in range(1,len(lines)):
         line = lines[l]
         if string.strip(line):
             while 1:
@@ -99,7 +99,7 @@
             break
 
     outlines = lines[0:1]
-    for l in xrange(1,len(lines)):
+    for l in range(1,len(lines)):
         outlines.append(lines[l][leading:])
 
     return string.join(outlines, '\n')
--- twisted/python/threadable.py (original)
+++ twisted/python/threadable.py (refactored)
@@ -108,7 +108,7 @@
     cb()
 
 try:
-    import thread as threadmodule
+    import _thread as threadmodule
     import threading as threadingmodule
 except ImportError:
     threadmodule = None
--- twisted/python/threadpool.py (original)
+++ twisted/python/threadpool.py (refactored)
@@ -11,7 +11,7 @@
 """
 
 # System Imports
-import Queue
+import queue
 import threading
 import copy
 import sys
@@ -53,7 +53,7 @@
         """
         assert minthreads >= 0, 'minimum is negative'
         assert minthreads <= maxthreads, 'minimum is greater than maximum'
-        self.q = Queue.Queue(0)
+        self.q = queue.Queue(0)
         self.min = minthreads
         self.max = maxthreads
         self.name = name
@@ -169,7 +169,7 @@
 
     def _runWithCallback(self, callback, errback, func, args, kwargs):
         try:
-            result = apply(func, args, kwargs)
+            result = func(*args, **kwargs)
         except:
             errback(sys.exc_info()[1])
         else:
--- twisted/python/timeoutqueue.py (original)
+++ twisted/python/timeoutqueue.py (refactored)
@@ -7,7 +7,7 @@
 """
 
 # System Imports
-import Queue, time, warnings
+import queue, time, warnings
 
 
 _time = time.time
@@ -18,7 +18,7 @@
     pass
 
 
-class TimeoutQueue(Queue.Queue):
+class TimeoutQueue(queue.Queue):
     """
     A thread-safe queue that supports timeouts.
     """
@@ -26,7 +26,7 @@
     def __init__(self, max=0):
         warnings.warn("timeoutqueue is deprecated since Twisted 8.0",
                       category=DeprecationWarning, stacklevel=2)
-        Queue.Queue.__init__(self, max)
+        queue.Queue.__init__(self, max)
 
     def wait(self, timeout):
         """
@@ -40,7 +40,7 @@
                 break
             remaining = endtime - _time()
             if remaining <= 0:
-                raise TimedOut, "timed out."
+                raise TimedOut("timed out.")
             delay = min(delay * 2, remaining, .05)
             _sleep(delay)
 
--- twisted/python/urlpath.py (original)
+++ twisted/python/urlpath.py (refactored)
@@ -4,8 +4,8 @@
 
 #
 
-import urlparse
-import urllib
+import urllib.parse
+import urllib.request, urllib.parse, urllib.error
 
 class URLPath:
     def __init__(self, scheme='', netloc='localhost', path='',
@@ -22,7 +22,7 @@
     def pathList(self, unquote=0, copy=1):
         if self._qpathlist is None:
             self._qpathlist = self.path.split('/')
-            self._uqpathlist = map(urllib.unquote, self._qpathlist)
+            self._uqpathlist = list(map(urllib.parse.unquote, self._qpathlist))
         if unquote:
             result = self._uqpathlist
         else:
@@ -33,7 +33,7 @@
             return result
 
     def fromString(klass, st):
-        t = urlparse.urlsplit(st)
+        t = urllib.parse.urlsplit(st)
         u = klass(*t)
         return u
 
@@ -88,7 +88,7 @@
         """Return a path which is the URL where a browser would presumably take
         you if you clicked on a link with an HREF as given.
         """
-        scheme, netloc, path, query, fragment = urlparse.urlsplit(st)
+        scheme, netloc, path, query, fragment = urllib.parse.urlsplit(st)
         if not scheme:
             scheme = self.scheme
         if not netloc:
@@ -111,7 +111,7 @@
 
     
     def __str__(self):
-        x = urlparse.urlunsplit((
+        x = urllib.parse.urlunsplit((
             self.scheme, self.netloc, self.path,
             self.query, self.fragment))
         return x
--- twisted/python/usage.py (original)
+++ twisted/python/usage.py (refactored)
@@ -52,7 +52,7 @@
                              % (parameterName,))
         try:
             value = self.coerce(value)
-        except ValueError, e:
+        except ValueError as e:
             raise UsageError("Parameter type enforcement failed: %s" % (e,))
 
         self.options.opts[parameterName] = value
@@ -171,18 +171,18 @@
         as dictionary keys.  This is an internal feature used to implement
         the parser.  Do not rely on it in application code.
         """
-        return int(id(self) % sys.maxint)
+        return int(id(self) % sys.maxsize)
 
     def opt_help(self):
         """
         Display this help and exit.
         """
-        print self.__str__()
+        print(self.__str__())
         sys.exit(0)
 
     def opt_version(self):
         from twisted import copyright
-        print "Twisted version:", copyright.version
+        print("Twisted version:", copyright.version)
         sys.exit(0)
 
     #opt_h = opt_help # this conflicted with existing 'host' options.
@@ -197,7 +197,7 @@
         try:
             opts, args = getopt.getopt(options,
                                        self.shortOpt, self.longOpt)
-        except getopt.error, e:
+        except getopt.error as e:
             raise UsageError(str(e))
 
         for opt, arg in opts:
@@ -283,18 +283,18 @@
         reflect.accumulateClassList(self.__class__, 'optFlags', flags)
 
         for flag in flags:
-            long, short, doc = util.padTo(3, flag)
-            if not long:
+            int, short, doc = util.padTo(3, flag)
+            if not int:
                 raise ValueError("A flag cannot be without a name.")
 
-            docs[long] = doc
-            settings[long] = 0
+            docs[int] = doc
+            settings[int] = 0
             if short:
                 shortOpt = shortOpt + short
-                synonyms[short] = long
-            longOpt.append(long)
-            synonyms[long] = long
-            dispatch[long] = self._generic_flag
+                synonyms[short] = int
+            longOpt.append(int)
+            synonyms[int] = int
+            dispatch[int] = self._generic_flag
 
         return longOpt, shortOpt, docs, settings, synonyms, dispatch
 
@@ -320,21 +320,21 @@
         synonyms = {}
 
         for parameter in parameters:
-            long, short, default, doc, paramType = util.padTo(5, parameter)
-            if not long:
+            int, short, default, doc, paramType = util.padTo(5, parameter)
+            if not int:
                 raise ValueError("A parameter cannot be without a name.")
 
-            docs[long] = doc
-            settings[long] = default
+            docs[int] = doc
+            settings[int] = default
             if short:
                 shortOpt = shortOpt + short + ':'
-                synonyms[short] = long
-            longOpt.append(long + '=')
-            synonyms[long] = long
+                synonyms[short] = int
+            longOpt.append(int + '=')
+            synonyms[int] = int
             if paramType is not None:
-                dispatch[long] = CoerceParameter(self, paramType)
-            else:
-                dispatch[long] = CoerceParameter(self, str)
+                dispatch[int] = CoerceParameter(self, paramType)
+            else:
+                dispatch[int] = CoerceParameter(self, str)
 
         return longOpt, shortOpt, docs, settings, synonyms, dispatch
 
@@ -350,7 +350,7 @@
         dct = {}
         reflect.addMethodNamesToDict(self.__class__, dct, "opt_")
 
-        for name in dct.keys():
+        for name in list(dct.keys()):
             method = getattr(self, 'opt_'+name)
 
             takesArg = not flagFunction(method, name)
@@ -389,7 +389,7 @@
 
         reverse_dct = {}
         # Map synonyms
-        for name in dct.keys():
+        for name in list(dct.keys()):
             method = getattr(self, 'opt_' + name)
             if method not in reverse_dct:
                 reverse_dct[method] = []
@@ -397,7 +397,7 @@
 
         cmpLength = lambda a, b: cmp(len(a), len(b))
 
-        for method, names in reverse_dct.items():
+        for method, names in list(reverse_dct.items()):
             if len(names) < 2:
                 continue
             names_ = names[:]
@@ -460,7 +460,7 @@
             commands = ''
 
         longToShort = {}
-        for key, value in self.synonyms.items():
+        for key, value in list(self.synonyms.items()):
             longname = value
             if (key != longname) and (len(key) == 1):
                 longToShort[longname] = key
@@ -562,20 +562,20 @@
             short = ''
 
         if opt.get('long', None):
-            long = opt['long']
+            int = opt['long']
             if opt.get("optType", None) == "parameter":
-                long = long + '='
-
-            long = "%-*s" % (maxOptLen, long)
+                int = int + '='
+
+            int = "%-*s" % (maxOptLen, int)
             if short:
                 comma = ","
         else:
-            long = " " * (maxOptLen + len('--'))
+            int = " " * (maxOptLen + len('--'))
 
         if opt.get('optType', None) == 'command':
-            column1 = '    %s      ' % long
-        else:
-            column1 = "  %2s%c --%s  " % (short, comma, long)
+            column1 = '    %s      ' % int
+        else:
+            column1 = "  %2s%c --%s  " % (short, comma, int)
 
         if opt.get('doc', ''):
             doc = opt['doc'].strip()
@@ -608,10 +608,10 @@
 
 
 def flagFunction(method, name=None):
-    reqArgs = method.im_func.func_code.co_argcount
+    reqArgs = method.__func__.__code__.co_argcount
     if reqArgs > 2:
         raise UsageError('Invalid Option function for %s' %
-                         (name or method.func_name))
+                         (name or method.__name__))
     if reqArgs == 2:
         # argName = method.im_func.func_code.co_varnames[1]
         return 0
--- twisted/python/util.py (original)
+++ twisted/python/util.py (refactored)
@@ -39,7 +39,7 @@
         del self.data[k]
 
     def _lowerOrReturn(self, key):
-        if isinstance(key, str) or isinstance(key, unicode):
+        if isinstance(key, str) or isinstance(key, str):
             return key.lower()
         else:
             return key
@@ -58,27 +58,27 @@
     def has_key(self, key):
         """Case insensitive test whether 'key' exists."""
         k = self._lowerOrReturn(key)
-        return self.data.has_key(k)
+        return k in self.data
     __contains__=has_key
 
     def _doPreserve(self, key):
         if not self.preserve and (isinstance(key, str)
-                                  or isinstance(key, unicode)):
+                                  or isinstance(key, str)):
             return key.lower()
         else:
             return key
 
     def keys(self):
         """List of keys in their original case."""
-        return list(self.iterkeys())
+        return list(self.keys())
 
     def values(self):
         """List of values."""
-        return list(self.itervalues())
+        return list(self.values())
 
     def items(self):
         """List of (key,value) pairs."""
-        return list(self.iteritems())
+        return list(self.items())
 
     def get(self, key, default=None):
         """Retrieve value associated with 'key' or return default value
@@ -91,39 +91,39 @@
     def setdefault(self, key, default):
         """If 'key' doesn't exists, associate it with the 'default' value.
         Return value associated with 'key'."""
-        if not self.has_key(key):
+        if key not in self:
             self[key] = default
         return self[key]
 
     def update(self, dict):
         """Copy (key,value) pairs from 'dict'."""
-        for k,v in dict.items():
+        for k,v in list(dict.items()):
             self[k] = v
 
     def __repr__(self):
         """String representation of the dictionary."""
-        items = ", ".join([("%r: %r" % (k,v)) for k,v in self.items()])
+        items = ", ".join([("%r: %r" % (k,v)) for k,v in list(self.items())])
         return "InsensitiveDict({%s})" % items
 
     def iterkeys(self):
-        for v in self.data.itervalues():
+        for v in self.data.values():
             yield self._doPreserve(v[0])
 
     def itervalues(self):
-        for v in self.data.itervalues():
+        for v in self.data.values():
             yield v[1]
 
     def iteritems(self):
-        for (k, v) in self.data.itervalues():
+        for (k, v) in self.data.values():
             yield self._doPreserve(k), v
 
     def popitem(self):
-        i=self.items()[0]
+        i=list(self.items())[0]
         del self[i[0]]
         return i
 
     def clear(self):
-        for k in self.keys():
+        for k in list(self.keys()):
             del self[k]
 
     def copy(self):
@@ -133,7 +133,7 @@
         return len(self.data)
 
     def __eq__(self, other):
-        for k,v in self.items():
+        for k,v in list(self.items()):
             if not (k in other) or not (other[k]==v):
                 return 0
         return len(self)==len(other)
@@ -152,10 +152,10 @@
         if len(kwargs):
             self.update(kwargs)
     def __repr__(self):
-        return '{'+', '.join([('%r: %r' % item) for item in self.items()])+'}'
+        return '{'+', '.join([('%r: %r' % item) for item in list(self.items())])+'}'
 
     def __setitem__(self, key, value):
-        if not self.has_key(key):
+        if key not in self:
             self._order.append(key)
         UserDict.__setitem__(self, key, value)
 
@@ -171,14 +171,14 @@
             yield (item, self[item])
 
     def items(self):
-        return list(self.iteritems())
+        return list(self.items())
 
     def itervalues(self):
         for item in self._order:
             yield self[item]
 
     def values(self):
-        return list(self.itervalues())
+        return list(self.values())
 
     def iterkeys(self):
         return iter(self._order)
@@ -193,13 +193,13 @@
         return (key, value)
 
     def setdefault(self, item, default):
-        if self.has_key(item):
+        if item in self:
             return self[item]
         self[item] = default
         return default
 
     def update(self, d):
-        for k, v in d.items():
+        for k, v in list(d.items()):
             self[k] = v
 
 def uniquify(lst):
@@ -209,7 +209,7 @@
     dct = {}
     result = []
     for k in lst:
-        if not dct.has_key(k): result.append(k)
+        if k not in dct: result.append(k)
         dct[k] = 1
     return result
 
@@ -226,7 +226,7 @@
     """
 
     if len(seq) > n:
-        raise ValueError, "%d elements is more than %d." % (len(seq), n)
+        raise ValueError("%d elements is more than %d." % (len(seq), n))
 
     blank = [default] * n
 
@@ -240,7 +240,7 @@
                             os.path.abspath(twisted.__file__))), 'plugins')
     userPlugins = os.path.expanduser("~/TwistedPlugins")
     confPlugins = os.path.expanduser("~/.twisted")
-    allPlugins = filter(os.path.isdir, [systemPlugins, userPlugins, confPlugins])
+    allPlugins = list(filter(os.path.isdir, [systemPlugins, userPlugins, confPlugins]))
     return allPlugins
 
 def addPluginDir():
@@ -261,7 +261,7 @@
     import getpass
     try:
         return getpass.getpass(prompt)
-    except IOError, e:
+    except IOError as e:
         if e.errno == errno.EINTR:
             raise KeyboardInterrupt
         raise
@@ -317,9 +317,9 @@
 
 
 def dict(*a, **k):
-    import __builtin__
+    import builtins
     warnings.warn('twisted.python.util.dict is deprecated.  Use __builtin__.dict instead')
-    return __builtin__.dict(*a, **k)
+    return builtins.dict(*a, **k)
 
 def println(*a):
     sys.stdout.write(' '.join(map(str, a))+'\n')
@@ -369,20 +369,20 @@
 def spewer(frame, s, ignored):
     """A trace function for sys.settrace that prints every function or method call."""
     from twisted.python import reflect
-    if frame.f_locals.has_key('self'):
+    if 'self' in frame.f_locals:
         se = frame.f_locals['self']
         if hasattr(se, '__class__'):
             k = reflect.qual(se.__class__)
         else:
             k = reflect.qual(type(se))
-        print 'method %s of %s at %s' % (
+        print('method %s of %s at %s' % (
             frame.f_code.co_name, k, id(se)
-        )
+        ))
     else:
-        print 'function %s in %s, line %s' % (
+        print('function %s in %s, line %s' % (
             frame.f_code.co_name,
             frame.f_code.co_filename,
-            frame.f_lineno)
+            frame.f_lineno))
 
 def searchupwards(start, files=[], dirs=[]):
     """Walk upwards from start, looking for a directory containing
@@ -436,7 +436,7 @@
             self.log.append(line)
 
     def str(self):
-        return '\n'.join(filter(None,self.log))
+        return '\n'.join([_f for _f in self.log if _f])
 
     def __getitem__(self, item):
         return filter(None,self.log)[item]
@@ -490,11 +490,11 @@
 class _IntervalDifferentialIterator:
     def __init__(self, i, d):
 
-        self.intervals = [[e, e, n] for (e, n) in zip(i, range(len(i)))]
+        self.intervals = [[e, e, n] for (e, n) in zip(i, list(range(len(i))))]
         self.default = d
         self.last = 0
 
-    def next(self):
+    def __next__(self):
         if not self.intervals:
             return (self.default, None)
         last, index = self.intervals[0][0], self.intervals[0][2]
@@ -521,7 +521,7 @@
                     if i[2] > index:
                         i[2] -= 1
                 return
-        raise ValueError, "Specified interval not in IntervalDifferential"
+        raise ValueError("Specified interval not in IntervalDifferential")
 
 
 class FancyStrMixin:
@@ -564,7 +564,7 @@
 
 
 def dsu(list, key):
-    L2 = [(key(e), i, e) for (i, e) in zip(range(len(list)), list)]
+    L2 = [(key(e), i, e) for (i, e) in zip(list(range(len(list))), list)]
     L2.sort()
     return [e[2] for e in L2]
 
@@ -591,7 +591,7 @@
                     del l[-1]
                 else:
                     raise
-            except OSError, e:
+            except OSError as e:
                 if e.errno == errno.EINVAL and len(l) > 1:
                     # This comes from the OS saying too many groups
                     del l[-1]
@@ -638,7 +638,7 @@
                     break # No more groups, ignore any more
         try:
             _setgroups_until_success(l)
-        except OSError, e:
+        except OSError as e:
             # We might be able to remove this code now that we
             # don't try to setgid/setuid even when not asked to.
             if e.errno == errno.EPERM:
@@ -669,14 +669,14 @@
     __csio = None
 
     def __init__(self, *a, **kw):
-        from cStringIO import StringIO
+        from io import StringIO
         self.__csio = StringIO(*a, **kw)
 
     def __iter__(self):
         return self.__csio.__iter__()
 
-    def next(self):
-        return self.__csio.next()
+    def __next__(self):
+        return next(self.__csio)
 
     def close(self):
         return self.__csio.close()
@@ -740,7 +740,7 @@
                           % (projectName, origModuleName, projectURL))
 
     # Populate the old module with the new module's contents
-    for k,v in vars(newModule).items():
+    for k,v in list(vars(newModule).items()):
         globDict[k] = v
     globDict['__doc__'] = modoc
     import warnings
@@ -754,7 +754,7 @@
     while True:
         try:
             return f(*a, **kw)
-        except (IOError, OSError), e:
+        except (IOError, OSError) as e:
             if e.args[0] == errno.EINTR:
                 continue
             raise
@@ -762,7 +762,7 @@
 # A value about twice as large as any Python int, to which negative values
 # from id() will be added, moving them into a range which should begin just
 # above where positive values from id() leave off.
-_HUGEINT = (sys.maxint + 1L) * 2L
+_HUGEINT = (sys.maxsize + 1) * 2
 def unsignedID(obj):
     """
     Return the id of an object as an unsigned number so that its hex
@@ -790,9 +790,9 @@
     except TypeError:
         try:
             merged = new.function(
-                g.func_code, g.func_globals,
+                g.__code__, g.__globals__,
                 f.__name__, inspect.getargspec(g)[-1],
-                g.func_closure)
+                g.__closure__)
         except TypeError:
             pass
     else:
--- twisted/python/zippath.py (original)
+++ twisted/python/zippath.py (refactored)
@@ -84,7 +84,7 @@
     def listdir(self):
         if self.exists():
             if self.isdir():
-                return self.archive.childmap[self.pathInArchive].keys()
+                return list(self.archive.childmap[self.pathInArchive].keys())
             else:
                 raise OSError(errno.ENOTDIR, "Leaf zip entry listed")
         else:
--- twisted/python/zipstream.py (original)
+++ twisted/python/zipstream.py (refactored)
@@ -122,7 +122,7 @@
         return bytes
 
 
-    def next(self):
+    def __next__(self):
         """
         Implement next as file does (like readline, except raises StopIteration
         at EOF)
--- twisted/python/zshcomp.py (original)
+++ twisted/python/zshcomp.py (refactored)
@@ -134,7 +134,7 @@
 
 Have fun!
 """
-import itertools, sys, commands, os.path
+import itertools, sys, subprocess, os.path
 
 from twisted.python import reflect, util, usage
 from twisted.scripts.mktap import IServiceMaker
@@ -153,12 +153,12 @@
                       "Output files to this directory"]]
     def postOptions(self):
         if self['install'] and self['directory']:
-            raise usage.UsageError, "Can't have --install and " \
-                                    "--directory at the same time"
+            raise usage.UsageError("Can't have --install and " \
+                                    "--directory at the same time")
         if not self['install'] and not self['directory']:
-            raise usage.UsageError, "Not enough arguments"
+            raise usage.UsageError("Not enough arguments")
         if self['directory'] and not os.path.isdir(self['directory']):
-            raise usage.UsageError, "%s is not a directory" % self['directory']
+            raise usage.UsageError("%s is not a directory" % self['directory'])
 
 class Builder:
     def __init__(self, cmd_name, options, file):
@@ -349,10 +349,10 @@
         Write out zsh code for each option in this command
         @return: C{None}
         """
-        optNames = self.optAll_d.keys()
+        optNames = list(self.optAll_d.keys())
         optNames.sort()
-        for long in optNames:
-            self.writeOpt(long)
+        for int in optNames:
+            self.writeOpt(int)
 
     def writeExtras(self):
         """
@@ -379,9 +379,9 @@
                            zsh_* variables
         """
         def err(name):
-            raise ValueError, "Unknown option name \"%s\" found while\n" \
+            raise ValueError("Unknown option name \"%s\" found while\n" \
                 "examining zsh_ attributes for the %s command" % (
-                    name, self.cmd_name)
+                    name, self.cmd_name))
 
         for name in itertools.chain(self.altArgDescr, self.actionDescr,
         self.actions, self.multiUse):
@@ -393,7 +393,7 @@
                 if name not in self.optAll_d:
                     err(name)
 
-    def excludeStr(self, long, buildShort=False):
+    def excludeStr(self, int, buildShort=False):
         """
         Generate an "exclusion string" for the given option
 
@@ -408,21 +408,21 @@
 
         @return: The generated C{str}
         """
-        if long in self.excludes:
-            exclusions = self.excludes[long][:]
+        if int in self.excludes:
+            exclusions = self.excludes[int][:]
         else:
             exclusions = []
 
         # if long isn't a multiUse option (can't appear on the cmd line more
         # than once), then we have to exclude the short option if we're
         # building for the long option, and vice versa.
-        if long not in self.multiUse:
+        if int not in self.multiUse:
             if buildShort is False:
-                short = self.getShortOption(long)
+                short = self.getShortOption(int)
                 if short is not None:
                     exclusions.append(short)
             else:
-                exclusions.append(long)
+                exclusions.append(int)
 
         if not exclusions:
             return ''
@@ -454,7 +454,7 @@
 
         excludes = {}
         for lst in self.mutuallyExclusive:
-            for i, long in enumerate(lst):
+            for i, int in enumerate(lst):
                 tmp = []
                 tmp.extend(lst[:i])
                 tmp.extend(lst[i+1:])
@@ -462,13 +462,13 @@
                     if name in longToShort:
                         tmp.append(longToShort[name])
 
-                if long in excludes:
-                    excludes[long].extend(tmp)
+                if int in excludes:
+                    excludes[int].extend(tmp)
                 else:
-                    excludes[long] = tmp
+                    excludes[int] = tmp
         return excludes
 
-    def writeOpt(self, long):
+    def writeOpt(self, int):
         """
         Write out the zsh code for the given argument. This is just part of the
         one big call to _arguments
@@ -479,39 +479,39 @@
 
         @return: C{None}
         """
-        if long in self.optFlags_d:
+        if int in self.optFlags_d:
             # It's a flag option. Not one that takes a parameter.
-            long_field = "--%s" % long
+            long_field = "--%s" % int
         else:
-            long_field = "--%s=" % long
-
-        short = self.getShortOption(long)
+            long_field = "--%s=" % int
+
+        short = self.getShortOption(int)
         if short != None:
             short_field = "-" + short
         else:
             short_field = ''
 
-        descr = self.getDescription(long)
+        descr = self.getDescription(int)
         descr_field = descr.replace("[", "\[")
         descr_field = descr_field.replace("]", "\]")
         descr_field = '[%s]' % descr_field
 
-        if long in self.actionDescr:
-            actionDescr_field = self.actionDescr[long]
+        if int in self.actionDescr:
+            actionDescr_field = self.actionDescr[int]
         else:
             actionDescr_field = descr
 
-        action_field = self.getAction(long)
-        if long in self.multiUse:
+        action_field = self.getAction(int)
+        if int in self.multiUse:
             multi_field = '*'
         else:
             multi_field = ''
 
-        longExclusions_field = self.excludeStr(long)
+        longExclusions_field = self.excludeStr(int)
 
         if short:
             #we have to write an extra line for the short option if we have one
-            shortExclusions_field = self.excludeStr(long, buildShort=True)
+            shortExclusions_field = self.excludeStr(int, buildShort=True)
             self.file.write(escape('%s%s%s%s%s' % (shortExclusions_field,
                 multi_field, short_field, descr_field, action_field)))
             self.file.write(' \\\n')
@@ -520,46 +520,46 @@
             multi_field, long_field, descr_field, action_field)))
         self.file.write(' \\\n')
 
-    def getAction(self, long):
+    def getAction(self, int):
         """
         Return a zsh "action" string for the given argument
         @return: C{str}
         """
-        if long in self.actions:
-            if callable(self.actions[long]):
-                action = self.actions[long]()
+        if int in self.actions:
+            if hasattr(self.actions[int], '__call__'):
+                action = self.actions[int]()
             else:
-                action = self.actions[long]
-            return ":%s:%s" % (self.getActionDescr(long), action)
-        if long in self.optParams_d:
-            return ':%s:_files' % self.getActionDescr(long)
+                action = self.actions[int]
+            return ":%s:%s" % (self.getActionDescr(int), action)
+        if int in self.optParams_d:
+            return ':%s:_files' % self.getActionDescr(int)
         return ''
 
-    def getActionDescr(self, long):
+    def getActionDescr(self, int):
         """
         Return the description to be used when this argument is completed
         @return: C{str}
         """
-        if long in self.actionDescr:
-            return self.actionDescr[long]
+        if int in self.actionDescr:
+            return self.actionDescr[int]
         else:
-            return long
-
-    def getDescription(self, long):
+            return int
+
+    def getDescription(self, int):
         """
         Return the description to be used for this argument
         @return: C{str}
         """
         #check if we have an alternate descr for this arg, and if so use it
-        if long in self.altArgDescr:
-            return self.altArgDescr[long]
+        if int in self.altArgDescr:
+            return self.altArgDescr[int]
 
         #otherwise we have to get it from the optFlags or optParams
         try:
-            descr = self.optFlags_d[long][1]
+            descr = self.optFlags_d[int][1]
         except KeyError:
             try:
-                descr = self.optParams_d[long][2]
+                descr = self.optParams_d[int][2]
             except KeyError:
                 descr = None
 
@@ -567,21 +567,21 @@
             return descr
 
         # lets try to get it from the opt_foo method doc string if there is one
-        longMangled = long.replace('-', '_') # this is what t.p.usage does
+        longMangled = int.replace('-', '_') # this is what t.p.usage does
         obj = getattr(self.options, 'opt_%s' % longMangled, None)
         if obj:
             descr = descrFromDoc(obj)
             if descr is not None:
                 return descr
 
-        return long # we really ought to have a good description to use
-
-    def getShortOption(self, long):
+        return int # we really ought to have a good description to use
+
+    def getShortOption(self, int):
         """
         Return the short option letter or None
         @return: C{str} or C{None}
         """
-        optList = self.optAll_d[long]
+        optList = self.optAll_d[int]
         try:
             return optList[0] or None
         except IndexError:
@@ -601,31 +601,31 @@
                 methodToShort[methodsDict[name]] = name
                 del methodsDict[name]
 
-        for methodName, methodObj in methodsDict.items():
-            long = methodName.replace('_', '-') # t.p.usage does this
+        for methodName, methodObj in list(methodsDict.items()):
+            int = methodName.replace('_', '-') # t.p.usage does this
             # if this option is already defined by the optFlags or
             # optParameters then we don't want to override that data
-            if long in self.optAll_d:
+            if int in self.optAll_d:
                 continue
 
-            descr = self.getDescription(long)
+            descr = self.getDescription(int)
 
             short = None
             if methodObj in methodToShort:
                 short = methodToShort[methodObj]
 
-            reqArgs = methodObj.im_func.func_code.co_argcount
+            reqArgs = methodObj.__func__.__code__.co_argcount
             if reqArgs == 2:
-                self.optParams.append([long, short, None, descr])
-                self.optParams_d[long] = [short, None, descr]
-                self.optAll_d[long] = [short, None, descr]
+                self.optParams.append([int, short, None, descr])
+                self.optParams_d[int] = [short, None, descr]
+                self.optAll_d[int] = [short, None, descr]
             elif reqArgs == 1:
-                self.optFlags.append([long, short, descr])
-                self.optFlags_d[long] = [short, descr]
-                self.optAll_d[long] = [short, None, descr]
+                self.optFlags.append([int, short, descr])
+                self.optFlags_d[int] = [short, descr]
+                self.optAll_d[int] = [short, None, descr]
             else:
-                raise TypeError, '%r has wrong number ' \
-                                 'of arguments' % (methodObj,)
+                raise TypeError('%r has wrong number ' \
+                                 'of arguments' % (methodObj,))
 
 def descrFromDoc(obj):
     """
@@ -660,7 +660,7 @@
     """
     Shell escape the given string
     """
-    return commands.mkarg(str)[1:]
+    return subprocess.mkarg(str)[1:]
 
 def siteFunctionsPath():
     """
@@ -669,7 +669,7 @@
     """
     try:
         cmd = "zsh -f -c 'echo ${(M)fpath:#/*/site-functions}'"
-        output = commands.getoutput(cmd)
+        output = subprocess.getoutput(cmd)
         if os.path.isdir(output):
             return output
     except:
@@ -745,7 +745,7 @@
             else:
                 b = Builder(cmd_name, o, f)
                 b.write()
-        except Exception, e:
+        except Exception as e:
             skips.append( (cmd_name, e) )
             continue
     return skips
@@ -757,9 +757,9 @@
     options = MyOptions()
     try:
         options.parseOptions(sys.argv[1:])
-    except usage.UsageError, e:
-        print e
-        print options.getUsage()
+    except usage.UsageError as e:
+        print(e)
+        print(options.getUsage())
         sys.exit(2)
 
     if options['install']:
--- twisted/python/test/test_release.py (original)
+++ twisted/python/test/test_release.py (refactored)
@@ -8,7 +8,7 @@
 import warnings
 import operator
 import os, sys, signal
-from StringIO import StringIO
+from io import StringIO
 import tarfile
 
 try:
@@ -438,7 +438,7 @@
         replaceProjectVersion("test_project",
                               Version("twisted.test_project", 0, 82, 7))
         ns = {'__name___': 'twisted.test_project'}
-        execfile("test_project", ns)
+        exec(open("test_project").read(), ns)
         self.assertEquals(ns["version"].base(), "0.82.7")
 
 
@@ -451,7 +451,7 @@
                               Version("twisted.test_project", 0, 82, 7,
                                       prerelease=8))
         ns = {'__name___': 'twisted.test_project'}
-        execfile("test_project", ns)
+        exec(open("test_project").read(), ns)
         self.assertEquals(ns["version"].base(), "0.82.7pre8")
 
 
@@ -1060,7 +1060,7 @@
 
 
     def _setupTeXFiles(self):
-        sections = range(3)
+        sections = list(range(3))
         self._setupTeXSections(sections)
         return self._setupTeXBook(sections)
 
@@ -1210,7 +1210,7 @@
         L{BookBuilder.build} generates a pdf book file from some lore input
         files.
         """
-        sections = range(1, 4)
+        sections = list(range(1, 4))
         for sectionNumber in sections:
             self.howtoDir.child("%d.xhtml" % (sectionNumber,)).setContent(
                 self.getArbitraryLoreInput(sectionNumber))
@@ -1227,7 +1227,7 @@
         """
         L{BookBuilder.build} removes the intermediate LaTeX files it creates.
         """
-        sections = range(1, 4)
+        sections = list(range(1, 4))
         for sectionNumber in sections:
             self.howtoDir.child("%d.xhtml" % (sectionNumber,)).setContent(
                 self.getArbitraryLoreInput(sectionNumber))
--- twisted/python/test/test_util.py (original)
+++ twisted/python/test/test_util.py (refactored)
@@ -37,7 +37,7 @@
         except ZeroDivisionError:
             pass
         else:
-            raise unittest.FailTest, "util.raises didn't raise when it should have"
+            raise unittest.FailTest("util.raises didn't raise when it should have")
 
     def testUninterruptably(self):
         def f(a, b):
@@ -62,7 +62,7 @@
         try:
             for i in range(1, 100):
                 self.assertEquals(util.unsignedID(i), i)
-            top = (sys.maxint + 1L) * 2L
+            top = (sys.maxsize + 1) * 2
             for i in range(-100, -1):
                 self.assertEquals(util.unsignedID(i), top + i)
         finally:
@@ -143,7 +143,8 @@
         def foo():
             return foo_object
 
-        def bar(x, y, (a, b), c=10, *d, **e):
+        def bar(x, y, xxx_todo_changeme, c=10, *d, **e):
+            (a, b) = xxx_todo_changeme
             return bar_object
 
         baz = util.mergeFunctionMetadata(foo, bar)
@@ -231,12 +232,12 @@
         d[3] = 12
         d[1234] = 4321
         self.assertEquals(repr(d), "{'a': 'b', 'b': 'a', 3: 12, 1234: 4321}")
-        self.assertEquals(d.values(), ['b', 'a', 12, 4321])
+        self.assertEquals(list(d.values()), ['b', 'a', 12, 4321])
         del d[3]
         self.assertEquals(repr(d), "{'a': 'b', 'b': 'a', 1234: 4321}")
         self.assertEquals(d, {'a': 'b', 'b': 'a', 1234:4321})
-        self.assertEquals(d.keys(), ['a', 'b', 1234])
-        self.assertEquals(list(d.iteritems()),
+        self.assertEquals(list(d.keys()), ['a', 'b', 1234])
+        self.assertEquals(list(d.items()),
                           [('a', 'b'), ('b','a'), (1234, 4321)])
         item = d.popitem()
         self.assertEquals(item, (1234, 4321))
@@ -261,8 +262,8 @@
         self.assertEquals(eval(repr(dct)), dct)
         keys=['Foo', 'fnz', 1]
         for x in keys:
-            assert x in dct.keys()
-            assert (x, dct[x]) in dct.items()
+            assert x in list(dct.keys())
+            assert (x, dct[x]) in list(dct.items())
         self.assertEquals(len(keys), len(dct))
         del dct[1]
         del dct['foo']
@@ -272,8 +273,8 @@
         dct=InsensitiveDict({'Foo':'bar', 1:2, 'fnz':{1:2}}, preserve=0)
         keys=['foo', 'fnz', 1]
         for x in keys:
-            assert x in dct.keys()
-            assert (x, dct[x]) in dct.items()
+            assert x in list(dct.keys())
+            assert (x, dct[x]) in list(dct.items())
         self.assertEquals(len(keys), len(dct))
         del dct[1]
         del dct['foo']
@@ -321,7 +322,8 @@
               'sys.stdout.flush()\n')],
             env={'PYTHONPATH': os.pathsep.join(sys.path)})
 
-        def processFinished((reason, output)):
+        def processFinished(xxx_todo_changeme1):
+            (reason, output) = xxx_todo_changeme1
             reason.trap(ProcessDone)
             self.assertIn((1, 'secret'), output)
 
@@ -359,82 +361,82 @@
     def testDSU(self):
         L = [Foo(x) for x in range(20, 9, -1)]
         L2 = util.dsu(L, lambda o: o.x)
-        self.assertEquals(range(10, 21), [o.x for o in L2])
+        self.assertEquals(list(range(10, 21)), [o.x for o in L2])
 
 class IntervalDifferentialTestCase(unittest.TestCase):
     def testDefault(self):
         d = iter(util.IntervalDifferential([], 10))
         for i in range(100):
-            self.assertEquals(d.next(), (10, None))
+            self.assertEquals(next(d), (10, None))
 
     def testSingle(self):
         d = iter(util.IntervalDifferential([5], 10))
         for i in range(100):
-            self.assertEquals(d.next(), (5, 0))
+            self.assertEquals(next(d), (5, 0))
 
     def testPair(self):
         d = iter(util.IntervalDifferential([5, 7], 10))
         for i in range(100):
-            self.assertEquals(d.next(), (5, 0))
-            self.assertEquals(d.next(), (2, 1))
-            self.assertEquals(d.next(), (3, 0))
-            self.assertEquals(d.next(), (4, 1))
-            self.assertEquals(d.next(), (1, 0))
-            self.assertEquals(d.next(), (5, 0))
-            self.assertEquals(d.next(), (1, 1))
-            self.assertEquals(d.next(), (4, 0))
-            self.assertEquals(d.next(), (3, 1))
-            self.assertEquals(d.next(), (2, 0))
-            self.assertEquals(d.next(), (5, 0))
-            self.assertEquals(d.next(), (0, 1))
+            self.assertEquals(next(d), (5, 0))
+            self.assertEquals(next(d), (2, 1))
+            self.assertEquals(next(d), (3, 0))
+            self.assertEquals(next(d), (4, 1))
+            self.assertEquals(next(d), (1, 0))
+            self.assertEquals(next(d), (5, 0))
+            self.assertEquals(next(d), (1, 1))
+            self.assertEquals(next(d), (4, 0))
+            self.assertEquals(next(d), (3, 1))
+            self.assertEquals(next(d), (2, 0))
+            self.assertEquals(next(d), (5, 0))
+            self.assertEquals(next(d), (0, 1))
 
     def testTriple(self):
         d = iter(util.IntervalDifferential([2, 4, 5], 10))
         for i in range(100):
-            self.assertEquals(d.next(), (2, 0))
-            self.assertEquals(d.next(), (2, 0))
-            self.assertEquals(d.next(), (0, 1))
-            self.assertEquals(d.next(), (1, 2))
-            self.assertEquals(d.next(), (1, 0))
-            self.assertEquals(d.next(), (2, 0))
-            self.assertEquals(d.next(), (0, 1))
-            self.assertEquals(d.next(), (2, 0))
-            self.assertEquals(d.next(), (0, 2))
-            self.assertEquals(d.next(), (2, 0))
-            self.assertEquals(d.next(), (0, 1))
-            self.assertEquals(d.next(), (2, 0))
-            self.assertEquals(d.next(), (1, 2))
-            self.assertEquals(d.next(), (1, 0))
-            self.assertEquals(d.next(), (0, 1))
-            self.assertEquals(d.next(), (2, 0))
-            self.assertEquals(d.next(), (2, 0))
-            self.assertEquals(d.next(), (0, 1))
-            self.assertEquals(d.next(), (0, 2))
+            self.assertEquals(next(d), (2, 0))
+            self.assertEquals(next(d), (2, 0))
+            self.assertEquals(next(d), (0, 1))
+            self.assertEquals(next(d), (1, 2))
+            self.assertEquals(next(d), (1, 0))
+            self.assertEquals(next(d), (2, 0))
+            self.assertEquals(next(d), (0, 1))
+            self.assertEquals(next(d), (2, 0))
+            self.assertEquals(next(d), (0, 2))
+            self.assertEquals(next(d), (2, 0))
+            self.assertEquals(next(d), (0, 1))
+            self.assertEquals(next(d), (2, 0))
+            self.assertEquals(next(d), (1, 2))
+            self.assertEquals(next(d), (1, 0))
+            self.assertEquals(next(d), (0, 1))
+            self.assertEquals(next(d), (2, 0))
+            self.assertEquals(next(d), (2, 0))
+            self.assertEquals(next(d), (0, 1))
+            self.assertEquals(next(d), (0, 2))
 
     def testInsert(self):
         d = iter(util.IntervalDifferential([], 10))
-        self.assertEquals(d.next(), (10, None))
+        self.assertEquals(next(d), (10, None))
         d.addInterval(3)
-        self.assertEquals(d.next(), (3, 0))
-        self.assertEquals(d.next(), (3, 0))
+        self.assertEquals(next(d), (3, 0))
+        self.assertEquals(next(d), (3, 0))
         d.addInterval(6)
-        self.assertEquals(d.next(), (3, 0))
-        self.assertEquals(d.next(), (3, 0))
-        self.assertEquals(d.next(), (0, 1))
-        self.assertEquals(d.next(), (3, 0))
-        self.assertEquals(d.next(), (3, 0))
-        self.assertEquals(d.next(), (0, 1))
+        self.assertEquals(next(d), (3, 0))
+        self.assertEquals(next(d), (3, 0))
+        self.assertEquals(next(d), (0, 1))
+        self.assertEquals(next(d), (3, 0))
+        self.assertEquals(next(d), (3, 0))
+        self.assertEquals(next(d), (0, 1))
 
     def testRemove(self):
         d = iter(util.IntervalDifferential([3, 5], 10))
-        self.assertEquals(d.next(), (3, 0))
-        self.assertEquals(d.next(), (2, 1))
-        self.assertEquals(d.next(), (1, 0))
+        self.assertEquals(next(d), (3, 0))
+        self.assertEquals(next(d), (2, 1))
+        self.assertEquals(next(d), (1, 0))
         d.removeInterval(3)
-        self.assertEquals(d.next(), (4, 0))
-        self.assertEquals(d.next(), (5, 0))
+        self.assertEquals(next(d), (4, 0))
+        self.assertEquals(next(d), (5, 0))
         d.removeInterval(5)
-        self.assertEquals(d.next(), (10, None))
+        self.assertEquals(next(d), (10, None))
         self.assertRaises(ValueError, d.removeInterval, 10)
 
 
--- twisted/python/test/test_versions.py (original)
+++ twisted/python/test/test_versions.py (refactored)
@@ -2,7 +2,7 @@
 # See LICENSE for details.
 
 import sys
-from cStringIO import StringIO
+from io import StringIO
 
 from twisted.python.versions import getVersionString, IncomparableVersions
 from twisted.python.versions import Version, _inf
--- twisted/python/test/test_zipstream.py (original)
+++ twisted/python/test/test_zipstream.py (refactored)
@@ -62,9 +62,9 @@
         Zip file entries should implement the iterator protocol as files do.
         """
         fileEntry = self.getFileEntry('ho\nhoho')
-        self.assertEquals(fileEntry.next(), 'ho\n')
-        self.assertEquals(fileEntry.next(), 'hoho')
-        self.assertRaises(StopIteration, fileEntry.next)
+        self.assertEquals(next(fileEntry), 'ho\n')
+        self.assertEquals(next(fileEntry), 'hoho')
+        self.assertRaises(StopIteration, fileEntry.__next__)
 
 
     def test_readlines(self):
@@ -81,7 +81,7 @@
         """
         fileEntry = self.getFileEntry('')
         self.assertIdentical(iter(fileEntry), fileEntry)
-        self.assertIdentical(fileEntry.xreadlines(), fileEntry)
+        self.assertIdentical(fileEntry, fileEntry)
 
 
     def test_readWhole(self):
@@ -294,7 +294,7 @@
         uziter = zipstream.unzipIter(zpfilename, self.unzipdir.path)
         for i in range(numfiles):
             self.assertEquals(len(list(self.unzipdir.children())), i)
-            self.assertEquals(uziter.next(), numfiles - i - 1)
+            self.assertEquals(next(uziter), numfiles - i - 1)
         self.assertEquals(len(list(self.unzipdir.children())), numfiles)
 
         for child in self.unzipdir.children():
@@ -330,11 +330,11 @@
 
         testfile.setContent('NOT OVERWRITTEN')
         uziter = zipstream.unzipIter(zpfilename, self.unzipdir.path)
-        uziter.next()
+        next(uziter)
         self.assertEquals(testfile.open().read(), 'NOT OVERWRITTEN')
         uziter = zipstream.unzipIter(zpfilename, self.unzipdir.path,
                                      overwrite=True)
-        uziter.next()
+        next(uziter)
         self.assertEquals(testfile.open().read(), 'OVERWRITTEN')
 
 
@@ -346,7 +346,7 @@
         """
         unzipIterChunky should unzip the given number of bytes per iteration.
         """
-        junk = ' '.join([str(random.random()) for n in xrange(1000)])
+        junk = ' '.join([str(random.random()) for n in range(1000)])
         junkmd5 = md5(junk).hexdigest()
 
         tempdir = filepath.FilePath(self.mktemp())
@@ -355,7 +355,7 @@
         self._makebigfile(zfpath, compression, junk)
         uziter = zipstream.unzipIterChunky(zfpath, tempdir.path,
                                            chunksize=chunksize)
-        r = uziter.next()
+        r = next(uziter)
         # test that the number of chunks is in the right ballpark;
         # this could theoretically be any number but statistically it
         # should always be in this range
--- twisted/runner/inetd.py (original)
+++ twisted/runner/inetd.py (refactored)
@@ -41,7 +41,7 @@
         # FIXME: maybe this should be done in process.py?  are other uses of
         #        Process possibly affected by this?
         fdesc.setBlocking(sockFD)
-        if childFDs.has_key(2):
+        if 2 in childFDs:
             fdesc.setBlocking(childFDs[2])
 
         service = self.factory.service
--- twisted/runner/inetdconf.py (original)
+++ twisted/runner/inetdconf.py (refactored)
@@ -76,7 +76,7 @@
         try:
             self.parseFields(*line.split())
         except ValueError:
-            raise InvalidInetdConfError, 'Invalid line: ' + repr(line)
+            raise InvalidInetdConfError('Invalid line: ' + repr(line))
     
     def parseFields(self, *fields):
         """Override this."""
@@ -138,8 +138,8 @@
                 port = int(serviceName)
                 serviceName = 'unknown'
             except:
-                raise UnknownService, "Unknown service: %s (%s)" \
-                      % (serviceName, protocol)
+                raise UnknownService("Unknown service: %s (%s)" \
+                      % (serviceName, protocol))
 
         self.services.append(InetdService(serviceName, port, socketType,
                                           protocol, wait, user, group, program,
@@ -160,10 +160,10 @@
     def parseFields(self, name, portAndProtocol, *aliases):
         try:
             port, protocol = portAndProtocol.split('/')
-            port = long(port)
+            port = int(port)
         except:
-            raise InvalidServicesConfError, 'Invalid port/protocol:' + \
-                                            repr(portAndProtocol)
+            raise InvalidServicesConfError('Invalid port/protocol:' + \
+                                            repr(portAndProtocol))
 
         self.services[(name, protocol)] = port
         for alias in aliases:
@@ -183,9 +183,9 @@
     
     def parseFields(self, name, port, *aliases):
         try:
-            port = long(port)
+            port = int(port)
         except:
-            raise InvalidRPCServicesConfError, 'Invalid port:' + repr(port)
+            raise InvalidRPCServicesConfError('Invalid port:' + repr(port))
                         
         self.services[name] = port
         for alias in aliases:
--- twisted/runner/inetdtap.py (original)
+++ twisted/runner/inetdtap.py (refactored)
@@ -81,7 +81,7 @@
         if rpc:
             # RPC has extra options, so extract that
             protocol = protocol[4:]     # trim 'rpc/'
-            if not protocolDict.has_key(protocol):
+            if protocol not in protocolDict:
                 log.msg('Bad protocol: ' + protocol)
                 continue
             
@@ -91,14 +91,14 @@
                 log.msg('Bad RPC service/version: ' + service.name)
                 continue
 
-            if not rpcConf.services.has_key(name):
+            if name not in rpcConf.services:
                 log.msg('Unknown RPC service: ' + repr(service.name))
                 continue
 
             try:
                 if '-' in rpcVersions:
-                    start, end = map(int, rpcVersions.split('-'))
-                    rpcVersions = range(start, end+1)
+                    start, end = list(map(int, rpcVersions.split('-')))
+                    rpcVersions = list(range(start, end+1))
                 else:
                     rpcVersions = [int(rpcVersions)]
             except ValueError:
@@ -140,7 +140,7 @@
                 continue
 
             # Internal services can use a standard ServerFactory
-            if not inetd.internalProtocols.has_key(service.name):
+            if service.name not in inetd.internalProtocols:
                 log.msg('Unknown internal service: ' + service.name)
                 continue
             factory = ServerFactory()
--- twisted/runner/procmon.py (original)
+++ twisted/runner/procmon.py (refactored)
@@ -110,7 +110,7 @@
     def __getstate__(self):
         dct = service.Service.__getstate__(self)
         for k in ('active', 'consistency'):
-            if dct.has_key(k):
+            if k in dct:
                 del dct[k]
         dct['protocols'] = {}
         dct['delay'] = {}
@@ -119,7 +119,7 @@
         return dct
 
     def _checkConsistency(self):
-        for name, protocol in self.protocols.items():
+        for name, protocol in list(self.protocols.items()):
             proc = protocol.transport
             try:
                 proc.signalProcess(0)
@@ -131,7 +131,7 @@
                                              self._checkConsistency)
 
     def addProcess(self, name, args, uid=None, gid=None):
-        if self.processes.has_key(name):
+        if name in self.processes:
             raise KeyError("remove %s first" % name)
         self.processes[name] = args, uid, gid
         if self.active:
@@ -144,7 +144,7 @@
     def startService(self):
         service.Service.startService(self)
         self.active = 1
-        for name in self.processes.keys():
+        for name in list(self.processes.keys()):
             reactor.callLater(0, self.startProcess, name)
         self.consistency = reactor.callLater(self.consistencyDelay,
                                              self._checkConsistency)
@@ -152,25 +152,25 @@
     def stopService(self):
         service.Service.stopService(self)
         self.active = 0
-        for name in self.processes.keys():
+        for name in list(self.processes.keys()):
             self.stopProcess(name)
         self.consistency.cancel()
 
     def connectionLost(self, name):
-        if self.murder.has_key(name):
+        if name in self.murder:
             self.murder[name].cancel()
             del self.murder[name]
-        if self.protocols.has_key(name):
+        if name in self.protocols:
             del self.protocols[name]
         if time.time()-self.timeStarted[name]<self.threshold:
             delay = self.delay[name] = min(1+2*self.delay.get(name, 0), 3600)
         else:
             delay = self.delay[name] = 0
-        if self.active and self.processes.has_key(name):
+        if self.active and name in self.processes:
             reactor.callLater(delay, self.startProcess, name)
 
     def startProcess(self, name):
-        if self.protocols.has_key(name):
+        if name in self.protocols:
             return
         p = self.protocols[name] = LoggingProtocol()
         p.service = self
@@ -186,7 +186,7 @@
             pass
 
     def stopProcess(self, name):
-        if not self.protocols.has_key(name):
+        if name not in self.protocols:
             return
         proc = self.protocols[name].transport
         del self.protocols[name]
@@ -198,12 +198,12 @@
             self.murder[name] = reactor.callLater(self.killTime, self._forceStopProcess, proc)
 
     def restartAll(self):
-        for name in self.processes.keys():
+        for name in list(self.processes.keys()):
             self.stopProcess(name)
 
     def __repr__(self):
         l = []
-        for name, proc in self.processes.items():
+        for name, proc in list(self.processes.items()):
             uidgid = ''
             if proc[1] is not None:
                 uidgid = str(proc[1])
--- twisted/scripts/_twistd_unix.py (original)
+++ twisted/scripts/_twistd_unix.py (refactored)
@@ -52,8 +52,8 @@
     def opt_version(self):
         """Print version information and exit.
         """
-        print 'twistd (the Twisted daemon) %s' % copyright.version
-        print copyright.copyright
+        print('twistd (the Twisted daemon) %s' % copyright.version)
+        print(copyright.copyright)
         sys.exit()
 
 
@@ -73,7 +73,7 @@
             sys.exit('Pidfile %s contains non-numeric value' % pidfile)
         try:
             os.kill(pid, 0)
-        except OSError, why:
+        except OSError as why:
             if why[0] == errno.ESRCH:
                 # The pid doesnt exists.
                 log.msg('Removing stale pidfile %s' % pidfile, isError=True)
@@ -164,7 +164,7 @@
     for i in range(3):
         try:
             os.dup2(null, i)
-        except OSError, e:
+        except OSError as e:
             if e.errno != errno.EBADF:
                 raise
     os.close(null)
@@ -220,7 +220,7 @@
             return
         try:
             os.unlink(pidfile)
-        except OSError, e:
+        except OSError as e:
             if e.errno == errno.EACCES or e.errno == errno.EPERM:
                 log.msg("Warning: No permission to delete pid file")
             else:
@@ -261,7 +261,7 @@
                 rundir = '/'
         os.chdir(rundir)
         if daemon and umask is None:
-            umask = 077
+            umask = 0o77
         if umask is not None:
             os.umask(umask)
         if daemon:
--- twisted/scripts/_twistw.py (original)
+++ twisted/scripts/_twistw.py (refactored)
@@ -18,8 +18,8 @@
     def opt_version(self):
         """Print version information and exit.
         """
-        print 'twistd (the Twisted Windows runner) %s' % copyright.version
-        print copyright.copyright
+        print('twistd (the Twisted Windows runner) %s' % copyright.version)
+        print(copyright.copyright)
         sys.exit()
 
 
--- twisted/scripts/htmlizer.py (original)
+++ twisted/scripts/htmlizer.py (refactored)
@@ -42,8 +42,8 @@
     options = Options()
     try:
         options.parseOptions()
-    except usage.UsageError, e:
-        print str(e)
+    except usage.UsageError as e:
+        print(str(e))
         sys.exit(1)
     filename = options['filename']
     if options.get('stylesheet') is not None:
--- twisted/scripts/manhole.py (original)
+++ twisted/scripts/manhole.py (refactored)
@@ -55,7 +55,7 @@
     except:
         pass
     else:
-        gtkvers = pygtk._get_available_versions().keys()
+        gtkvers = list(pygtk._get_available_versions().keys())
         for v in gtkvers:
             frontend = {'1.2': 'gtk1',
                         '2.0': 'gtk2'}.get(v)
@@ -88,15 +88,15 @@
     config = MyOptions()
     try:
         config.parseOptions()
-    except usage.UsageError, e:
-        print str(e)
-        print str(config)
+    except usage.UsageError as e:
+        print(str(e))
+        print(str(config))
         sys.exit(1)
 
     try:
         run = getattr(sys.modules[__name__], 'run_' + config.opts['toolkit'])
     except AttributeError:
-        print "Sorry, no support for toolkit %r." % (config.opts['toolkit'],)
+        print("Sorry, no support for toolkit %r." % (config.opts['toolkit'],))
         sys.exit(1)
 
     run(config)
--- twisted/scripts/mktap.py (original)
+++ twisted/scripts/mktap.py (refactored)
@@ -120,7 +120,7 @@
 
     def init(self, tapLookup):
         sc = []
-        for (name, module) in tapLookup.iteritems():
+        for (name, module) in tapLookup.items():
             if IServiceMaker.providedBy(module):
                 sc.append((
                     name, None, lambda m=module: m.options(), module.description))
@@ -136,14 +136,14 @@
         self.params += rest
 
     def _reportDebug(self, info):
-        print 'Debug: ', info
+        print('Debug: ', info)
 
     def _reportProgress(self, info):
         s = self.pb(info)
         if s:
-            print '\rProgress: ', s,
+            print('\rProgress: ', s, end=' ')
         if info == 1.0:
-            print '\r' + (' ' * 79) + '\r',
+            print('\r' + (' ' * 79) + '\r', end=' ')
 
     def postOptions(self):
         if self.recursing:
@@ -165,7 +165,7 @@
             raise usage.UsageError(str(self))
         if hasattr(self, 'subOptions') and self.subOptions.get('help'):
             raise usage.UsageError(str(self.subOptions))
-        if not self.tapLookup.has_key(self.subCommand):
+        if self.subCommand not in self.tapLookup:
             raise usage.UsageError("Please select one of: "+
                                    ' '.join(self.tapLookup))
 
@@ -174,8 +174,8 @@
     options = FirstPassOptions()
     try:
         options.parseOptions(sys.argv[1:])
-    except usage.UsageError, e:
-        print e
+    except usage.UsageError as e:
+        print(e)
         sys.exit(2)
     except KeyboardInterrupt:
         sys.exit(1)
--- twisted/scripts/tap2deb.py (original)
+++ twisted/scripts/tap2deb.py (refactored)
@@ -27,7 +27,7 @@
 
     def postOptions(self):
         if not self["maintainer"]:
-            raise usage.UsageError, "maintainer must be specified."
+            raise usage.UsageError("maintainer must be specified.")
 
 
 type_dict = {
@@ -48,7 +48,7 @@
     try:
         config = MyOptions()
         config.parseOptions()
-    except usage.error, ue:
+    except usage.error as ue:
         sys.exit("%s: %s" % (sys.argv[0], ue))
 
     tap_file = config['tapfile']
@@ -143,7 +143,7 @@
 exit 0
 ''' % vars())
 
-    os.chmod(os.path.join('.build', directory, 'debian', 'init.d'), 0755)
+    os.chmod(os.path.join('.build', directory, 'debian', 'init.d'), 0o755)
 
     save_to_file(os.path.join('.build', directory, 'debian', 'postinst'),
     '''\
@@ -271,7 +271,7 @@
 .PHONY: build clean binary-indep binary-arch binary install
 ''' % vars())
 
-    os.chmod(os.path.join('.build', directory, 'debian', 'rules'), 0755)
+    os.chmod(os.path.join('.build', directory, 'debian', 'rules'), 0o755)
 
     os.chdir('.build/%(directory)s' % vars())
     os.system('dpkg-buildpackage -rfakeroot'+ ['', ' -uc -us'][config['unsigned']])
--- twisted/scripts/tap2rpm.py (original)
+++ twisted/scripts/tap2rpm.py (refactored)
@@ -173,7 +173,7 @@
     import random, string
 
     #  make top directory
-    oldMask = os.umask(0077)
+    oldMask = os.umask(0o077)
     while 1:
         tmpDir = os.path.join(baseDir, 'tap2rpm-%s-%s' % ( os.getpid(),
                                         random.randint(0, 999999999) ))
@@ -212,7 +212,7 @@
     try:
         config = MyOptions()
         config.parseOptions()
-    except usage.error, ue:
+    except usage.error as ue:
          sys.exit("%s: %s" % (sys.argv[0], ue))
 
     #  set up some useful local variables
@@ -254,19 +254,19 @@
               % vars())
     
     #  build rpm
-    print 'Starting build...'
-    print '=' * 70
+    print('Starting build...')
+    print('=' * 70)
     sys.stdout.flush()
     os.system('rpmbuild -ta --rcfile "%s" %s' % ( rpmrc_file, tarfile_name ))
-    print 'Done with build...'
-    print '=' * 70
+    print('Done with build...')
+    print('=' * 70)
     
     #  copy the RPMs to the local directory
     rpm_path = glob.glob(os.path.join(tmp_dir, 'RPMS', 'noarch', '*'))[0]
     srpm_path = glob.glob(os.path.join(tmp_dir, 'SRPMS', '*'))[0]
-    print 'Writing "%s"...' % os.path.basename(rpm_path)
+    print('Writing "%s"...' % os.path.basename(rpm_path))
     shutil.copy(rpm_path, '.')
-    print 'Writing "%s"...' % os.path.basename(srpm_path)
+    print('Writing "%s"...' % os.path.basename(srpm_path))
     shutil.copy(srpm_path, '.')
     
     #  remove the build directory
--- twisted/scripts/tapconvert.py (original)
+++ twisted/scripts/tapconvert.py (refactored)
@@ -45,8 +45,8 @@
     options = ConvertOptions()
     try:
         options.parseOptions(sys.argv[1:])
-    except usage.UsageError, e:
-        print e
+    except usage.UsageError as e:
+        print(e)
     else:
         app.convertStyle(options["in"], options["typein"],
                      options.opts['decrypt'] or getpass.getpass('Passphrase: '),
--- twisted/scripts/tkunzip.py (original)
+++ twisted/scripts/tkunzip.py (refactored)
@@ -1,6 +1,6 @@
 """Post-install GUI to compile to pyc and unpack twisted doco"""
 
-from __future__ import generators
+
 
 import sys
 import zipfile
@@ -16,8 +16,8 @@
 tkdll='tk84.dll'
 if which(tkdll) or which('DLLs/%s' % tkdll):
     try:
-        import Tkinter
-        from Tkinter import *
+        import tkinter
+        from tkinter import *
         from twisted.internet import tksupport
     except ImportError:
         pass
@@ -152,7 +152,7 @@
             return
         
         try:
-            self.remaining=self.iterator.next()
+            self.remaining=next(self.iterator)
         except StopIteration:
             self.stopping=1            
         except:
@@ -174,7 +174,7 @@
     os.path.walk(path, justlist, all)
 
     remaining=len(all)
-    i=zip(all, range(remaining-1, -1, -1))
+    i=list(zip(all, list(range(remaining-1, -1, -1))))
     for f, remaining in i:
         py_compile.compile(f)
         yield remaining
@@ -205,9 +205,9 @@
     opt=TkunzipOptions()
     try:
         opt.parseOptions(argv[1:])
-    except usage.UsageError, e:
-        print str(opt)
-        print str(e)
+    except usage.UsageError as e:
+        print(str(opt))
+        print(str(e))
         sys.exit(1)
 
     if opt['use-console']:
@@ -227,22 +227,22 @@
     sys.stdout = sys.__stdout__
     sys.stderr = sys.__stderr__
     if opt['zipfile']:
-        print 'Unpacking documentation...'
+        print('Unpacking documentation...')
         for n in zipstream.unzipIter(opt['zipfile'], opt['ziptargetdir']):
             if n % 100 == 0:
-                print n,
+                print(n, end=' ')
             if n % 1000 == 0:
-                print
-        print 'Done unpacking.'
+                print()
+        print('Done unpacking.')
         
     if opt['compiledir']:
-        print 'Compiling to pyc...'
+        print('Compiling to pyc...')
         import compileall
         compileall.compile_dir(opt["compiledir"])
-        print 'Done compiling.'
+        print('Done compiling.')
 
 def doItTkinterly(opt):
-    root=Tkinter.Tk()
+    root=tkinter.Tk()
     root.withdraw()
     root.title('One Moment.')
     root.protocol('WM_DELETE_WINDOW', reactor.stop)
--- twisted/scripts/trial.py (original)
+++ twisted/scripts/trial.py (refactored)
@@ -143,7 +143,7 @@
         Python 2.3.3.
         """
         coverdir = 'coverage'
-        print "Setting coverage directory to %s." % (coverdir,)
+        print("Setting coverage directory to %s." % (coverdir,))
         import trace
 
         # begin monkey patch ---------------------------
@@ -161,7 +161,7 @@
             try:
                 prog = open(filename).read()
                 prog = '\n'.join(prog.splitlines()) + '\n'
-            except IOError, err:
+            except IOError as err:
                 sys.stderr.write("Not printing coverage data for %r: %s\n"
                                  % (filename, err))
                 sys.stderr.flush()
@@ -208,10 +208,10 @@
         synopsis = ("Trial's output can be customized using plugins called "
                     "Reporters. You can\nselect any of the following "
                     "reporters using --reporter=<foo>\n")
-        print synopsis
+        print(synopsis)
         for p in plugin.getPlugins(itrial.IReporter):
-            print '   ', p.longOpt, '\t', p.description
-        print
+            print('   ', p.longOpt, '\t', p.description)
+        print()
         sys.exit(0)
 
     def opt_disablegc(self):
@@ -248,7 +248,7 @@
 
     def opt_random(self, option):
         try:
-            self['random'] = long(option)
+            self['random'] = int(option)
         except ValueError:
             raise usage.UsageError(
                 "Argument to --random must be a positive integer")
@@ -257,7 +257,7 @@
                 raise usage.UsageError(
                     "Argument to --random must be a positive integer")
             elif self['random'] == 0:
-                self['random'] = long(time.time() * 100)
+                self['random'] = int(time.time() * 100)
 
     def opt_without_module(self, option):
         """
@@ -321,7 +321,7 @@
         randomer = random.Random()
         randomer.seed(config['random'])
         loader.sorter = lambda x : randomer.random()
-        print 'Running tests shuffled with seed %d\n' % config['random']
+        print('Running tests shuffled with seed %d\n' % config['random'])
     if not config['until-failure']:
         loader.suiteFactory = runner.DestructiveTestSuite
     return loader
@@ -350,8 +350,8 @@
     config = Options()
     try:
         config.parseOptions()
-    except usage.error, ue:
-        raise SystemExit, "%s: %s" % (sys.argv[0], ue)
+    except usage.error as ue:
+        raise SystemExit("%s: %s" % (sys.argv[0], ue))
     _initialDebugSetup(config)
     trialRunner = _makeRunner(config)
     suite = _getSuite(config)
--- twisted/spread/banana.py (original)
+++ twisted/spread/banana.py (refactored)
@@ -19,7 +19,7 @@
 from twisted.persisted import styles
 from twisted.python import log
 
-import copy, cStringIO, struct
+import copy, io, struct
 
 class BananaError(Exception):
     pass
@@ -34,7 +34,7 @@
         integer = integer >> 7
 
 def b1282int(st):
-    oneHundredAndTwentyEight = 128l
+    oneHundredAndTwentyEight = 128
     i = 0
     place = 0
     for char in st:
@@ -190,11 +190,11 @@
             elif typebyte == LONGINT:
                 buffer = rest
                 num = b1282int(num)
-                gotItem(long(num))
+                gotItem(int(num))
             elif typebyte == LONGNEG:
                 buffer = rest
                 num = b1282int(num)
-                gotItem(-long(num))
+                gotItem(-int(num))
             elif typebyte == NEG:
                 buffer = rest
                 num = -b1282int(num)
@@ -263,7 +263,7 @@
         }
 
     incomingVocabulary = {}
-    for k, v in outgoingVocabulary.items():
+    for k, v in list(outgoingVocabulary.items()):
         incomingVocabulary[v] = k
 
     def __init__(self, isClient=1):
@@ -273,7 +273,7 @@
         self.isClient = isClient
 
     def sendEncoded(self, obj):
-        io = cStringIO.StringIO()
+        io = io.StringIO()
         self._encode(obj, io.write)
         value = io.getvalue()
         self.transport.write(value)
@@ -287,7 +287,7 @@
             write(LIST)
             for elem in obj:
                 self._encode(elem, write)
-        elif isinstance(obj, (int, long)):
+        elif isinstance(obj, (int, int)):
             if obj < self._smallestLongInt or obj > self._largestLongInt:
                 raise BananaError(
                     "int/long is too large to send (%d)" % (obj,))
@@ -331,7 +331,7 @@
 
 def encode(lst):
     """Encode a list s-expression."""
-    io = cStringIO.StringIO()
+    io = io.StringIO()
     _i.transport = io
     _i.sendEncoded(lst)
     return io.getvalue()
--- twisted/spread/flavors.py (original)
+++ twisted/spread/flavors.py (refactored)
@@ -29,9 +29,9 @@
 from twisted.python import log, reflect
 
 # sibling imports
-from jelly import setUnjellyableForClass, setUnjellyableForClassTree, setUnjellyableFactoryForClass, unjellyableRegistry
-from jelly import Jellyable, Unjellyable, _Dummy, _DummyNewStyle
-from jelly import setInstanceState, getInstanceState
+from .jelly import setUnjellyableForClass, setUnjellyableForClassTree, setUnjellyableFactoryForClass, unjellyableRegistry
+from .jelly import Jellyable, Unjellyable, _Dummy, _DummyNewStyle
+from .jelly import setInstanceState, getInstanceState
 
 # compatibility
 setCopierForClass = setUnjellyableForClass
@@ -212,7 +212,7 @@
         kw = broker.unserialize(kw, self.perspective)
         method = getattr(self.object, "view_%s" % message)
         try:
-            state = apply(method, (self.perspective,)+args, kw)
+            state = method(*(self.perspective,)+args, **kw)
         except TypeError:
             log.msg("%s didn't accept %s and %s" % (method, args, kw))
             raise
@@ -419,7 +419,7 @@
         kw = broker.unserialize(kw)
         method = getattr(self, "observe_%s" % message)
         try:
-            state = apply(method, args, kw)
+            state = method(*args, **kw)
         except TypeError:
             log.msg("%s didn't accept %s and %s" % (method, args, kw))
             raise
@@ -475,7 +475,7 @@
     def __hash__(self):
         """Hash me.
         """
-        return int(id(self.__dict__) % sys.maxint)
+        return int(id(self.__dict__) % sys.maxsize)
 
     broker = None
     luid = None
@@ -537,7 +537,7 @@
         """
         cacheID = self.broker.cachedRemotelyAs(self.cached)
         if cacheID is None:
-            from pb import ProtocolError
+            from .pb import ProtocolError
             raise ProtocolError("You can't call a cached method when the object hasn't been given to the peer yet.")
         return self.broker._sendMessage('cache', self.perspective, cacheID, self.name, args, kw)
 
@@ -588,7 +588,7 @@
         """
         cacheID = self.broker.cachedRemotelyAs(self.cached)
         if cacheID is None:
-            from pb import ProtocolError
+            from .pb import ProtocolError
             raise ProtocolError("You can't call a cached method when the "
                                 "object hasn't been given to the peer yet.")
         return self.broker._sendMessage('cache', self.perspective, cacheID,
--- twisted/spread/jelly.py (original)
+++ twisted/spread/jelly.py (refactored)
@@ -161,7 +161,7 @@
     'state' will be used to update inst.__dict__ . Supports both new- and
     old-style classes.
     """
-    if not isinstance(cls, types.ClassType):
+    if not isinstance(cls, type):
         # new-style
         inst = cls.__new__(cls)
         inst.__dict__.update(state) # Copy 'instance' behaviour
@@ -263,7 +263,7 @@
 
     for i in dir(module):
         i_ = getattr(module, i)
-        if type(i_) == types.ClassType:
+        if type(i_) == type:
             if issubclass(i_, baseClass):
                 setUnjellyableForClass('%s%s' % (prefix, i), i_)
 
@@ -451,8 +451,8 @@
             self.preserved[id(object)] = sexp
         return sexp
 
-    constantTypes = {types.StringType : 1, types.IntType : 1,
-                     types.FloatType : 1, types.LongType : 1}
+    constantTypes = {bytes : 1, int : 1,
+                     float : 1, int : 1}
 
 
     def _checkMutable(self,obj):
@@ -480,9 +480,9 @@
                 return obj
             elif objType is MethodType:
                 return ["method",
-                        obj.im_func.__name__,
-                        self.jelly(obj.im_self),
-                        self.jelly(obj.im_class)]
+                        obj.__func__.__name__,
+                        self.jelly(obj.__self__),
+                        self.jelly(obj.__self__.__class__)]
 
             elif UnicodeType and objType is UnicodeType:
                 return ['unicode', obj.encode('UTF-8')]
@@ -531,7 +531,7 @@
                     sxp.extend(self._jellyIterable(tuple_atom, obj))
                 elif objType in DictTypes:
                     sxp.append(dictionary_atom)
-                    for key, val in obj.items():
+                    for key, val in list(obj.items()):
                         sxp.append([self.jelly(key), self.jelly(val)])
                 elif (_set is not None and objType is set or
                       objType is _sets.Set):
@@ -633,7 +633,7 @@
 
 
     def unjelly(self, obj):
-        if type(obj) is not types.ListType:
+        if type(obj) is not list:
             return obj
         jelType = obj[0]
         if not self.taster.isTypeAllowed(jelType):
@@ -691,7 +691,7 @@
 
     def _unjelly_unicode(self, exp):
         if UnicodeType:
-            return unicode(exp[0], "UTF-8")
+            return str(exp[0], "UTF-8")
         else:
             return Unpersistable("Could not unpersist unicode: %s" % (exp[0],))
 
@@ -723,19 +723,19 @@
 
 
     def _unjelly_datetime(self, exp):
-        return datetime.datetime(*map(int, exp[0].split()))
+        return datetime.datetime(*list(map(int, exp[0].split())))
 
 
     def _unjelly_date(self, exp):
-        return datetime.date(*map(int, exp[0].split()))
+        return datetime.date(*list(map(int, exp[0].split())))
 
 
     def _unjelly_time(self, exp):
-        return datetime.time(*map(int, exp[0].split()))
+        return datetime.time(*list(map(int, exp[0].split())))
 
 
     def _unjelly_timedelta(self, exp):
-        days, seconds, microseconds = map(int, exp[0].split())
+        days, seconds, microseconds = list(map(int, exp[0].split()))
         return datetime.timedelta(
             days=days, seconds=seconds, microseconds=microseconds)
 
@@ -774,7 +774,7 @@
 
 
     def _unjelly_tuple(self, lst):
-        l = range(len(lst))
+        l = list(range(len(lst)))
         finished = 1
         for elem in l:
             if isinstance(self.unjellyInto(l, elem, lst[elem]), NotKnown):
@@ -786,7 +786,7 @@
 
 
     def _unjelly_list(self, lst):
-        l = range(len(lst))
+        l = list(range(len(lst)))
         for elem in l:
             self.unjellyInto(l, elem, lst[elem])
         return l
@@ -801,7 +801,7 @@
 
         @param containerType: the type of C{set} to use.
         """
-        l = range(len(lst))
+        l = list(range(len(lst)))
         finished = True
         for elem in l:
             data = self.unjellyInto(l, elem, lst[elem])
@@ -848,7 +848,7 @@
 
     def _unjelly_module(self, rest):
         moduleName = rest[0]
-        if type(moduleName) != types.StringType:
+        if type(moduleName) != bytes:
             raise InsecureJelly(
                 "Attempted to unjelly a module with a non-string name.")
         if not self.taster.isModuleAllowed(moduleName):
@@ -864,7 +864,7 @@
         if not self.taster.isModuleAllowed(modName):
             raise InsecureJelly("module %s not allowed" % modName)
         klaus = namedObject(rest[0])
-        if type(klaus) is not types.ClassType:
+        if type(klaus) is not type:
             raise InsecureJelly(
                 "class %r unjellied to something that isn't a class: %r" % (
                     rest[0], klaus))
@@ -893,7 +893,7 @@
 
     def _unjelly_instance(self, rest):
         clz = self.unjelly(rest[0])
-        if type(clz) is not types.ClassType:
+        if type(clz) is not type:
             raise InsecureJelly("Instance found with non-class class.")
         if hasattr(clz, "__setstate__"):
             inst = _newInstance(clz, {})
@@ -918,7 +918,7 @@
         im_name = rest[0]
         im_self = self.unjelly(rest[1])
         im_class = self.unjelly(rest[2])
-        if type(im_class) is not types.ClassType:
+        if type(im_class) is not type:
             raise InsecureJelly("Method found with non-class class.")
         if im_name in im_class.__dict__:
             if im_self is None:
--- twisted/spread/pb.py (original)
+++ twisted/spread/pb.py (refactored)
@@ -279,7 +279,7 @@
 
         This callback will be called with one argument, this instance.
         """
-        assert callable(callback)
+        assert hasattr(callback, '__call__')
         self.disconnectCallbacks.append(callback)
         if len(self.disconnectCallbacks) == 1:
             self.broker.notifyOnDisconnect(self._disconnected)
@@ -483,7 +483,7 @@
         """Called when the consumer attached to me runs out of buffer.
         """
         # Go backwards over the list so we can remove indexes from it as we go
-        for pageridx in xrange(len(self.pageProducers)-1, -1, -1):
+        for pageridx in range(len(self.pageProducers)-1, -1, -1):
             pager = self.pageProducers[pageridx]
             pager.sendNextPage()
             if not pager.stillPaging():
@@ -506,7 +506,7 @@
     def expressionReceived(self, sexp):
         """Evaluate an expression as it's received.
         """
-        if isinstance(sexp, types.ListType):
+        if isinstance(sexp, list):
             command = sexp[0]
             methodName = "proto_%s" % command
             method = getattr(self, methodName, None)
@@ -574,13 +574,13 @@
         # nuke potential circular references.
         self.luids = None
         if self.waitingForAnswers:
-            for d in self.waitingForAnswers.values():
+            for d in list(self.waitingForAnswers.values()):
                 try:
                     d.errback(failure.Failure(PBConnectionLost(reason)))
                 except:
                     log.deferr()
         # Assure all Cacheable.stoppedObserving are called
-        for lobj in self.remotelyCachedObjects.values():
+        for lobj in list(self.remotelyCachedObjects.values()):
             cacheable = lobj.object
             perspective = lobj.perspective
             try:
@@ -605,17 +605,17 @@
 
     def notifyOnDisconnect(self, notifier):
         """Call the given callback when the Broker disconnects."""
-        assert callable(notifier)
+        assert hasattr(notifier, '__call__')
         self.disconnects.append(notifier)
 
     def notifyOnFail(self, notifier):
         """Call the given callback if the Broker fails to connect."""
-        assert callable(notifier)
+        assert hasattr(notifier, '__call__')
         self.failures.append(notifier)
 
     def notifyOnConnect(self, notifier):
         """Call the given callback when the Broker connects."""
-        assert callable(notifier)
+        assert hasattr(notifier, '__call__')
         if self.connects is None:
             try:
                 notifier()
@@ -793,13 +793,13 @@
         pbc = None
         pbe = None
         answerRequired = 1
-        if kw.has_key('pbcallback'):
+        if 'pbcallback' in kw:
             pbc = kw['pbcallback']
             del kw['pbcallback']
-        if kw.has_key('pberrback'):
+        if 'pberrback' in kw:
             pbe = kw['pberrback']
             del kw['pberrback']
-        if kw.has_key('pbanswer'):
+        if 'pbanswer' in kw:
             assert (not pbe) and (not pbc), "You can't specify a no-answer requirement."
             answerRequired = kw['pbanswer']
             del kw['pbanswer']
@@ -838,7 +838,7 @@
             if object is None:
                 raise Error("Invalid Object ID")
             netResult = object.remoteMessageReceived(self, message, netArgs, netKw)
-        except Error, e:
+        except Error as e:
             if answerRequired:
                 # If the error is Jellyable or explicitly allowed via our
                 # security options, send it back and let the code on the
@@ -1108,7 +1108,8 @@
         return root.callRemote("login", username).addCallback(
             self._cbResponse, password, client)
 
-    def _cbResponse(self, (challenge, challenger), password, client):
+    def _cbResponse(self, xxx_todo_changeme, password, client):
+        (challenge, challenger) = xxx_todo_changeme
         return challenger.callRemote("respond", respond(challenge, password), client)
 
 
@@ -1258,11 +1259,12 @@
     Helper class for code which deals with avatars which PB must be capable of
     sending to a peer.
     """
-    def _cbLogin(self, (interface, avatar, logout)):
+    def _cbLogin(self, xxx_todo_changeme1):
         """
         Ensure that the avatar to be returned to the client is jellyable and
         set up disconnection notification to call the realm's logout object.
         """
+        (interface, avatar, logout) = xxx_todo_changeme1
         if not IJellyable.providedBy(avatar):
             avatar = AsReferenceable(avatar, "perspective")
 
--- twisted/spread/refpath.py (original)
+++ twisted/spread/refpath.py (refactored)
@@ -16,7 +16,7 @@
 
 from twisted.python import log
 
-from flavors import Referenceable, Viewable
+from .flavors import Referenceable, Viewable
 from copy import copy
 import os
 
@@ -55,7 +55,7 @@
     def remote_callPath(self, path, name, *args, **kw):
         ctx = PathReferenceContext(path, self)
         obj = ctx.getObject()
-        return apply(getattr(obj, "%s_%s" % (self.prefix, name)), args, kw)
+        return getattr(obj, "%s_%s" % (self.prefix, name))(*args, **kw)
 
 class PathReferenceContextDirectory(Referenceable):
     def __init__(self, root, prefix="remote"):
@@ -64,8 +64,7 @@
     def remote_callPath(self, path, name, *args, **kw):
         ctx = PathReferenceContext(path, self)
         obj = ctx.getObject()
-        return apply(getattr(obj, "%s_%s" % (self.prefix, name)),
-                     (ctx,)+args, kw)
+        return getattr(obj, "%s_%s" % (self.prefix, name))(*(ctx,)+args, **kw)
 
 class PathViewDirectory(Viewable):
     def __init__(self, root, prefix="view"):
@@ -74,8 +73,7 @@
     def view_callPath(self, perspective, path, name, *args, **kw):
         ctx = PathReferenceContext(path, self)
         obj = ctx.getObject()
-        return apply(getattr(obj, "%s_%s" % (self.prefix, name)),
-                     (perspective,)+args, kw)
+        return getattr(obj, "%s_%s" % (self.prefix, name))(*(perspective,)+args, **kw)
 
 class PathViewContextDirectory(Viewable):
     def __init__(self, root, prefix="view"):
@@ -84,8 +82,7 @@
     def view_callPath(self, perspective, path, name, *args, **kw):
         ctx = PathReferenceContext(path, self)
         obj = ctx.getObject()
-        return apply(getattr(obj, "%s_%s" % (self.prefix, name)),
-                     (perspective,ctx)+args, kw)
+        return getattr(obj, "%s_%s" % (self.prefix, name))(*(perspective,ctx)+args, **kw)
 
 ### "Client"-side objects
 
@@ -95,5 +92,4 @@
         self.path = path
 
     def callRemote(self, name, *args, **kw):
-        apply(self.ref.callRemote,
-              ("callPath", self.path, name)+args, kw)
+        self.ref.callRemote(*("callPath", self.path, name)+args, **kw)
--- twisted/spread/util.py (original)
+++ twisted/spread/util.py (refactored)
@@ -92,7 +92,7 @@
         Create a pager with a Reference to a remote collector and
         an optional callable to invoke upon completion.
         """
-        if callable(callback):
+        if hasattr(callback, '__call__'):
             self.callback = callback
             self.callbackArgs = args
             self.callbackKeyword = kw
--- twisted/spread/ui/gtk2util.py (original)
+++ twisted/spread/ui/gtk2util.py (refactored)
@@ -3,7 +3,7 @@
 # See LICENSE for details.
 
 
-from __future__ import nested_scopes
+
 
 import gtk
 
@@ -91,12 +91,12 @@
 
 
     def setDefaults(self, defaults):
-        if not defaults.has_key('port'):
+        if 'port' not in defaults:
             defaults['port'] = str(pb.portno)
-        elif isinstance(defaults['port'], (int, long)):
+        elif isinstance(defaults['port'], (int, int)):
             defaults['port'] = str(defaults['port'])
 
-        for k, v in defaults.iteritems():
+        for k, v in defaults.items():
             if k in self.fields:
                 widget = getattr(self, "_%sEntry" % (k,))
                 widget.set_text(v)
@@ -179,10 +179,10 @@
         if isinstance(reason, failure.Failure):
             reason = reason.value
         self.statusMsg(reason)
-        if isinstance(reason, (unicode, str)):
+        if isinstance(reason, (str, str)):
             text = reason
         else:
-            text = unicode(reason)
+            text = str(reason)
         msg = gtk.MessageDialog(self._loginDialog,
                                 gtk.DIALOG_DESTROY_WITH_PARENT,
                                 gtk.MESSAGE_ERROR,
@@ -210,6 +210,6 @@
             getattr(widget, op)()
 
     def statusMsg(self, text):
-        if not isinstance(text, (unicode, str)):
-            text = unicode(text)
+        if not isinstance(text, (str, str)):
+            text = str(text)
         return self._statusBar.push(self._statusContext, text)
--- twisted/spread/ui/gtkutil.py (original)
+++ twisted/spread/ui/gtkutil.py (refactored)
@@ -34,7 +34,7 @@
             bName = string.replace(b, '_', ' ')
             result.append(cbutton(bName, getattr(self,prefix+b)))
         if container:
-            map(container.add, result)
+            list(map(container.add, result))
         return result
 
 def scrollify(widget):
@@ -138,13 +138,13 @@
         self.signal_connect('destroy',gtk.mainquit,None)
 
     def loginReset(self):
-        print 'doing login reset'
+        print('doing login reset')
         self.logstat.set_text("Idle.")
         self._resetTimeout = None
         return 0
 
     def loginReport(self, txt):
-        print 'setting login report',repr(txt)
+        print('setting login report',repr(txt))
         self.logstat.set_text(txt)
         if not (self._resetTimeout is None):
             gtk.timeout_remove(self._resetTimeout)
@@ -198,7 +198,7 @@
 
     def doIt(self):
         gtk.timeout_remove(self.tid)
-        apply(self.cmd, self.args)
+        self.cmd(*self.args)
 
 def afterOneTimeout(timeout, cmd, *args):
     _TimerOuter(timeout, cmd, args)
--- twisted/spread/ui/tktree.py (original)
+++ twisted/spread/ui/tktree.py (refactored)
@@ -16,7 +16,7 @@
 """
 
 import os
-from Tkinter import *
+from tkinter import *
 
 class Node:
     def __init__(self):
@@ -61,8 +61,8 @@
     def isExpandable(self):
         return os.path.isdir(self.name)
     def getSubNodes(self):
-        names=map(lambda x,n=self.name:os.path.join(n,x),os.listdir(self.name))
-        return map(FileNode,names)
+        names=list(map(lambda x,n=self.name:os.path.join(n,x),os.listdir(self.name)))
+        return list(map(FileNode,names))
 
 class TreeItem:
     def __init__(self,widget,parent,node):
@@ -112,7 +112,7 @@
 
 class ListboxTree:
     def __init__(self,parent=None,**options):
-        self.box=apply(Listbox,[parent],options)
+        self.box=Listbox(*[parent], **options)
         self.box.bind("<Double-1>",self.flip)
         self.roots=[]
         self.items=[]
@@ -120,17 +120,17 @@
         """
         for packing.
         """
-        apply(self.box.pack,args,kw)
+        self.box.pack(*args, **kw)
     def grid(self,*args,**kw):
         """
         for gridding.
         """
-        apply(self.box.grid,args,kw)
+        self.box.grid(*args, **kw)
     def yview(self,*args,**kw):
         """
         for scrolling.
         """
-        apply(self.box.yview,args,kw)
+        self.box.yview(*args, **kw)
     def addRoot(self,node):
         r=ListboxTreeItem(self,None,node)
         self.roots.append(r)
@@ -153,7 +153,7 @@
     def expand(self,item):
         if item.expand or item.expand==None: return
         item.expand=1
-        item.subitems=map(lambda x,i=item,s=self:ListboxTreeItem(s,i,x),item.node.getSubNodes())
+        item.subitems=list(map(lambda x,i=item,s=self:ListboxTreeItem(s,i,x),item.node.getSubNodes()))
         if item.subitems:
             item.subitems[0].first=1
         i=self.items.index(item)
--- twisted/spread/ui/tkutil.py (original)
+++ twisted/spread/ui/tkutil.py (refactored)
@@ -4,9 +4,9 @@
 
 """Utilities for building L{PB<twisted.spread.pb>} clients with L{Tkinter}.
 """
-from Tkinter import *
-from tkSimpleDialog import _QueryString
-from tkFileDialog import _Dialog
+from tkinter import *
+from tkinter.simpledialog import _QueryString
+from tkinter.filedialog import _Dialog
 from twisted.spread import pb
 from twisted.internet import reactor
 from twisted import copyright
@@ -41,7 +41,7 @@
 
     @returns: a string
     '''
-    d = apply(_QueryPassword, (title, prompt), kw)
+    d = _QueryPassword(*(title, prompt), **kw)
     return d.result
 
 def grid_setexpand(widget):
@@ -62,7 +62,7 @@
             b=Button(self,text=labels[i],anchor=W,height=1,pady=0)
             b.config(command=lambda s=self,i=i:s.setSort(i))
             b.grid(column=i,row=0,sticky=N+E+W)
-            box=apply(Listbox,(self,),kw)
+            box=Listbox(*(self,), **kw)
             box.grid(column=i,row=1,sticky=N+E+S+W)
             self.lists.append(box)
         grid_setexpand(self)
@@ -77,7 +77,7 @@
         rets=[]
         for l in self.lists:
             func=getattr(l,funcname)
-            ret=apply(func,args,kw)
+            ret=func(*args, **kw)
             if ret!=None: rets.append(ret)
         if rets: return rets
 
@@ -132,10 +132,10 @@
         return self.lists[0].curselection()
 
     def delete(self,*args):
-        apply(self._callall,("delete",)+args)
+        self._callall(*("delete",)+args)
 
     def get(self,*args):
-        bad=apply(self._callall,("get",)+args)
+        bad=self._callall(*("get",)+args)
         if len(args)==1:
             return bad
         ret=[]
@@ -172,7 +172,7 @@
     select_anchor=selection_anchor
 
     def selection_clear(self,*args):
-        apply(self._callall,("selection_clear",)+args)
+        self._callall(*("selection_clear",)+args)
 
     select_clear=selection_clear
 
@@ -182,17 +182,17 @@
     select_includes=selection_includes
 
     def selection_set(self,*args):
-        apply(self._callall,("selection_set",)+args)
+        self._callall(*("selection_set",)+args)
 
     select_set=selection_set
 
     def xview(self,*args):
         if not args: return self.lists[0].xview()
-        apply(self._callall,("xview",)+args)
+        self._callall(*("xview",)+args)
 
     def yview(self,*args):
         if not args: return self.lists[0].yview()
-        apply(self._callall,("yview",)+args)
+        self._callall(*("yview",)+args)
 
 class ProgressBar:
     def __init__(self, master=None, orientation="horizontal",
@@ -292,7 +292,7 @@
                 dict=stuff[2]
             else: dict={}
             Label(self,text=label+": ").grid(column=0,row=row)
-            e=apply(Entry,(self,),dict)
+            e=Entry(*(self,), **dict)
             e.grid(column=1,row=row)
             e.insert(0,value)
             self.entries[label]=e
@@ -307,7 +307,7 @@
 
     def doLogin(self):
         values={}
-        for k in self.entries.keys():
+        for k in list(self.entries.keys()):
             values[string.lower(k)]=self.entries[k].get()
         self.callback(values)
         self.destroy()
--- twisted/tap/manhole.py (original)
+++ twisted/tap/manhole.py (refactored)
@@ -39,7 +39,7 @@
     opt_w = opt_password
 
     def postOptions(self):
-        if not self.has_key('password'):
+        if 'password' not in self:
             self.opt_password('-')
 
 def makeService(config):
--- twisted/tap/socks.py (original)
+++ twisted/tap/socks.py (refactored)
@@ -23,12 +23,12 @@
 
 def makeService(config):
     if config["interface"] != "127.0.0.1":
-        print
-        print "WARNING:"
-        print "  You have chosen to listen on a non-local interface."
-        print "  This may allow intruders to access your local network"
-        print "  if you run this on a firewall."
-        print
+        print()
+        print("WARNING:")
+        print("  You have chosen to listen on a non-local interface.")
+        print("  This may allow intruders to access your local network")
+        print("  if you run this on a firewall.")
+        print()
     t = socks.SOCKSv4Factory(config['log'])
     portno = int(config['port'])
     return internet.TCPServer(portno, t, interface=config['interface'])
--- twisted/test/app_qtstub.py (original)
+++ twisted/test/app_qtstub.py (refactored)
@@ -39,14 +39,14 @@
     sys.meta_path.insert(0, QTNotImporter())
     try:
         reactors.installReactor('qt')
-    except reactors.NoSuchReactor, e:
+    except reactors.NoSuchReactor as e:
         if e.args != ('qt',):
-            print 'Wrong arguments to NoSuchReactor:', e.args
+            print('Wrong arguments to NoSuchReactor:', e.args)
         else:
             # Do nothing to indicate success.
             pass
     else:
-        print 'installed qtreactor succesfully'
+        print('installed qtreactor succesfully')
     sys.stdout.flush()
 
 if __name__ == '__main__':
--- twisted/test/generator_failure_tests.py (original)
+++ twisted/test/generator_failure_tests.py (refactored)
@@ -70,7 +70,7 @@
                 self.fail("Yield should have yielded exception.")
         g = generator()
         f = getDivisionFailure()
-        g.next()
+        next(g)
         self._throwIntoGenerator(f, g)
 
         self.assertEquals(stuff[0][0], ZeroDivisionError)
@@ -98,7 +98,7 @@
                 self.fail("No exception sent to generator")
 
         g = generator()
-        g.next()
+        next(g)
         self._throwIntoGenerator(f, g)
 
         self.assertEqual(foundFailures, [f])
@@ -124,7 +124,7 @@
             else:
                 self.fail("No exception sent to generator")
         g = generator()
-        g.next()
+        next(g)
         self._throwIntoGenerator(f, g)
 
         self.assertEqual(len(newFailures), 1)
@@ -145,7 +145,7 @@
             except:
                 self.assertIsInstance(Failure().value, IndexError)
         g = generator()
-        g.next()
+        next(g)
         f = getDivisionFailure()
         self._throwIntoGenerator(f, g)
 
@@ -161,7 +161,7 @@
             except:
                 [][1]
         g = generator()
-        g.next()
+        next(g)
         f = getDivisionFailure()
         try:
             self._throwIntoGenerator(f, g)
--- twisted/test/iosim.py (original)
+++ twisted/test/iosim.py (refactored)
@@ -45,7 +45,7 @@
     implements(interfaces.ITransport,
                interfaces.ITLSTransport) # ha ha not really
 
-    _nextserial = itertools.count().next
+    _nextserial = itertools.count().__next__
     closed = 0
     disconnecting = 0
     disconnected = 0
@@ -213,18 +213,18 @@
         Returns whether any data was moved.
         """
         if self.debug or debug:
-            print '-- GLUG --'
+            print('-- GLUG --')
         sData = self.serverIO.getOutBuffer()
         cData = self.clientIO.getOutBuffer()
         self.clientIO._checkProducer()
         self.serverIO._checkProducer()
         if self.debug or debug:
-            print '.'
+            print('.')
             # XXX slightly buggy in the face of incremental output
             if cData:
-                print 'C: '+repr(cData)
+                print('C: '+repr(cData))
             if sData:
-                print 'S: '+repr(sData)
+                print('S: '+repr(sData))
         if cData:
             self.serverIO.bufferReceived(cData)
         if sData:
@@ -234,14 +234,14 @@
         if (self.serverIO.disconnecting and
             not self.serverIO.disconnected):
             if self.debug or debug:
-                print '* C'
+                print('* C')
             self.serverIO.disconnected = True
             self.clientIO.disconnecting = True
             self.clientIO.reportDisconnect()
             return True
         if self.clientIO.disconnecting and not self.clientIO.disconnected:
             if self.debug or debug:
-                print '* S'
+                print('* S')
             self.clientIO.disconnected = True
             self.serverIO.disconnecting = True
             self.serverIO.reportDisconnect()
--- twisted/test/process_cmdline.py (original)
+++ twisted/test/process_cmdline.py (refactored)
@@ -2,4 +2,4 @@
 
 import sys
 for x in sys.argv[1:]:
-    print x
+    print(x)
--- twisted/test/process_fds.py (original)
+++ twisted/test/process_fds.py (refactored)
@@ -9,32 +9,32 @@
 
 if debug: stderr = os.fdopen(2, "w")
 
-if debug: print >>stderr, "this is stderr"
+if debug: print("this is stderr", file=stderr)
 
 abcd = os.read(0, 4)
-if debug: print >>stderr, "read(0):", abcd
+if debug: print("read(0):", abcd, file=stderr)
 if abcd != "abcd":
     sys.exit(1)
 
-if debug: print >>stderr, "os.write(1, righto)"
+if debug: print("os.write(1, righto)", file=stderr)
 
 os.write(1, "righto")
 
 efgh = os.read(3, 4)
-if debug: print >>stderr, "read(3):", efgh
+if debug: print("read(3):", efgh, file=stderr)
 if efgh != "efgh":
     sys.exit(2)
 
-if debug: print >>stderr, "os.close(4)"
+if debug: print("os.close(4)", file=stderr)
 os.close(4)
 
 eof = os.read(5, 4)
-if debug: print >>stderr, "read(5):", eof
+if debug: print("read(5):", eof, file=stderr)
 if eof != "":
     sys.exit(3)
 
-if debug: print >>stderr, "os.write(1, closed)"
+if debug: print("os.write(1, closed)", file=stderr)
 os.write(1, "closed")
 
-if debug: print >>stderr, "sys.exit(0)"
+if debug: print("sys.exit(0)", file=stderr)
 sys.exit(0)
--- twisted/test/process_linger.py (original)
+++ twisted/test/process_linger.py (refactored)
@@ -5,9 +5,9 @@
 
 import os, sys, time
 
-print "here is some text"
+print("here is some text")
 time.sleep(1)
-print "goodbye"
+print("goodbye")
 os.close(1)
 os.close(2)
 
--- twisted/test/process_signal.py (original)
+++ twisted/test/process_signal.py (refactored)
@@ -3,6 +3,6 @@
 signal.signal(signal.SIGINT, signal.SIG_DFL)
 if getattr(signal, "SIGHUP", None) is not None:
     signal.signal(signal.SIGHUP, signal.SIG_DFL)
-print 'ok, signal us'
+print('ok, signal us')
 sys.stdin.read()
 sys.exit(1)
--- twisted/test/process_twisted.py (original)
+++ twisted/test/process_twisted.py (refactored)
@@ -24,19 +24,19 @@
     implements(interfaces.IHalfCloseableProtocol)
     
     def connectionMade(self):
-        print "connection made"
+        print("connection made")
     
     def dataReceived(self, data):
         self.transport.write(data)
 
     def readConnectionLost(self):
-        print "readConnectionLost"
+        print("readConnectionLost")
         self.transport.loseConnection()
     def writeConnectionLost(self):
-        print "writeConnectionLost"
+        print("writeConnectionLost")
     
     def connectionLost(self, reason):
-        print "connectionLost", reason
+        print("connectionLost", reason)
         reactor.stop()
 
 stdio.StandardIO(Echo())
--- twisted/test/proto_helpers.py (original)
+++ twisted/test/proto_helpers.py (refactored)
@@ -3,9 +3,9 @@
 
 
 try:
-    from cStringIO import StringIO
+    from io import StringIO
 except ImportError:
-    from StringIO import StringIO
+    from io import StringIO
 
 from twisted.protocols import basic
 from twisted.internet import error
@@ -21,11 +21,11 @@
 
     def connectionMade(self):
         if self.start:
-            map(self.sendLine, self.lines)
+            list(map(self.sendLine, self.lines))
 
     def lineReceived(self, line):
         if not self.start:
-            map(self.sendLine, self.lines)
+            list(map(self.sendLine, self.lines))
             self.lines = []
         self.response.append(line)
 
@@ -64,7 +64,7 @@
         return self.io.getvalue()
 
     def write(self, data):
-        if isinstance(data, unicode): # no, really, I mean it
+        if isinstance(data, str): # no, really, I mean it
             raise TypeError("Data must not be unicode")
         self.io.write(data)
 
--- twisted/test/test_adbapi.py (original)
+++ twisted/test/test_adbapi.py (refactored)
@@ -54,7 +54,7 @@
         if not conn:
             self.failUnless(self.openfun_called)
         else:
-            self.failUnless(self.openfun_called.has_key(conn))
+            self.failUnless(conn in self.openfun_called)
 
     def testPool(self):
         d = self.dbpool.runOperation(simple_table_schema)
@@ -292,7 +292,7 @@
 
     def _testPool_2(self, res):
         # reach in and close the connection manually
-        self.dbpool.connections.values()[0].close()
+        list(self.dbpool.connections.values())[0].close()
 
     def _testPool_3(self, res):
         sql = "select count(1) from simple"
@@ -672,7 +672,7 @@
         success = True
         try:
             result = f(*a, **kw)
-        except Exception, e:
+        except Exception as e:
             success = False
             result = Failure()
         onResult(success, result)
--- twisted/test/test_amp.py (original)
+++ twisted/test/test_amp.py (refactored)
@@ -533,7 +533,7 @@
                                                    'print': "ignored",
                                                    '_answer': "1"}))
         self.assertEquals(answers, [dict(hello="yay",
-                                         Print=u"ignored")])
+                                         Print="ignored")])
 
 
 class SimpleGreeting(amp.Command):
@@ -1384,8 +1384,9 @@
         if spuriousTraffic:
             self.assertRaises(amp.ProtocolSwitched, c.sendHello, 'world')
 
-        def cbConnsLost(((serverSuccess, serverData),
-                         (clientSuccess, clientData))):
+        def cbConnsLost(xxx_todo_changeme):
+            ((serverSuccess, serverData),
+                         (clientSuccess, clientData)) = xxx_todo_changeme
             self.failUnless(serverSuccess)
             self.failUnless(clientSuccess)
             self.assertEquals(''.join(serverData), SWITCH_CLIENT_DATA)
--- twisted/test/test_application.py (original)
+++ twisted/test/test_application.py (refactored)
@@ -2,7 +2,7 @@
 # See LICENSE for details.
 
 import sys, copy, os, pickle, warnings
-from StringIO import StringIO
+from io import StringIO
 
 
 from twisted.trial import unittest, util
@@ -430,7 +430,7 @@
         # FIXME: This test is far too dense.  It needs comments.
         #  -- spiv, 2004-11-07
         if not interfaces.IReactorUNIX(reactor, None):
-            raise unittest.SkipTest, "This reactor does not support UNIX domain sockets"
+            raise unittest.SkipTest("This reactor does not support UNIX domain sockets")
         s = service.MultiService()
         s.startService()
         factory = protocol.ServerFactory()
@@ -461,7 +461,7 @@
 
     def testVolatile(self):
         if not interfaces.IReactorUNIX(reactor, None):
-            raise unittest.SkipTest, "This reactor does not support UNIX domain sockets"
+            raise unittest.SkipTest("This reactor does not support UNIX domain sockets")
         factory = protocol.ServerFactory()
         factory.protocol = wire.Echo
         t = internet.UNIXServer('echo.skt', factory)
@@ -486,7 +486,7 @@
 
     def testStoppingServer(self):
         if not interfaces.IReactorUNIX(reactor, None):
-            raise unittest.SkipTest, "This reactor does not support UNIX domain sockets"
+            raise unittest.SkipTest("This reactor does not support UNIX domain sockets")
         factory = protocol.ServerFactory()
         factory.protocol = wire.Echo
         t = internet.UNIXServer('echo.skt', factory)
@@ -878,7 +878,8 @@
         Test that installing qtreactor when it's absent fails properly.
         """
         scriptPath = sibpath(__file__, "app_qtstub.py")
-        def _checkOutput((output, err, code)):
+        def _checkOutput(xxx_todo_changeme):
+            (output, err, code) = xxx_todo_changeme
             self.failIf(output, output)
         result = getProcessOutputAndValue(
             sys.executable,
--- twisted/test/test_banana.py (original)
+++ twisted/test/test_banana.py (refactored)
@@ -1,7 +1,7 @@
 # Copyright (c) 2001-2007 Twisted Matrix Laboratories.
 # See LICENSE for details.
 
-import StringIO
+import io
 import sys
 
 # Twisted Imports
@@ -13,9 +13,9 @@
 
 class MathTestCase(unittest.TestCase):
     def testInt2b128(self):
-        funkylist = range(0,100) + range(1000,1100) + range(1000000,1000100) + [1024 **10l]
+        funkylist = list(range(0,100)) + list(range(1000,1100)) + list(range(1000000,1000100)) + [1024 **10]
         for i in funkylist:
-            x = StringIO.StringIO()
+            x = io.StringIO()
             banana.int2b128(i, x.write)
             v = x.getvalue()
             y = banana.b1282int(v)
@@ -26,7 +26,7 @@
     encClass = banana.Banana
 
     def setUp(self):
-        self.io = StringIO.StringIO()
+        self.io = io.StringIO()
         self.enc = self.encClass()
         self.enc.makeConnection(protocol.FileWrapper(self.io))
         self.enc._selectDialect("none")
@@ -46,9 +46,9 @@
         assert self.result == 'hello'
 
     def testLong(self):
-        self.enc.sendEncoded(1015l)
-        self.enc.dataReceived(self.io.getvalue())
-        assert self.result == 1015l, "should be 1015l, got %s" % self.result
+        self.enc.sendEncoded(1015)
+        self.enc.dataReceived(self.io.getvalue())
+        assert self.result == 1015, "should be 1015l, got %s" % self.result
 
 
     def test_largeLong(self):
@@ -131,9 +131,9 @@
 
 
     def testNegativeLong(self):
-        self.enc.sendEncoded(-1015l)
-        self.enc.dataReceived(self.io.getvalue())
-        assert self.result == -1015l, "should be -1015l, got %s" % self.result
+        self.enc.sendEncoded(-1015)
+        self.enc.dataReceived(self.io.getvalue())
+        assert self.result == -1015, "should be -1015l, got %s" % self.result
 
     def testInteger(self):
         self.enc.sendEncoded(1015)
@@ -160,7 +160,7 @@
         foo = [1, 2, [3, 4], [30.5, 40.2], 5,
                ["six", "seven", ["eight", 9]], [10],
                # TODO: currently the C implementation's a bit buggy...
-               sys.maxint * 3l, sys.maxint * 2l, sys.maxint * -2l]
+               sys.maxsize * 3, sys.maxsize * 2, sys.maxsize * -2]
         self.enc.sendEncoded(foo)
         for byte in self.io.getvalue():
             self.enc.dataReceived(byte)
--- twisted/test/test_compat.py (original)
+++ twisted/test/test_compat.py (refactored)
@@ -22,7 +22,7 @@
     def __iter__(self):
         return self
 
-    def next(self):
+    def __next__(self):
         self.i += 1
         if self.i >= self.lim:
             raise StopIteration
@@ -35,7 +35,7 @@
         self.assertEquals(d1, d2)
         d1['a'] = 'c'
         self.assertNotEquals(d1, d2)
-        d2 = dict(d1.items())
+        d2 = dict(list(d1.items()))
         self.assertEquals(d1, d2)
 
     def testBool(self):
@@ -45,7 +45,7 @@
         self.assertEquals(bool(False), False)
 
     def testIteration(self):
-        lst1, lst2 = range(10), []
+        lst1, lst2 = list(range(10)), []
 
         for i in iter(lst1):
             lst2.append(i)
@@ -55,7 +55,7 @@
         try:
             iterable = iter(lst1)
             while 1:
-                lst2.append(iterable.next())
+                lst2.append(next(iterable))
         except StopIteration:
             pass
         self.assertEquals(lst1, lst2)
@@ -69,18 +69,18 @@
         try:
             iterable = iter(IterableCounter(10))
             while 1:
-                lst2.append(iterable.next())
+                lst2.append(next(iterable))
         except StopIteration:
             pass
         self.assertEquals(lst1, lst2)
         del lst2[:]
 
-        for i in iter(IterableCounter(20).next, 10):
+        for i in iter(IterableCounter(20).__next__, 10):
             lst2.append(i)
         self.assertEquals(lst1, lst2)
 
     def testIsinstance(self):
-        self.assert_(isinstance(u'hi', types.StringTypes))
+        self.assert_(isinstance('hi', str))
         self.assert_(isinstance(self, unittest.TestCase))
         # I'm pretty sure it's impossible to implement this
         # without replacing isinstance on 2.2 as well :(
--- twisted/test/test_cooperator.py (original)
+++ twisted/test/test_cooperator.py (refactored)
@@ -121,7 +121,7 @@
             tasks.append(c.coiterate(myiter(stuff)))
 
         return defer.DeferredList(tasks).addCallback(
-            lambda ign: self.assertEquals(tuple(L), sum(zip(*groupsOfThings), ())))
+            lambda ign: self.assertEquals(tuple(L), sum(list(zip(*groupsOfThings)), ())))
 
 
     def testResourceExhaustion(self):
@@ -146,7 +146,7 @@
         c._tick()
         c.stop()
         self.failUnless(_TPF.stopped)
-        self.assertEquals(output, range(10))
+        self.assertEquals(output, list(range(10)))
 
 
     def testCallbackReCoiterate(self):
--- twisted/test/test_defer.py (original)
+++ twisted/test/test_defer.py (refactored)
@@ -337,7 +337,7 @@
         S, E = [], []
         try:
             '10' + 5
-        except TypeError, e:
+        except TypeError as e:
             expected = str(e)
         d = defer.maybeDeferred((lambda x: x + 5), '10')
         d.addCallbacks(S.append, E.append)
@@ -573,7 +573,7 @@
         self._call_1(d)
         try:
             self._call_2(d)
-        except defer.AlreadyCalledError, e:
+        except defer.AlreadyCalledError as e:
             self._check(e, "testAlreadyCalledDebug_CC", "_call_1", "_call_2")
         else:
             self.fail("second callback failed to raise AlreadyCalledError")
@@ -584,7 +584,7 @@
         self._call_1(d)
         try:
             self._err_2(d)
-        except defer.AlreadyCalledError, e:
+        except defer.AlreadyCalledError as e:
             self._check(e, "testAlreadyCalledDebug_CE", "_call_1", "_err_2")
         else:
             self.fail("second errback failed to raise AlreadyCalledError")
@@ -595,7 +595,7 @@
         self._err_1(d)
         try:
             self._call_2(d)
-        except defer.AlreadyCalledError, e:
+        except defer.AlreadyCalledError as e:
             self._check(e, "testAlreadyCalledDebug_EC", "_err_1", "_call_2")
         else:
             self.fail("second callback failed to raise AlreadyCalledError")
@@ -606,7 +606,7 @@
         self._err_1(d)
         try:
             self._err_2(d)
-        except defer.AlreadyCalledError, e:
+        except defer.AlreadyCalledError as e:
             self._check(e, "testAlreadyCalledDebug_EE", "_err_1", "_err_2")
         else:
             self.fail("second errback failed to raise AlreadyCalledError")
@@ -618,7 +618,7 @@
         self._call_1(d)
         try:
             self._call_2(d)
-        except defer.AlreadyCalledError, e:
+        except defer.AlreadyCalledError as e:
             self.failIf(e.args)
         else:
             self.fail("second callback failed to raise AlreadyCalledError")
@@ -822,16 +822,16 @@
 
         for i in range(M):
             queue.put(i)
-            self.assertEquals(gotten, range(i + 1))
+            self.assertEquals(gotten, list(range(i + 1)))
         for i in range(N):
             queue.put(N + i)
-            self.assertEquals(gotten, range(M))
+            self.assertEquals(gotten, list(range(M)))
         self.assertRaises(defer.QueueOverflow, queue.put, None)
 
         gotten = []
         for i in range(N):
             queue.get().addCallback(gotten.append)
-            self.assertEquals(gotten, range(N, N + i + 1))
+            self.assertEquals(gotten, list(range(N, N + i + 1)))
 
         queue = defer.DeferredQueue()
         gotten = []
@@ -839,7 +839,7 @@
             queue.get().addCallback(gotten.append)
         for i in range(N):
             queue.put(i)
-        self.assertEquals(gotten, range(N))
+        self.assertEquals(gotten, list(range(N)))
 
         queue = defer.DeferredQueue(size=0)
         self.assertRaises(defer.QueueOverflow, queue.put, None)
--- twisted/test/test_defgen.py (original)
+++ twisted/test/test_defgen.py (refactored)
@@ -1,4 +1,4 @@
-from __future__ import generators, nested_scopes
+
 
 import sys
 
@@ -107,7 +107,7 @@
         yield ow
         try:
             ow.getResult()
-        except ZeroDivisionError, e:
+        except ZeroDivisionError as e:
             self.assertEquals(str(e), 'OMG')
         yield "WOOSH"
         return
@@ -274,7 +274,7 @@
 
 if sys.version_info > (2, 5):
     # Load tests
-    exec inlineCallbacksTestsSource
+    exec(inlineCallbacksTestsSource)
 else:
     # Make a placeholder test case
     class InlineCallbacksTests(unittest.TestCase):
--- twisted/test/test_dirdbm.py (original)
+++ twisted/test/test_dirdbm.py (refactored)
@@ -52,7 +52,7 @@
 
         # check they exist
         for k, v in self.items:
-            assert d.has_key(k), "has_key() failed"
+            assert k in d, "has_key() failed"
             assert d[k] == v, "database has wrong value"
 
         # check non existent key
@@ -91,16 +91,16 @@
         assert dbitems == copyitems, ".copyTo().items() didn't match: %s != %s" % (repr(dbkeys), repr(copyitems))
 
         d2.clear()
-        assert len(d2.keys()) == len(d2.values()) == len(d2.items()) == 0, ".clear() failed"
+        assert len(list(d2.keys())) == len(list(d2.values())) == len(list(d2.items())) == 0, ".clear() failed"
         shutil.rmtree(copyPath)
 
         # delete items
         for k, v in self.items:
             del d[k]
-            assert not d.has_key(k), "has_key() even though we deleted it"
-        assert len(d.keys()) == 0, "database has keys"
-        assert len(d.values()) == 0, "database has values"
-        assert len(d.items()) == 0, "database has items"
+            assert k not in d, "has_key() even though we deleted it"
+        assert len(list(d.keys())) == 0, "database has keys"
+        assert len(list(d.values())) == 0, "database has values"
+        assert len(list(d.items())) == 0, "database has items"
 
 
     def testModificationTime(self):
--- twisted/test/test_doc.py (original)
+++ twisted/test/test_doc.py (refactored)
@@ -35,7 +35,7 @@
                 continue
             try:
                 package = reflect.namedModule(packageName)
-            except ImportError, e:
+            except ImportError as e:
                 # This is testing doc coverage, not importability.
                 # (Really, I don't want to deal with the fact that I don't
                 #  have pyserial installed.)
@@ -61,7 +61,7 @@
             try:
                 module = reflect.namedModule('.'.join([packageName,
                                                        moduleName]))
-            except Exception, e:
+            except Exception as e:
                 # print moduleName, "misbehaved:", e
                 pass
             else:
@@ -75,7 +75,7 @@
         for packageName in self.packageNames:
             try:
                 package = reflect.namedModule(packageName)
-            except Exception, e:
+            except Exception as e:
                 # This is testing doc coverage, not importability.
                 # (Really, I don't want to deal with the fact that I don't
                 #  have pyserial installed.)
@@ -85,7 +85,7 @@
                 if not inspect.getdoc(package):
                     docless.append(package.__file__.replace('.pyc','.py'))
         self.failIf(docless, "No docstrings for package files\n"
-                    "%s" % ('\n'.join(map(errorInFile, docless),)))
+                    "%s" % ('\n'.join(list(map(errorInFile, docless)),)))
 
 
     # This test takes a while and doesn't come close to passing.  :(
--- twisted/test/test_enterprise.py (original)
+++ twisted/test/test_enterprise.py (refactored)
@@ -17,7 +17,7 @@
             ("foo'd", "text", "'foo''d'"),
             ("\x00abc\\s\xFF", "bytea", "'\\\\000abc\\\\\\\\s\\377'"),
             (12, "text", "'12'"),
-            (u"123'456", "text", u"'123''456'")
+            ("123'456", "text", "'123''456'")
             ]:
             self.assertEquals(
                 self.callDeprecated(util._deprecatedVersion, util.quote, value,
--- twisted/test/test_epoll.py (original)
+++ twisted/test/test_epoll.py (refactored)
@@ -47,7 +47,7 @@
         client.setblocking(False)
         try:
             client.connect(('127.0.0.1', self.serverSocket.getsockname()[1]))
-        except socket.error, e:
+        except socket.error as e:
             self.assertEquals(e.args[0], errno.EINPROGRESS)
         else:
             raise unittest.FailTest("Connect should have raised EINPROGRESS")
@@ -63,7 +63,7 @@
         """
         try:
             p = _epoll.epoll(16)
-        except OSError, e:
+        except OSError as e:
             raise unittest.FailTest(str(e))
         else:
             p.close()
@@ -148,7 +148,7 @@
 else:
     try:
         e = _epoll.epoll(16)
-    except IOError, exc:
+    except IOError as exc:
         if exc.errno == errno.ENOSYS:
             del exc
             EPoll.skip = "epoll support missing from platform"
--- twisted/test/test_explorer.py (original)
+++ twisted/test/test_explorer.py (refactored)
@@ -143,8 +143,9 @@
     "A function which accepts a variable number of args and keywords."
     return a, kw
 
-def function_crazy((alpha, beta), c, d=range(4), **kw):
+def function_crazy(xxx_todo_changeme, c, d=list(range(4)), **kw):
     "A function with a mad crazy signature."
+    (alpha, beta) = xxx_todo_changeme
     return alpha, beta, c, d, kw
 
 class TestBrowseFunction(unittest.TestCase):
@@ -211,7 +212,7 @@
 
         expected_signature = [{'name': 'c'},
                               {'name': 'd',
-                               'default': range(4)},
+                               'default': list(range(4))},
                               {'name': 'kw',
                                'keywords': 1}]
 
@@ -223,11 +224,10 @@
         self.failUnlessEqual(signature.get_name(1), 'c')
 
         # Get a list of values from a list of ExplorerImmutables.
-        arg_2_default = map(lambda l: l.value,
-                            signature.get_default(2)[1].get_elements())
+        arg_2_default = [l.value for l in signature.get_default(2)[1].get_elements()]
 
         self.failUnlessEqual(signature.get_name(2), 'd')
-        self.failUnlessEqual(arg_2_default, range(4))
+        self.failUnlessEqual(arg_2_default, list(range(4)))
 
         self.failUnlessEqual(signature.get_name(3), 'kw')
         self.failUnless(signature.is_keyword(3))
--- twisted/test/test_factories.py (original)
+++ twisted/test/test_factories.py (refactored)
@@ -37,7 +37,7 @@
         self.msgs = Out.msgs.copy()
 
     def connectionMade(self):
-        for i in self.msgs.keys():
+        for i in list(self.msgs.keys()):
             self.sendString(pickle.dumps( (i, self.msgs[i])))
 
     def stringReceived(self, msg):
--- twisted/test/test_failure.py (original)
+++ twisted/test/test_failure.py (refactored)
@@ -7,7 +7,7 @@
 """
 
 import sys
-import StringIO
+import io
 import traceback
 
 from twisted.trial import unittest, util
@@ -54,7 +54,7 @@
         self.assertRaises(failure.Failure, f.trap, OverflowError)
 
     def testPrinting(self):
-        out = StringIO.StringIO()
+        out = io.StringIO()
         try:
             1/0
         except:
@@ -123,7 +123,7 @@
         information, even for string exceptions.
         """
         failure = self._getStringFailure()
-        output = StringIO.StringIO()
+        output = io.StringIO()
         failure.printTraceback(file=output)
         lines = output.getvalue().splitlines()
         # The last line should be the value of the raised string
--- twisted/test/test_formmethod.py (original)
+++ twisted/test/test_formmethod.py (refactored)
@@ -54,23 +54,23 @@
         self.argTest(formmethod.Boolean, tests, ())
 
     def testDate(self):
-        goodTests = { 
+        goodTests = list({ 
             ("2002", "12", "21"): (2002, 12, 21),
             ("1996", "2", "29"): (1996, 2, 29),
             ("", "", ""): None,
-            }.items()
+            }.items())
         badTests = [("2002", "2", "29"), ("xx", "2", "3"),
                     ("2002", "13", "1"), ("1999", "12","32"),
                     ("2002", "1"), ("2002", "2", "3", "4")]
         self.argTest(formmethod.Date, goodTests, badTests)
 
     def testRangedInteger(self):
-        goodTests = {"0": 0, "12": 12, "3": 3}.items()
+        goodTests = list({"0": 0, "12": 12, "3": 3}.items())
         badTests = ["-1", "x", "13", "-2000", "3.4"]
         self.argTest(formmethod.IntegerRange, goodTests, badTests, 0, 12)
 
     def testVerifiedPassword(self):
-        goodTests = {("foo", "foo"): "foo", ("ab", "ab"): "ab"}.items()
+        goodTests = list({("foo", "foo"): "foo", ("ab", "ab"): "ab"}.items())
         badTests = [("ab", "a"), ("12345", "12345"), ("", ""), ("a", "a"), ("a",), ("a", "a", "a")]
         self.argTest(formmethod.VerifiedPassword, goodTests, badTests, min=2, max=4)
 
--- twisted/test/test_ftp.py (original)
+++ twisted/test/test_ftp.py (refactored)
@@ -8,7 +8,7 @@
 """
 
 import os.path
-from StringIO import StringIO
+from io import StringIO
 import errno
 
 from zope.interface import implements
@@ -296,7 +296,7 @@
     def testDecodeHostPort(self):
         self.assertEquals(ftp.decodeHostPort('25,234,129,22,100,23'),
                 ('25.234.129.22', 25623))
-        nums = range(6)
+        nums = list(range(6))
         for i in range(6):
             badValue = list(nums)
             badValue[i] = 256
@@ -358,11 +358,11 @@
         port = self.serverProtocol.getDTPPort(protocol.Factory())
         self.assertEquals(port, 0)
 
-        self.serverProtocol.passivePortRange = xrange(22032, 65536)
+        self.serverProtocol.passivePortRange = range(22032, 65536)
         port = self.serverProtocol.getDTPPort(protocol.Factory())
         self.assertEquals(port, 22035)
 
-        self.serverProtocol.passivePortRange = xrange(22032, 22035)
+        self.serverProtocol.passivePortRange = range(22032, 22035)
         self.assertRaises(error.CannotListenError,
                           self.serverProtocol.getDTPPort,
                           protocol.Factory())
@@ -413,7 +413,8 @@
             return defer.gatherResults([d1, d2])
         chainDeferred.addCallback(queueCommand)
 
-        def downloadDone((ignored, downloader)):
+        def downloadDone(xxx_todo_changeme):
+            (ignored, downloader) = xxx_todo_changeme
             return downloader.buffer
         return chainDeferred.addCallback(downloadDone)
 
@@ -570,7 +571,8 @@
     def testOneLine(self):
         # This example line taken from the docstring for FTPFileListProtocol
         line = '-rw-r--r--   1 root     other        531 Jan 29 03:26 README'
-        def check(((file,), other)):
+        def check(xxx_todo_changeme1):
+            ((file,), other) = xxx_todo_changeme1
             self.failIf(other, 'unexpect unparsable lines: %s' % repr(other))
             self.failUnless(file['filetype'] == '-', 'misparsed fileitem')
             self.failUnless(file['perms'] == 'rw-r--r--', 'misparsed perms')
@@ -587,7 +589,8 @@
         line1 = 'drw-r--r--   2 root     other        531 Jan  9  2003 A'
         line2 = 'lrw-r--r--   1 root     other          1 Jan 29 03:26 B -> A'
         line3 = 'woohoo! '
-        def check(((file1, file2), (other,))):
+        def check(xxx_todo_changeme2):
+            ((file1, file2), (other,)) = xxx_todo_changeme2
             self.failUnless(other == 'woohoo! \r', 'incorrect other line')
             # file 1
             self.failUnless(file1['filetype'] == 'd', 'misparsed fileitem')
@@ -612,7 +615,8 @@
         return self.getFilesForLines([line1, line2, line3]).addCallback(check)
 
     def testUnknownLine(self):
-        def check((files, others)):
+        def check(xxx_todo_changeme3):
+            (files, others) = xxx_todo_changeme3
             self.failIf(files, 'unexpected file entries')
             self.failUnless(others == ['ABC\r', 'not a file\r'],
                             'incorrect unparsable lines: %s' % repr(others))
@@ -1633,7 +1637,7 @@
         d = self.client.removeFile("/tmp/test")
         response = ['250-perhaps a progress report',
                     '250 okay']
-        map(self.client.lineReceived, response)
+        list(map(self.client.lineReceived, response))
         return d.addCallback(self.assertTrue)
 
 
--- twisted/test/test_htb.py (original)
+++ twisted/test/test_htb.py (refactored)
@@ -70,7 +70,7 @@
 
 # TODO: Test the Transport stuff?
 
-from test_pcp import DummyConsumer
+from .test_pcp import DummyConsumer
 
 class ConsumerShaperTest(TestBucketBase):
     def setUp(self):
--- twisted/test/test_internet.py (original)
+++ twisted/test/test_internet.py (refactored)
@@ -859,9 +859,9 @@
         def f2(x):
             l2.append(x)
         def done():
-            self.assertEquals(l, range(20))
+            self.assertEquals(l, list(range(20)))
         def done2():
-            self.assertEquals(l2, range(10))
+            self.assertEquals(l2, list(range(10)))
 
         for n in range(10):
             reactor.callLater(0, f, n)
@@ -908,7 +908,7 @@
         dc.cancel()
         str(dc)
 
-        dc = reactor.callLater(0, lambda: None, x=[({'hello': u'world'}, 10j), reactor], *range(10))
+        dc = reactor.callLater(0, lambda: None, x=[({'hello': 'world'}, 10j), reactor], *list(range(10)))
         str(dc)
         dc.cancel()
         str(dc)
@@ -987,7 +987,7 @@
         """
         Test that reactor.crash terminates reactor.run
         """
-        for i in xrange(3):
+        for i in range(3):
             reactor.callLater(0.01, reactor.crash)
             reactor.run()
 
@@ -1074,11 +1074,11 @@
         reactor.iterate() # flush timers
 
     def tearDown(self):
-        for t in self.timers.values():
+        for t in list(self.timers.values()):
             t.cancel()
 
     def checkTimers(self):
-        l1 = self.timers.values()
+        l1 = list(self.timers.values())
         l2 = list(reactor.getDelayedCalls())
 
         # There should be at least the calls we put in.  There may be other
@@ -1203,9 +1203,10 @@
 
         reactor.spawnProcess(helperProto, sys.executable, ("python", "-u", helperPath), env)
 
-        def cbFinished((reason, output, error)):
+        def cbFinished(xxx_todo_changeme):
             # If the output is "done 127.0.0.1\n" we don't really care what
             # else happened.
+            (reason, output, error) = xxx_todo_changeme
             output = ''.join(output)
             if output != 'done 127.0.0.1\n':
                 self.fail((
--- twisted/test/test_iutils.py (original)
+++ twisted/test/test_iutils.py (refactored)
@@ -115,7 +115,8 @@
             "sys.exit(1)"
             ])
 
-        def gotOutputAndValue((out, err, code)):
+        def gotOutputAndValue(xxx_todo_changeme):
+            (out, err, code) = xxx_todo_changeme
             self.assertEquals(out, "hello world!\n")
             self.assertEquals(err, "goodbye world!" + os.linesep)
             self.assertEquals(code, 1)
@@ -141,7 +142,8 @@
             "sys.stderr.flush()",
             "os.kill(os.getpid(), signal.SIGKILL)"])
 
-        def gotOutputAndValue((out, err, sig)):
+        def gotOutputAndValue(xxx_todo_changeme1):
+            (out, err, sig) = xxx_todo_changeme1
             self.assertEquals(out, "stdout bytes\n")
             self.assertEquals(err, "stderr bytes\n")
             self.assertEquals(sig, signal.SIGKILL)
@@ -188,7 +190,8 @@
         L{getProcessOutputAndValue} runs the given command with the working
         directory given by the C{path} parameter.
         """
-        def check((out, err, status), dir):
+        def check(xxx_todo_changeme2, dir):
+            (out, err, status) = xxx_todo_changeme2
             self.assertEqual(out, dir)
             self.assertEqual(status, 0)
         return self._pathTest(utils.getProcessOutputAndValue, check)
@@ -252,7 +255,8 @@
         directory as the parent process and succeeds even if the current
         working directory is not accessible.
         """
-        def check((out, err, status), dir):
+        def check(xxx_todo_changeme3, dir):
+            (out, err, status) = xxx_todo_changeme3
             self.assertEqual(out, dir)
             self.assertEqual(status, 0)
         return self._defaultPathTest(
--- twisted/test/test_jelly.py (original)
+++ twisted/test/test_jelly.py (refactored)
@@ -131,7 +131,7 @@
         a.bmethod = b.bmethod
         b.a = a
         im_ = jelly.unjelly(jelly.jelly(b)).a.bmethod
-        self.assertEquals(im_.im_class, im_.im_self.__class__)
+        self.assertEquals(im_.__self__.__class__, im_.__self__.__class__)
 
 
     def test_methodsNotSelfIdentity(self):
@@ -358,7 +358,7 @@
 
 
     def test_unicode(self):
-        x = unicode('blah')
+        x = str('blah')
         y = jelly.unjelly(jelly.jelly(x))
         self.assertEquals(x, y)
         self.assertEquals(type(x), type(y))
--- twisted/test/test_log.py (original)
+++ twisted/test/test_log.py (refactored)
@@ -6,7 +6,7 @@
 """
 
 import os, sys, time, logging, warnings
-from cStringIO import StringIO
+from io import StringIO
 
 from twisted.trial import unittest
 
@@ -36,7 +36,7 @@
         i = catcher.pop()
         self.assertEquals(i["message"][0], "test")
         self.assertEquals(i["testShouldCatch"], True)
-        self.failUnless(i.has_key("time"))
+        self.failUnless("time" in i)
         self.assertEquals(len(catcher), 0)
 
 
@@ -89,7 +89,7 @@
             log.addObserver(observer)
             self.addCleanup(log.removeObserver, observer)
 
-        for i in xrange(3):
+        for i in range(3):
             # Reset the lists for simpler comparison.
             L1[:] = []
             L2[:] = []
@@ -209,7 +209,7 @@
         self.lp.addObserver(self.flo.emit)
 
         try:
-            str(u'\N{VULGAR FRACTION ONE HALF}')
+            str('\N{VULGAR FRACTION ONE HALF}')
         except UnicodeEncodeError:
             # This is the behavior we want - don't change anything.
             self._origEncoding = None
@@ -249,7 +249,7 @@
 
 
     def testSingleUnicode(self):
-        self.lp.msg(u"Hello, \N{VULGAR FRACTION ONE HALF} world.")
+        self.lp.msg("Hello, \N{VULGAR FRACTION ONE HALF} world.")
         self.assertEquals(len(self.out), 1)
         self.assertIn('with str error', self.out[0])
         self.assertIn('UnicodeEncodeError', self.out[0])
--- twisted/test/test_logfile.py (original)
+++ twisted/test/test_logfile.py (refactored)
@@ -27,9 +27,9 @@
         Restore back write rights on created paths: if tests modified the
         rights, that will allow the paths to be removed easily afterwards.
         """
-        os.chmod(self.dir, 0777)
+        os.chmod(self.dir, 0o777)
         if os.path.exists(self.path):
-            os.chmod(self.path, 0777)
+            os.chmod(self.path, 0o777)
 
 
     def testWriting(self):
@@ -127,7 +127,7 @@
         Check rotated files have same permissions as original.
         """
         f = open(self.path, "w").close()
-        os.chmod(self.path, 0707)
+        os.chmod(self.path, 0o707)
         mode = os.stat(self.path)[stat.ST_MODE]
         log = logfile.LogFile(self.name, self.dir)
         log.write("abc")
@@ -143,7 +143,7 @@
         log.write("abc")
 
         # change permissions so rotation would fail
-        os.chmod(self.dir, 0555)
+        os.chmod(self.dir, 0o555)
 
         # if this succeeds, chmod doesn't restrict us, so we can't
         # do the test
@@ -193,8 +193,8 @@
         """
         Test the fromFullPath method.
         """
-        log1 = logfile.LogFile(self.name, self.dir, 10, defaultMode=0777)
-        log2 = logfile.LogFile.fromFullPath(self.path, 10, defaultMode=0777)
+        log1 = logfile.LogFile(self.name, self.dir, 10, defaultMode=0o777)
+        log2 = logfile.LogFile.fromFullPath(self.path, 10, defaultMode=0o777)
         self.assertEquals(log1.name, log2.name)
         self.assertEquals(os.path.abspath(log1.path), log2.path)
         self.assertEquals(log1.rotateLength, log2.rotateLength)
@@ -206,7 +206,7 @@
         should keep the permission.
         """
         f = file(self.path, "w")
-        os.chmod(self.path, 0707)
+        os.chmod(self.path, 0o707)
         currentMode = stat.S_IMODE(os.stat(self.path)[stat.ST_MODE])
         f.close()
         log1 = logfile.LogFile(self.name, self.dir)
@@ -217,13 +217,13 @@
         """
         Test specifying the permissions used on the log file.
         """
-        log1 = logfile.LogFile(self.name, self.dir, defaultMode=0066)
+        log1 = logfile.LogFile(self.name, self.dir, defaultMode=0o066)
         mode = stat.S_IMODE(os.stat(self.path)[stat.ST_MODE])
         if runtime.platform.isWindows():
             # The only thing we can get here is global read-only
-            self.assertEquals(mode, 0444)
+            self.assertEquals(mode, 0o444)
         else:
-            self.assertEquals(mode, 0066)
+            self.assertEquals(mode, 0o066)
 
 
 class RiggedDailyLogFile(logfile.DailyLogFile):
--- twisted/test/test_loopback.py (original)
+++ twisted/test/test_loopback.py (refactored)
@@ -236,7 +236,7 @@
 
 
     def _producertest(self, producerClass):
-        toProduce = map(str, range(0, 10))
+        toProduce = list(map(str, list(range(0, 10))))
 
         class ProducingProtocol(Protocol):
             def connectionMade(self):
@@ -285,7 +285,8 @@
                     self.consumer.unregisterProducer()
         d = self._producertest(PushProducer)
 
-        def finished((client, server)):
+        def finished(xxx_todo_changeme):
+            (client, server) = xxx_todo_changeme
             self.failIf(
                 server.producer.resumed,
                 "Streaming producer should not have been resumed.")
--- twisted/test/test_memcache.py (original)
+++ twisted/test/test_memcache.py (refactored)
@@ -402,12 +402,12 @@
         """
         Using a non-string key as argument to commands should raise an error.
         """
-        d1 = self.assertFailure(self.proto.set(u"foo", "bar"), ClientError)
-        d2 = self.assertFailure(self.proto.increment(u"egg"), ClientError)
+        d1 = self.assertFailure(self.proto.set("foo", "bar"), ClientError)
+        d2 = self.assertFailure(self.proto.increment("egg"), ClientError)
         d3 = self.assertFailure(self.proto.get(1), ClientError)
-        d4 = self.assertFailure(self.proto.delete(u"bar"), ClientError)
-        d5 = self.assertFailure(self.proto.append(u"foo", "bar"), ClientError)
-        d6 = self.assertFailure(self.proto.prepend(u"foo", "bar"), ClientError)
+        d4 = self.assertFailure(self.proto.delete("bar"), ClientError)
+        d5 = self.assertFailure(self.proto.append("foo", "bar"), ClientError)
+        d6 = self.assertFailure(self.proto.prepend("foo", "bar"), ClientError)
         return gatherResults([d1, d2, d3, d4, d5, d6])
 
 
@@ -415,7 +415,7 @@
         """
         Using a non-string value should raise an error.
         """
-        return self.assertFailure(self.proto.set("foo", u"bar"), ClientError)
+        return self.assertFailure(self.proto.set("foo", "bar"), ClientError)
 
 
     def test_pipelining(self):
--- twisted/test/test_modules.py (original)
+++ twisted/test/test_modules.py (refactored)
@@ -215,7 +215,7 @@
     stuffing some code in it.
     """
 
-    _serialnum = itertools.count().next # used to generate serial numbers for
+    _serialnum = itertools.count().__next__ # used to generate serial numbers for
                                         # package names.
 
     def setUp(self):
--- twisted/test/test_monkey.py (original)
+++ twisted/test/test_monkey.py (refactored)
@@ -151,7 +151,7 @@
         def _():
             self.assertEquals(self.testObject.foo, 'haha')
             self.assertEquals(self.testObject.bar, 'blahblah')
-            raise RuntimeError, "Something went wrong!"
+            raise RuntimeError("Something went wrong!")
 
         self.monkeyPatcher.addPatch(self.testObject, 'foo', 'haha')
         self.monkeyPatcher.addPatch(self.testObject, 'bar', 'blahblah')
--- twisted/test/test_newcred.py (original)
+++ twisted/test/test_newcred.py (refactored)
@@ -113,7 +113,7 @@
         self.avatars = {}
 
     def requestAvatar(self, avatarId, mind, *interfaces):
-        if self.avatars.has_key(avatarId):
+        if avatarId in self.avatars:
             avatar = self.avatars[avatarId]
         else:
             avatar = TestAvatar(avatarId)
--- twisted/test/test_nmea.py (original)
+++ twisted/test/test_nmea.py (refactored)
@@ -4,7 +4,7 @@
 
 """Test cases for the NMEA GPS protocol"""
 
-import StringIO
+import io
 
 from twisted.trial import unittest
 from twisted.internet import reactor, protocol
@@ -12,7 +12,7 @@
 
 from twisted.protocols.gps import nmea
 
-class StringIOWithNoClose(StringIO.StringIO):
+class StringIOWithNoClose(io.StringIO):
     def close(self):
         pass
 
@@ -27,7 +27,7 @@
         l = len(self.results)
         try:
             function(*args, **kwargs)
-        except Exception, e:
+        except Exception as e:
             self.results.append(e)
         if l == len(self.results):
             self.results.append(NotImplementedError())
--- twisted/test/test_paths.py (original)
+++ twisted/test/test_paths.py (refactored)
@@ -129,9 +129,9 @@
         dictoid[f1] = 3
         dictoid[f1prime] = 4
         self.assertEquals(dictoid[f1], 4)
-        self.assertEquals(dictoid.keys(), [f1])
-        self.assertIdentical(dictoid.keys()[0], f1)
-        self.assertNotIdentical(dictoid.keys()[0], f1prime) # sanity check
+        self.assertEquals(list(dictoid.keys()), [f1])
+        self.assertIdentical(list(dictoid.keys())[0], f1)
+        self.assertNotIdentical(list(dictoid.keys())[0], f1prime) # sanity check
         dictoid[f2] = 5
         self.assertEquals(dictoid[f2], 5)
         self.assertEquals(len(dictoid), 2)
@@ -233,9 +233,9 @@
         """
         fp = filepath.FilePath(self.mktemp())
         ose = self.assertRaises(OSError, fp.children)
-        d1 = ose.__dict__.keys()
+        d1 = list(ose.__dict__.keys())
         d1.remove('originalException')
-        d2 = ose.originalException.__dict__.keys()
+        d2 = list(ose.originalException.__dict__.keys())
         d1.sort()
         d2.sort()
         self.assertEquals(d1, d2)
@@ -273,7 +273,7 @@
         the passed file as expected (using C{os.stat} to check). We use some
         basic modes that should work everywhere (even on Windows).
         """
-        for mode in (0555, 0777):
+        for mode in (0o555, 0o777):
             self.path.child("sub1").chmod(mode)
             self.assertEquals(
                 stat.S_IMODE(os.stat(self.path.child("sub1").path).st_mode),
--- twisted/test/test_pb.py (original)
+++ twisted/test/test_pb.py (refactored)
@@ -13,7 +13,7 @@
 
 import sys, os, time, gc
 
-from cStringIO import StringIO
+from io import StringIO
 from zope.interface import implements, Interface
 
 from twisted.python.versions import Version
@@ -561,7 +561,7 @@
         foo = NestedRemote()
         s.setNameForLocal("foo", foo)
         x = c.remoteForName("foo")
-        for igno in xrange(pb.MAX_BROKER_REFS + 10):
+        for igno in range(pb.MAX_BROKER_REFS + 10):
             if s.transport.closed or c.transport.closed:
                 break
             x.callRemote("getSimple").addCallbacks(l.append, e.append)
@@ -675,7 +675,7 @@
         self.assertEquals(complex[0].foo, 4)
         self.assertEquals(len(coll), 2)
         cp = coll[0][0]
-        self.assertIdentical(cp.checkMethod().im_self, cp,
+        self.assertIdentical(cp.checkMethod().__self__, cp,
                              "potential refcounting issue")
         self.assertIdentical(cp.checkSelf(), cp,
                              "other potential refcounting issue")
@@ -1361,12 +1361,14 @@
         secondLogin = factory.login(
             credentials.UsernamePassword('baz', 'quux'), "BRAINS!")
         d = gatherResults([firstLogin, secondLogin])
-        def cbLoggedIn((first, second)):
+        def cbLoggedIn(xxx_todo_changeme):
+            (first, second) = xxx_todo_changeme
             return gatherResults([
                     first.callRemote('getAvatarId'),
                     second.callRemote('getAvatarId')])
         d.addCallback(cbLoggedIn)
-        def cbAvatarIds((first, second)):
+        def cbAvatarIds(xxx_todo_changeme1):
+            (first, second) = xxx_todo_changeme1
             self.assertEqual(first, 'foo')
             self.assertEqual(second, 'baz')
         d.addCallback(cbAvatarIds)
--- twisted/test/test_pcp.py (original)
+++ twisted/test/test_pcp.py (refactored)
@@ -5,7 +5,7 @@
 
 __version__ = '$Revision: 1.5 $'[11:-2]
 
-from StringIO import StringIO
+from io import StringIO
 from twisted.trial import unittest
 from twisted.protocols import pcp
 
--- twisted/test/test_persisted.py (original)
+++ twisted/test/test_persisted.py (refactored)
@@ -9,14 +9,14 @@
 from twisted.trial import unittest
 
 try:
-    import cPickle as pickle
+    import pickle as pickle
 except ImportError:
     import pickle
 
 try:
-    import cStringIO as StringIO
+    import io as StringIO
 except ImportError:
-    import StringIO
+    import io
 
 # Twisted Imports
 from twisted.persisted import styles, aot, crefutil
@@ -243,7 +243,7 @@
 
         def testCopyReg(self):
             s = "foo_bar"
-            sio = StringIO.StringIO()
+            sio = io.StringIO()
             sio.write(s)
             assert marmalade.unjellyFromXML(marmalade.jellyToXML({1:sio}))[1].getvalue() == s
 
@@ -253,7 +253,7 @@
             a.bmethod = b.bmethod
             b.a = a
             im_ = marmalade.unjellyFromXML(marmalade.jellyToXML(b)).a.bmethod
-            self.assertEquals(im_.im_class, im_.im_self.__class__)
+            self.assertEquals(im_.__self__.__class__, im_.__self__.__class__)
 
 
         def test_methodNotSelfIdentity(self):
@@ -303,8 +303,8 @@
             d = {'hello': 'world', "method": dj}
             l = [1, 2, 3,
                  "he\tllo\n\n\"x world!",
-                 u"goodbye \n\t\u1010 world!",
-                 1, 1.0, 100 ** 100l, unittest, marmalade.DOMJellier, d,
+                 "goodbye \n\t\u1010 world!",
+                 1, 1.0, 100 ** 100, unittest, marmalade.DOMJellier, d,
                  funktion,
                  True, False,
                  (2, 4, [2]),
@@ -338,7 +338,7 @@
         self.assertEquals(type(o), type(obj.getX))
     
     def testStringIO(self):
-        f = StringIO.StringIO()
+        f = io.StringIO()
         f.write("abc")
         pickl = pickle.dumps(f)
         o = pickle.loads(pickl)
@@ -360,7 +360,7 @@
 
 class AOTTestCase(unittest.TestCase):
     def testSimpleTypes(self):
-        obj = (1, 2.0, 3j, True, slice(1, 2, 3), 'hello', u'world', sys.maxint + 1, None, Ellipsis)
+        obj = (1, 2.0, 3j, True, slice(1, 2, 3), 'hello', 'world', sys.maxsize + 1, None, Ellipsis)
         rtObj = aot.unjellyFromSource(aot.jellyToSource(obj))
         self.assertEquals(obj, rtObj)
 
@@ -370,7 +370,7 @@
         a.bmethod = b.bmethod
         b.a = a
         im_ = aot.unjellyFromSource(aot.jellyToSource(b)).a.bmethod
-        self.assertEquals(im_.im_class, im_.im_self.__class__)
+        self.assertEquals(im_.__self__.__class__, im_.__self__.__class__)
 
 
     def test_methodNotSelfIdentity(self):
@@ -411,8 +411,8 @@
         d = {'hello': 'world', "method": aj}
         l = [1, 2, 3,
              "he\tllo\n\n\"x world!",
-             u"goodbye \n\t\u1010 world!",
-             1, 1.0, 100 ** 100l, unittest, aot.AOTJellier, d,
+             "goodbye \n\t\u1010 world!",
+             1, 1.0, 100 ** 100, unittest, aot.AOTJellier, d,
              funktion
              ]
         t = tuple(l)
@@ -431,7 +431,7 @@
 
     def testCopyReg(self):
         s = "foo_bar"
-        sio = StringIO.StringIO()
+        sio = io.StringIO()
         sio.write(s)
         uj = aot.unjellyFromSource(aot.jellyToSource(sio))
         # print repr(uj.__dict__)
--- twisted/test/test_plugin.py (original)
+++ twisted/test/test_plugin.py (refactored)
@@ -83,7 +83,7 @@
         for ext in ['c', 'o'] + (deleteSource and [''] or []):
             try:
                 os.remove(module.__file__ + ext)
-            except OSError, ose:
+            except OSError as ose:
                 if ose.errno != errno.ENOENT:
                     raise
 
@@ -305,12 +305,12 @@
         FilePath(__file__).sibling('plugin_extra1.py'
             ).copyTo(self.package.child('pluginextra.py'))
 
-        os.chmod(self.package.path, 0500)
+        os.chmod(self.package.path, 0o500)
         # Change the right of dropin.cache too for windows
-        os.chmod(self.package.child('dropin.cache').path, 0400)
-        self.addCleanup(os.chmod, self.package.path, 0700)
+        os.chmod(self.package.child('dropin.cache').path, 0o400)
+        self.addCleanup(os.chmod, self.package.path, 0o700)
         self.addCleanup(os.chmod,
-            self.package.child('dropin.cache').path, 0700)
+            self.package.child('dropin.cache').path, 0o700)
 
         cache = plugin.getCache(self.module)
         # The new plugin should be reported
@@ -416,16 +416,16 @@
         """
         Lock the system directories, as if they were unwritable by this user.
         """
-        os.chmod(self.sysplug.path, 0555)
-        os.chmod(self.syscache.path, 0555)
+        os.chmod(self.sysplug.path, 0o555)
+        os.chmod(self.syscache.path, 0o555)
 
 
     def unlockSystem(self):
         """
         Unlock the system directories, as if they were writable by this user.
         """
-        os.chmod(self.sysplug.path, 0777)
-        os.chmod(self.syscache.path, 0777)
+        os.chmod(self.sysplug.path, 0o777)
+        os.chmod(self.syscache.path, 0o777)
 
 
     def getAllPlugins(self):
--- twisted/test/test_policies.py (original)
+++ twisted/test/test_policies.py (refactored)
@@ -5,7 +5,7 @@
 Test code for policies.
 """
 
-from StringIO import StringIO
+from io import StringIO
 
 from twisted.trial import unittest
 from twisted.test.proto_helpers import StringTransportWithDisconnection
@@ -196,9 +196,9 @@
             return c3.dDisconnected
 
         def _check123(results):
-            self.assertEquals([c.connected for c in c1, c2, c3], [1, 1, 1])
-            self.assertEquals([c.disconnected for c in c1, c2, c3], [0, 0, 1])
-            self.assertEquals(len(tServer.protocols.keys()), 2)
+            self.assertEquals([c.connected for c in (c1, c2, c3)], [1, 1, 1])
+            self.assertEquals([c.disconnected for c in (c1, c2, c3)], [0, 0, 1])
+            self.assertEquals(len(list(tServer.protocols.keys())), 2)
             return results
 
         def _lose1(results):
--- twisted/test/test_process.py (original)
+++ twisted/test/test_process.py (refactored)
@@ -10,7 +10,7 @@
 import popen2
 import sys
 import signal
-import StringIO
+import io
 import errno
 import gc
 import stat
@@ -207,7 +207,7 @@
         elif childFD == 2:
             self.stages.append(3)
             if self.err != "1234":
-                print 'err != 1234: ' + repr(self.err)
+                print('err != 1234: ' + repr(self.err))
                 raise RuntimeError()
             self.transport.write("abcd")
             self.stages.append(4)
@@ -440,11 +440,11 @@
         d = {}
         while 1:
             try:
-                k = environ.next()
+                k = next(environ)
             except StopIteration:
                 break
             else:
-                v = environ.next()
+                v = next(environ)
                 d[k] = v
         return d
 
@@ -543,7 +543,7 @@
         protocols = []
         deferreds = []
 
-        for i in xrange(50):
+        for i in range(50):
             p = TestManyProcessProtocol()
             protocols.append(p)
             reactor.spawnProcess(p, exe, args, env=None)
@@ -614,7 +614,7 @@
         # Sanity check - this will fail for people who have mucked with
         # their site configuration in a stupid way, but there's nothing we
         # can do about that.
-        badUnicode = u'\N{SNOWMAN}'
+        badUnicode = '\N{SNOWMAN}'
         try:
             badUnicode.encode(sys.getdefaultencoding())
         except UnicodeEncodeError:
@@ -646,7 +646,7 @@
     # name: some versions of Windows only support upper case environment
     # variable names, and I think Python (as of 2.5) doesn't use the right
     # syscall for lowercase or mixed case names to work anyway.
-    okayUnicode = u"UNICODE"
+    okayUnicode = "UNICODE"
     encodedValue = "UNICODE"
 
     def _deprecatedUnicodeSupportTest(self, processProtocolClass, argv=[], env={}):
@@ -757,18 +757,18 @@
             self.processes[num] = p
 
     def close(self, num):
-        if self.verbose: print "closing stdin [%d]" % num
+        if self.verbose: print("closing stdin [%d]" % num)
         p = self.processes[num]
         pp = self.pp[num]
         self.failIf(pp.finished, "Process finished too early")
         p.loseConnection()
-        if self.verbose: print self.pp[0].finished, self.pp[1].finished
+        if self.verbose: print(self.pp[0].finished, self.pp[1].finished)
 
     def _onClose(self):
         return defer.gatherResults([ p.deferred for p in self.pp ])
 
     def testClose(self):
-        if self.verbose: print "starting processes"
+        if self.verbose: print("starting processes")
         self.createProcesses()
         reactor.callLater(1, self.close, 0)
         reactor.callLater(2, self.close, 1)
@@ -790,29 +790,29 @@
         return self._onClose()
 
     def kill(self, num):
-        if self.verbose: print "kill [%d] with SIGTERM" % num
+        if self.verbose: print("kill [%d] with SIGTERM" % num)
         p = self.processes[num]
         pp = self.pp[num]
         self.failIf(pp.finished, "Process finished too early")
         os.kill(p.pid, signal.SIGTERM)
-        if self.verbose: print self.pp[0].finished, self.pp[1].finished
+        if self.verbose: print(self.pp[0].finished, self.pp[1].finished)
 
     def testKill(self):
-        if self.verbose: print "starting processes"
+        if self.verbose: print("starting processes")
         self.createProcesses(usePTY=0)
         reactor.callLater(1, self.kill, 0)
         reactor.callLater(2, self.kill, 1)
         return self._onClose()
 
     def testClosePty(self):
-        if self.verbose: print "starting processes"
+        if self.verbose: print("starting processes")
         self.createProcesses(usePTY=1)
         reactor.callLater(1, self.close, 0)
         reactor.callLater(2, self.close, 1)
         return self._onClose()
 
     def testKillPty(self):
-        if self.verbose: print "starting processes"
+        if self.verbose: print("starting processes")
         self.createProcesses(usePTY=1)
         reactor.callLater(1, self.kill, 0)
         reactor.callLater(2, self.kill, 1)
@@ -939,8 +939,8 @@
     endedDeferred = None
 
     def connectionMade(self):
-        self.outF = StringIO.StringIO()
-        self.errF = StringIO.StringIO()
+        self.outF = io.StringIO()
+        self.errF = io.StringIO()
 
     def outReceived(self, d):
         self.outF.write(d)
@@ -1251,7 +1251,7 @@
         Fake C{os.fdopen}. Return a StringIO object whose content can be tested
         later via C{self.fdio}.
         """
-        self.fdio = StringIO.StringIO()
+        self.fdio = io.StringIO()
         return self.fdio
 
 
@@ -2130,10 +2130,10 @@
         for d in self.foobar, self.foobaz, self.bazfoo, self.bazbar:
             os.makedirs(d)
 
-        for name, mode in [(j(self.foobaz, "executable"), 0700),
-                           (j(self.foo, "executable"), 0700),
-                           (j(self.bazfoo, "executable"), 0700),
-                           (j(self.bazfoo, "executable.bin"), 0700),
+        for name, mode in [(j(self.foobaz, "executable"), 0o700),
+                           (j(self.foo, "executable"), 0o700),
+                           (j(self.bazfoo, "executable"), 0o700),
+                           (j(self.bazfoo, "executable.bin"), 0o700),
                            (j(self.bazbar, "executable"), 0)]:
             f = file(name, "w")
             f.close()
--- twisted/test/test_protocols.py (original)
+++ twisted/test/test_protocols.py (refactored)
@@ -12,9 +12,9 @@
 from twisted.test import proto_helpers
 
 import struct
-import StringIO
-
-class StringIOWithoutClosing(StringIO.StringIO):
+import io
+
+class StringIOWithoutClosing(io.StringIO):
     """
     A StringIO that can't be closed.
     """
@@ -750,4 +750,4 @@
         Test that L{proto_helpers.StringTransport} doesn't accept unicode data.
         """
         s = proto_helpers.StringTransport()
-        self.assertRaises(TypeError, s.write, u'foo')
+        self.assertRaises(TypeError, s.write, 'foo')
--- twisted/test/test_rebuild.py (original)
+++ twisted/test/test_rebuild.py (refactored)
@@ -8,7 +8,7 @@
 from twisted.trial import unittest
 from twisted.python import rebuild
 
-import crash_test_dummy
+from . import crash_test_dummy
 f = crash_test_dummy.foo
 
 class Foo: pass
@@ -149,10 +149,10 @@
             "class SlottedClass(object):\n"
             "    __slots__ = ['a']\n")
 
-        exec classDefinition in self.m.__dict__
+        exec(classDefinition, self.m.__dict__)
         inst = self.m.SlottedClass()
         inst.a = 7
-        exec classDefinition in self.m.__dict__
+        exec(classDefinition, self.m.__dict__)
         rebuild.updateInstance(inst)
         self.assertEqual(inst.a, 7)
         self.assertIdentical(type(inst), self.m.SlottedClass)
@@ -169,10 +169,10 @@
             "class SlottedClass(object):\n"
             "    __slots__ = ['a']\n")
 
-        exec classDefinition in self.m.__dict__
+        exec(classDefinition, self.m.__dict__)
         inst = self.m.SlottedClass()
         inst.a = 7
-        exec classDefinition in self.m.__dict__
+        exec(classDefinition, self.m.__dict__)
         self.assertRaises(rebuild.RebuildError, rebuild.updateInstance, inst)
 
     if sys.version_info >= (2, 6):
@@ -187,10 +187,10 @@
             "class ListSubclass(list):\n"
             "    pass\n")
 
-        exec classDefinition in self.m.__dict__
+        exec(classDefinition, self.m.__dict__)
         inst = self.m.ListSubclass()
         inst.append(2)
-        exec classDefinition in self.m.__dict__
+        exec(classDefinition, self.m.__dict__)
         rebuild.updateInstance(inst)
         self.assertEqual(inst[0], 2)
         self.assertIdentical(type(inst), self.m.ListSubclass)
@@ -205,13 +205,13 @@
             "class NotSlottedClass(object):\n"
             "    pass\n")
 
-        exec classDefinition in self.m.__dict__
+        exec(classDefinition, self.m.__dict__)
         inst = self.m.NotSlottedClass()
         inst.__slots__ = ['a']
         classDefinition = (
             "class NotSlottedClass:\n"
             "    pass\n")
-        exec classDefinition in self.m.__dict__
+        exec(classDefinition, self.m.__dict__)
         # Moving from new-style class to old-style should fail.
         self.assertRaises(TypeError, rebuild.updateInstance, inst)
 
--- twisted/test/test_reflect.py (original)
+++ twisted/test/test_reflect.py (refactored)
@@ -377,9 +377,9 @@
         o = Dummy()
         m = o.dummy
 
-        self.assertIn(".im_self", reflect.objgrep(m, m.im_self, reflect.isSame))
-        self.assertIn(".im_class", reflect.objgrep(m, m.im_class, reflect.isSame))
-        self.assertIn(".im_func", reflect.objgrep(m, m.im_func, reflect.isSame))
+        self.assertIn(".im_self", reflect.objgrep(m, m.__self__, reflect.isSame))
+        self.assertIn(".im_class", reflect.objgrep(m, m.__self__.__class__, reflect.isSame))
+        self.assertIn(".im_func", reflect.objgrep(m, m.__func__, reflect.isSame))
 
     def test_everything(self):
         """
@@ -476,8 +476,7 @@
 
 
 
-class BTBase(Breakable):
-    __metaclass__ = BrokenType
+class BTBase(Breakable, metaclass=BrokenType):
     breakRepr = True
     breakStr = True
 
--- twisted/test/test_reflector.py (original)
+++ twisted/test/test_reflector.py (refactored)
@@ -82,8 +82,7 @@
             if random.randint(0, 9) == 0:
                 value = ''
             else:
-                value = ''.join(map(lambda i:chr(random.randrange(32,127)),
-                                    xrange(random.randint(1, 64))))
+                value = ''.join([chr(random.randrange(32,127)) for i in range(random.randint(1, 64))])
             if not trailing_spaces_ok:
                 value = value.rstrip()
         setattr(row, name, value)
@@ -94,8 +93,8 @@
 def rowMatches(row, values):
     for name, type in row.rowColumns:
         if getattr(row, name) != values[name]:
-            print ("Mismatch on column %s: |%s| (row) |%s| (values)" %
-                   (name, getattr(row, name), values[name]))
+            print(("Mismatch on column %s: |%s| (row) |%s| (values)" %
+                   (name, getattr(row, name), values[name])))
             return False
     return True
 
--- twisted/test/test_roots.py (original)
+++ twisted/test/test_roots.py (refactored)
@@ -55,7 +55,7 @@
 
     def testHomogenous(self):
         h = roots.Homogenous()
-        h.entityType = types.IntType
+        h.entityType = int
         h.putEntity('a', 1)
         self.failUnlessEqual(h.getStaticEntity('a'),1 )
         self.failUnlessRaises(roots.ConstraintViolation,
--- twisted/test/test_sip.py (original)
+++ twisted/test/test_sip.py (refactored)
@@ -421,7 +421,7 @@
         self.proxy.sendMessage = lambda dest, msg: self.sent.append((dest, msg))
 
     def tearDown(self):
-        for d, uri in self.registry.users.values():
+        for d, uri in list(self.registry.users.values()):
             d.cancel()
         del self.proxy
 
@@ -580,7 +580,7 @@
                               self.serverPort.getHost().port)
 
     def tearDown(self):
-        for d, uri in self.registry.users.values():
+        for d, uri in list(self.registry.users.values()):
             d.cancel()
         d1 = defer.maybeDeferred(self.clientPort.stopListening)
         d2 = defer.maybeDeferred(self.serverPort.stopListening)
@@ -693,7 +693,7 @@
 
     def _cbReg(self, reg):
         if 3600 < reg.secondsToExpiry or reg.secondsToExpiry < 3598:
-            raise RuntimeError, "bad seconds to expire: %s" % reg.secondsToExpiry
+            raise RuntimeError("bad seconds to expire: %s" % reg.secondsToExpiry)
         reg.secondsToExpiry = 3600
         return reg
 
@@ -721,7 +721,7 @@
         self.proxy.portal = p
 
     def tearDown(self):
-        for d, uri in self.registry.users.values():
+        for d, uri in list(self.registry.users.values()):
             d.cancel()
         del self.proxy
     
--- twisted/test/test_split_compat.py (original)
+++ twisted/test/test_split_compat.py (refactored)
@@ -25,7 +25,7 @@
             try:
                 old = reflect.namedModule(oldName)
                 new = reflect.namedModule(newName)
-            except ImportError, e:
+            except ImportError as e:
                 continue
             for someName in vars(new):
                 if someName == '__doc__':
--- twisted/test/test_sslverify.py (original)
+++ twisted/test/test_sslverify.py (refactored)
@@ -70,7 +70,7 @@
 
 
 
-counter = itertools.count().next
+counter = itertools.count().__next__
 def makeCertificate(**kw):
     keypair = PKey()
     keypair.generate_key(TYPE_RSA, 512)
@@ -79,7 +79,7 @@
     certificate.gmtime_adj_notBefore(0)
     certificate.gmtime_adj_notAfter(60 * 60 * 24 * 365) # One year
     for xname in certificate.get_issuer(), certificate.get_subject():
-        for (k, v) in kw.items():
+        for (k, v) in list(kw.items()):
             setattr(xname, k, v)
 
     certificate.set_serial_number(counter())
@@ -346,8 +346,9 @@
                                consumeErrors=True)
 
 
-        def afterLost(((cSuccess, cResult), (sSuccess, sResult))):
-
+        def afterLost(xxx_todo_changeme):
+
+            ((cSuccess, cResult), (sSuccess, sResult)) = xxx_todo_changeme
             self.failIf(cSuccess)
             self.failIf(sSuccess)
             # Win32 fails to report the SSL Error, and report a connection lost
@@ -375,8 +376,9 @@
 
         d = defer.DeferredList([onClientLost, onServerLost],
                                consumeErrors=True)
-        def afterLost(((cSuccess, cResult), (sSuccess, sResult))):
-
+        def afterLost(xxx_todo_changeme1):
+
+            ((cSuccess, cResult), (sSuccess, sResult)) = xxx_todo_changeme1
             self.failIf(cSuccess)
             self.failIf(sSuccess)
 
--- twisted/test/test_stdio.py (original)
+++ twisted/test/test_stdio.py (refactored)
@@ -144,7 +144,7 @@
             self._spawnProcess(
                 p, 'stdio_test_lastwrite.py', UNIQUE_LAST_WRITE_STRING,
                 usePTY=True)
-        except ValueError, e:
+        except ValueError as e:
             # Some platforms don't work with usePTY=True
             raise unittest.SkipTest(str(e))
 
@@ -213,7 +213,7 @@
     def _junkPath(self):
         junkPath = self.mktemp()
         junkFile = file(junkPath, 'w')
-        for i in xrange(1024):
+        for i in range(1024):
             junkFile.write(str(i) + '\n')
         junkFile.close()
         return junkPath
@@ -228,7 +228,7 @@
         d = p.onCompletion
 
         written = []
-        toWrite = range(100)
+        toWrite = list(range(100))
 
         def connectionMade(ign):
             if toWrite:
--- twisted/test/test_strcred.py (original)
+++ twisted/test/test_strcred.py (refactored)
@@ -6,7 +6,7 @@
 """
 
 import os
-import StringIO
+import io
 
 from twisted import plugin
 from twisted.trial import unittest
@@ -325,7 +325,7 @@
         should produce a warning.
         """
         oldOutput = cred_file.theFileCheckerFactory.errorOutput
-        newOutput = StringIO.StringIO()
+        newOutput = io.StringIO()
         cred_file.theFileCheckerFactory.errorOutput = newOutput
         checker = strcred.makeChecker('file:' + self._fakeFilename())
         cred_file.theFileCheckerFactory.errorOutput = oldOutput
@@ -421,7 +421,7 @@
         Test that the --help-auth argument correctly displays all
         available authentication plugins, then exits.
         """
-        newStdout = StringIO.StringIO()
+        newStdout = io.StringIO()
         options = DummyOptions()
         options.authOutput = newStdout
         self.assertRaises(SystemExit, options.parseOptions, ['--help-auth'])
@@ -434,7 +434,7 @@
         Test that the --help-auth-for argument will correctly display
         the help file for a particular authentication plugin.
         """
-        newStdout = StringIO.StringIO()
+        newStdout = io.StringIO()
         options = DummyOptions()
         options.authOutput = newStdout
         self.assertRaises(
@@ -615,7 +615,7 @@
                 break
         self.assertNotIdentical(invalidFactory, None)
         # Capture output and make sure the warning is there
-        newStdout = StringIO.StringIO()
+        newStdout = io.StringIO()
         options.authOutput = newStdout
         self.assertRaises(SystemExit, options.parseOptions,
                           ['--help-auth-type', 'anonymous'])
--- twisted/test/test_strports.py (original)
+++ twisted/test/test_strports.py (refactored)
@@ -37,7 +37,7 @@
         self.assertEqual(
             strports.parse('unix:/var/run/finger', self.f),
             ('UNIX', ('/var/run/finger', self.f),
-             {'mode': 0666, 'backlog': 50, 'wantPID': True}))
+             {'mode': 0o666, 'backlog': 50, 'wantPID': True}))
 
 
     def test_modeUNIX(self):
@@ -47,7 +47,7 @@
         self.assertEqual(
             strports.parse('unix:/var/run/finger:mode=0660', self.f),
             ('UNIX', ('/var/run/finger', self.f),
-             {'mode': 0660, 'backlog': 50, 'wantPID': True}))
+             {'mode': 0o660, 'backlog': 50, 'wantPID': True}))
 
 
     def test_wantPIDUNIX(self):
@@ -57,7 +57,7 @@
         self.assertEqual(
             strports.parse('unix:/var/run/finger:lockfile=0', self.f),
             ('UNIX', ('/var/run/finger', self.f),
-             {'mode': 0666, 'backlog': 50, 'wantPID': False}))
+             {'mode': 0o666, 'backlog': 50, 'wantPID': False}))
 
 
     def testAllKeywords(self):
@@ -68,17 +68,17 @@
         self.assertEqual(
             strports.parse(r'unix:foo\:bar\=baz\:qux\\', self.f),
             ('UNIX', ('foo:bar=baz:qux\\', self.f),
-             {'mode': 0666, 'backlog': 50, 'wantPID': True}))
+             {'mode': 0o666, 'backlog': 50, 'wantPID': True}))
 
 
     def testImpliedEscape(self):
         self.assertEqual(
             strports.parse(r'unix:address=foo=bar', self.f),
             ('UNIX', ('foo=bar', self.f),
-             {'mode': 0666, 'backlog': 50, 'wantPID': True}))
+             {'mode': 0o666, 'backlog': 50, 'wantPID': True}))
 
     def testNonstandardDefault(self):
         self.assertEqual(
             strports.parse('filename', self.f, 'unix'),
             ('UNIX', ('filename', self.f),
-             {'mode': 0666, 'backlog': 50, 'wantPID': True}))
+             {'mode': 0o666, 'backlog': 50, 'wantPID': True}))
--- twisted/test/test_tcp.py (original)
+++ twisted/test/test_tcp.py (refactored)
@@ -239,7 +239,8 @@
         connector = reactor.connectTCP("127.0.0.1",
                                        port.getHost().port, client)
         self.addCleanup(connector.disconnect)
-        def check((serverProto, clientProto)):
+        def check(xxx_todo_changeme):
+            (serverProto, clientProto) = xxx_todo_changeme
             portNumber = port.getHost().port
             self.assertEquals(repr(serverProto.transport),
                               "<MyProtocol #0 on %s>" % (portNumber,))
@@ -271,7 +272,8 @@
                                         client.protocolConnectionMade]
                 ).addCallback(close)
 
-        def close((serverProto, clientProto)):
+        def close(xxx_todo_changeme1):
+            (serverProto, clientProto) = xxx_todo_changeme1
             clientProto.transport.loseConnection()
             serverProto.transport.loseConnection()
 
@@ -322,7 +324,8 @@
                                         client.protocolConnectionMade]
                 ).addCallback(close)
 
-        def close((serverProto, clientProto)):
+        def close(xxx_todo_changeme2):
+            (serverProto, clientProto) = xxx_todo_changeme2
             clientProto.transport.loseConnection()
             serverProto.transport.loseConnection()
 
@@ -421,7 +424,8 @@
         reactor.connectTCP("127.0.0.1", portNumber, clientF)
 
         connsMade = defer.gatherResults([serverConnMade, clientConnMade])
-        def connected((serverProtocol, clientProtocol)):
+        def connected(xxx_todo_changeme3):
+            (serverProtocol, clientProtocol) = xxx_todo_changeme3
             callback(serverProtocol, clientProtocol)
             serverProtocol.transport.loseConnection()
             clientProtocol.transport.loseConnection()
@@ -500,7 +504,7 @@
         # unbounded number of connections succeed.
 
         serverSockets = []
-        for i in xrange(10):
+        for i in range(10):
             serverSocket = socket.socket()
             serverSocket.bind(('127.0.0.1', 0))
             serverSocket.listen(1)
@@ -576,7 +580,8 @@
         c = reactor.connectTCP('127.0.0.1', 'http', clientFactory)
 
         connMade = defer.gatherResults([serverConnMade, clientConnMade])
-        def connected((serverProtocol, clientProtocol)):
+        def connected(xxx_todo_changeme4):
+            (serverProtocol, clientProtocol) = xxx_todo_changeme4
             self.assertTrue(
                 serverFactory.called,
                 "Server factory was not called upon to build a protocol.")
@@ -943,11 +948,11 @@
         self.transport.writeSequence(seq)
         peer = self.transport.getPeer()
         if peer.type != "TCP":
-            print "getPeer returned non-TCP socket:", peer
+            print("getPeer returned non-TCP socket:", peer)
             self.factory.problem = 1
         us = self.transport.getHost()
         if us.type != "TCP":
-            print "getHost returned non-TCP socket:", us
+            print("getHost returned non-TCP socket:", us)
             self.factory.problem = 1
         self.factory.done = 1
 
@@ -1281,11 +1286,12 @@
                 onClientConnectionLost, onServerConnectionLost])
         clientDeferred.addCallback(clientConnected)
 
-        def clientDisconnected((client, server)):
+        def clientDisconnected(xxx_todo_changeme5):
             """
             Verify that the underlying platform socket handle has been
             cleaned up.
             """
+            (client, server) = xxx_todo_changeme5
             client.lostConnectionReason.trap(error.ConnectionClosed)
             server.lostConnectionReason.trap(error.ConnectionClosed)
             expectedErrorCode = self.getHandleErrorCode()
--- twisted/test/test_tcp_internals.py (original)
+++ twisted/test/test_tcp_internals.py (refactored)
@@ -71,10 +71,10 @@
         port.listen(5)
 
         # Use up all the file descriptors
-        for i in xrange(self.socketLimit):
+        for i in range(self.socketLimit):
             try:
                 self.socket()
-            except socket.error, e:
+            except socket.error as e:
                 if e.args[0] in (EMFILE, ENOBUFS):
                     self.openSockets.pop().close()
                     break
--- twisted/test/test_text.py (original)
+++ twisted/test/test_text.py (refactored)
@@ -6,7 +6,7 @@
 from twisted.trial import unittest
 from twisted.python import text
 import string
-from cStringIO import StringIO
+from io import StringIO
 
 sampleText = \
 """Every attempt to employ mathematical methods in the study of chemical
--- twisted/test/test_threadable.py (original)
+++ twisted/test/test_threadable.py (refactored)
@@ -19,7 +19,7 @@
     y = 1
 
     def aMethod(self):
-        for i in xrange(10):
+        for i in range(10):
             self.x, self.y = self.y, self.x
             self.z = self.x + self.y
             assert self.z == 0, "z == %d, not 0 as expected" % (self.z,)
@@ -62,9 +62,9 @@
 
         def callMethodLots():
             try:
-                for i in xrange(1000):
+                for i in range(1000):
                     o.aMethod()
-            except AssertionError, e:
+            except AssertionError as e:
                 errors.append(str(e))
 
         threads = []
@@ -81,7 +81,7 @@
 
     def testUnthreadedSynchronization(self):
         o = TestObject()
-        for i in xrange(1000):
+        for i in range(1000):
             o.aMethod()
 
 class SerializationTestCase(unittest.TestCase):
--- twisted/test/test_threadpool.py (original)
+++ twisted/test/test_threadpool.py (refactored)
@@ -57,7 +57,7 @@
     Test threadpools.
     """
     def _waitForLock(self, lock):
-        for i in xrange(1000000):
+        for i in range(1000000):
             if lock.acquire(False):
                 break
             time.sleep(1e-5)
@@ -237,7 +237,7 @@
         waiting.acquire()
         actor = Synchronization(N, waiting)
 
-        for i in xrange(N):
+        for i in range(N):
             method(tp, actor)
 
         self._waitForLock(waiting)
@@ -394,16 +394,16 @@
         """
         threadIds = []
 
-        import thread
+        import _thread
 
         event = threading.Event()
 
         def onResult(success, result):
-            threadIds.append(thread.get_ident())
+            threadIds.append(_thread.get_ident())
             event.set()
 
         def func():
-            threadIds.append(thread.get_ident())
+            threadIds.append(_thread.get_ident())
 
         tp = threadpool.ThreadPool(0, 1)
         tp.callInThreadWithCallback(onResult, func)
--- twisted/test/test_threads.py (original)
+++ twisted/test/test_threads.py (refactored)
@@ -91,7 +91,7 @@
             def threadedFunction():
                 # Hopefully a hundred thousand queued calls is enough to
                 # trigger the error condition
-                for i in xrange(100000):
+                for i in range(100000):
                     try:
                         reactor.callFromThread(lambda: None)
                     except:
@@ -117,7 +117,7 @@
             def threadedFunc():
                 try:
                     r = threads.blockingCallFromThread(reactor, reactorFunc)
-                except Exception, e:
+                except Exception as e:
                     errors.append(e)
                 else:
                     results.append(r)
@@ -226,11 +226,11 @@
         d = defer.Deferred()
 
         def finished():
-            self.assertEquals(L, range(N))
+            self.assertEquals(L, list(range(N)))
             d.callback(None)
 
         threads.callMultipleInThread([
-            (L.append, (i,), {}) for i in xrange(N)
+            (L.append, (i,), {}) for i in range(N)
             ] + [(reactor.callFromThread, (finished,), {})])
         return d
 
@@ -377,7 +377,8 @@
         progfile.write(_callBeforeStartupProgram % {'reactor': reactor.__module__})
         progfile.close()
 
-        def programFinished((out, err, reason)):
+        def programFinished(xxx_todo_changeme):
+            (out, err, reason) = xxx_todo_changeme
             if reason.check(error.ProcessTerminated):
                 self.fail("Process did not exit cleanly (out: %s err: %s)" % (out, err))
 
--- twisted/test/test_tpfile.py (original)
+++ twisted/test/test_tpfile.py (refactored)
@@ -8,7 +8,7 @@
 from twisted.protocols import basic
 from twisted.internet import protocol, abstract
 
-import StringIO
+import io
 
 class BufferingServer(protocol.Protocol):
     buffer = ''
@@ -28,7 +28,7 @@
     def testSendingFile(self):
         testStr = 'xyz' * 100 + 'abc' * 100 + '123' * 100
         s = BufferingServer()
-        c = FileSendingClient(StringIO.StringIO(testStr))
+        c = FileSendingClient(io.StringIO(testStr))
         
         d = loopback.loopbackTCP(s, c)
         d.addCallback(lambda x : self.assertEquals(s.buffer, testStr))
@@ -38,7 +38,7 @@
         fileSender = basic.FileSender()
         consumer = abstract.FileDescriptor()
         consumer.connected = 1
-        emptyFile = StringIO.StringIO('')
+        emptyFile = io.StringIO('')
 
         d = fileSender.beginFileTransfer(emptyFile, consumer, lambda x: x)
 
--- twisted/test/test_twistd.py (original)
+++ twisted/test/test_twistd.py (refactored)
@@ -7,7 +7,7 @@
 
 import signal, inspect
 
-import os, sys, cPickle, StringIO
+import os, sys, pickle, StringIO
 try:
     import pwd, grp
 except ImportError:
@@ -243,7 +243,7 @@
         """
         self.tapfile = self.mktemp()
         f = file(self.tapfile, 'wb')
-        cPickle.dump(service.Application("Hi!"), f)
+        pickle.dump(service.Application("Hi!"), f)
         f.close()
 
 
@@ -639,7 +639,7 @@
         passed for the C{nodaemon} parameter.
         """
         self.runner.setupEnvironment(None, ".", False, None, None)
-        self.assertEqual(self.mask, 0077)
+        self.assertEqual(self.mask, 0o077)
 
 
 
--- twisted/test/test_udp.py (original)
+++ twisted/test/test_udp.py (refactored)
@@ -471,7 +471,7 @@
         # stub out the socket with a fake one which could be made to behave in
         # whatever way the test desires.  Unfortunately, this is hard because
         # of differences in various reactor implementations.
-        attempts = range(60)
+        attempts = list(range(60))
         succeededAttempts = []
 
         def makeAttempt():
@@ -796,6 +796,6 @@
         if s.startswith("Linux version"):
             s = s.split()[2]
             if s.split(".")[:2] == ["2", "2"]:
-                f = MulticastTestCase.testInterface.im_func
+                f = MulticastTestCase.testInterface.__func__
                 f.todo = "figure out why this fails in linux 2.2"
 checkForLinux22()
--- twisted/test/test_unix.py (original)
+++ twisted/test/test_unix.py (refactored)
@@ -68,10 +68,11 @@
         clientFactory.protocolConnectionMade = clientConnMade
         c = reactor.connectUNIX(filename, clientFactory)
         d = defer.gatherResults([serverConnMade, clientConnMade])
-        def allConnected((serverProtocol, clientProtocol)):
+        def allConnected(xxx_todo_changeme):
 
             # Incidental assertion which may or may not be redundant with some
             # other test.  This probably deserves its own test method.
+            (serverProtocol, clientProtocol) = xxx_todo_changeme
             self.assertEqual(clientFactory.peerAddresses,
                              [address.UNIXAddress(filename)])
 
@@ -103,10 +104,11 @@
         c = reactor.connectUNIX(filename, clientFactory, checkPID=1)
 
         d = defer.gatherResults([serverConnMade, clientConnMade])
-        def _portStuff((serverProtocol, clientProto)):
+        def _portStuff(xxx_todo_changeme1):
 
             # Incidental assertion which may or may not be redundant with some
             # other test.  This probably deserves its own test method.
+            (serverProtocol, clientProto) = xxx_todo_changeme1
             self.assertEqual(clientFactory.peerAddresses,
                              [address.UNIXAddress(filename)])
 
@@ -216,7 +218,7 @@
                 pass
 
         # Sanity check
-        self.assertIsInstance(ClassicFactory, types.ClassType)
+        self.assertIsInstance(ClassicFactory, type)
 
         return self._reprTest(
             ClassicFactory(), "twisted.test.test_unix.ClassicFactory")
@@ -371,7 +373,7 @@
                 pass
 
         # Sanity check
-        self.assertIsInstance(ClassicProtocol, types.ClassType)
+        self.assertIsInstance(ClassicProtocol, type)
 
         return self._reprTest(
             ClassicProtocol(), "twisted.test.test_unix.ClassicProtocol")
--- twisted/test/test_usage.py (original)
+++ twisted/test/test_usage.py (refactored)
@@ -331,7 +331,7 @@
         """
         try:
             self.nice.__str__()
-        except Exception, e:
+        except Exception as e:
             self.fail(e)
 
     def test_whitespaceStripFlagsAndParameters(self):
--- twisted/test/test_zshcomp.py (original)
+++ twisted/test/test_zshcomp.py (refactored)
@@ -6,7 +6,7 @@
 """
 
 import os, os.path
-from cStringIO import StringIO
+from io import StringIO
 
 from twisted.trial import unittest
 from twisted.python import zshcomp, usage
--- twisted/test/testutils.py (original)
+++ twisted/test/testutils.py (refactored)
@@ -1,4 +1,4 @@
-from cStringIO import StringIO
+from io import StringIO
 from twisted.internet.protocol import FileWrapper
 
 class IOPump:
--- twisted/test/threading_latency.py (original)
+++ twisted/test/threading_latency.py (refactored)
@@ -23,19 +23,19 @@
             reactor.iterate(1.0)
 
     def printResult(self):
-        print
-        print
-        print "callFromThread latency:"
+        print()
+        print()
+        print("callFromThread latency:")
         sum = 0
         for t in self.from_times: sum += t
-        print "%f millisecond" % ((sum / self.numRounds) * 1000)
+        print("%f millisecond" % ((sum / self.numRounds) * 1000))
 
-        print "callInThread latency:"
+        print("callInThread latency:")
         sum = 0
         for t in self.in_times: sum += t
-        print "%f millisecond" % ((sum / self.numRounds) * 1000)
-        print
-        print
+        print("%f millisecond" % ((sum / self.numRounds) * 1000))
+        print()
+        print()
     
     def testCallFromThread(self):
         for i in range(self.numRounds):
--- twisted/topfiles/setup.py (original)
+++ twisted/topfiles/setup.py (refactored)
@@ -11,7 +11,7 @@
 import os, sys
 
 if sys.version_info < (2,3):
-    print >>sys.stderr, "You must use at least Python 2.3 for Twisted"
+    print("You must use at least Python 2.3 for Twisted", file=sys.stderr)
     sys.exit(3)
 
 if os.path.exists('twisted'):
--- twisted/trial/reporter.py (original)
+++ twisted/trial/reporter.py (refactored)
@@ -963,7 +963,7 @@
         if len(segments) == 0:
             return segments
         segments = [
-            seg for seg in '.'.join(segments[:-1]), segments[-1]
+            seg for seg in ('.'.join(segments[:-1]), segments[-1])
             if len(seg) > 0]
         return segments
 
--- twisted/trial/runner.py (original)
+++ twisted/trial/runner.py (refactored)
@@ -489,7 +489,7 @@
         Given a class which contains test cases, return a sorted list of
         C{TestCase} instances.
         """
-        if not (isinstance(klass, type) or isinstance(klass, types.ClassType)):
+        if not (isinstance(klass, type) or isinstance(klass, type)):
             raise TypeError("%r is not a class" % (klass,))
         if not isTestCase(klass):
             raise ValueError("%r is not a test case" % (klass,))
@@ -513,7 +513,7 @@
         """
         if not isinstance(method, types.MethodType):
             raise TypeError("%r not a method" % (method,))
-        return self._makeCase(method.im_class, method.__name__)
+        return self._makeCase(method.__self__.__class__, method.__name__)
 
     def _makeCase(self, klass, methodName):
         return klass(methodName)
@@ -603,7 +603,7 @@
             if isPackage(thing):
                 return self.loadPackage(thing, recurse)
             return self.loadModule(thing)
-        elif isinstance(thing, types.ClassType):
+        elif isinstance(thing, type):
             return self.loadClass(thing)
         elif isinstance(thing, type):
             return self.loadClass(thing)
@@ -686,7 +686,7 @@
         try:
             import readline
         except ImportError:
-            print "readline module not available"
+            print("readline module not available")
             hasattr(sys, 'exc_clear') and sys.exc_clear()
         for path in ('.pdbrc', 'pdbrc'):
             if os.path.exists(path):
@@ -702,16 +702,16 @@
     def _removeSafely(self, path):
         try:
             shutil.rmtree(path)
-        except OSError, e:
-            print ("could not remove %r, caught OSError [Errno %s]: %s"
-                   % (path, e.errno,e.strerror))
+        except OSError as e:
+            print(("could not remove %r, caught OSError [Errno %s]: %s"
+                   % (path, e.errno,e.strerror)))
             try:
                 os.rename(path,
                           os.path.abspath("_trial_temp_old%s"
                                           % random.randint(0, 99999999)))
-            except OSError, e:
-                print ("could not rename path, caught OSError [Errno %s]: %s"
-                       % (e.errno,e.strerror))
+            except OSError as e:
+                print(("could not rename path, caught OSError [Errno %s]: %s"
+                       % (e.errno,e.strerror)))
                 raise
 
 
--- twisted/trial/unittest.py (original)
+++ twisted/trial/unittest.py (refactored)
@@ -153,7 +153,7 @@
     # Disable the per-module cache for every module otherwise if the warning
     # which the caller is expecting us to collect was already emitted it won't
     # be re-emitted by the call to f which happens below.
-    for v in sys.modules.itervalues():
+    for v in sys.modules.values():
         if v is not None:
             try:
                 v.__warningregistry__ = None
@@ -233,7 +233,7 @@
         """
         try:
             result = f(*args, **kwargs)
-        except exception, inst:
+        except exception as inst:
             return inst
         except:
             raise self.failureException('%s raised instead of %s:\n %s'
@@ -973,7 +973,7 @@
 
         @param reactor: The Twisted reactor.
         """
-        for name, method in self._reactorMethods.iteritems():
+        for name, method in self._reactorMethods.items():
             setattr(reactor, name, method)
         self._reactorMethods = {}
 
@@ -1064,7 +1064,7 @@
                     toFlush.append(w)
                     break
             # Remove everything which is being flushed.
-            map(self._warnings.remove, toFlush)
+            list(map(self._warnings.remove, toFlush))
 
         return [
             {'message': w.message, 'category': w.category,
--- twisted/trial/util.py (original)
+++ twisted/trial/util.py (refactored)
@@ -177,7 +177,7 @@
                 delayedString = str(p)
                 p.cancel()
             else:
-                print "WEIRDNESS! pending timed call not active!"
+                print("WEIRDNESS! pending timed call not active!")
             delayedCallStrings.append(delayedString)
         return delayedCallStrings
     _cleanPending = utils.suppressWarnings(
@@ -268,8 +268,8 @@
     """Walk up the Python tree from method 'meth', finding its class, its module
     and all containing packages."""
     containers = []
-    containers.append(meth.im_class)
-    moduleName = meth.im_class.__module__
+    containers.append(meth.__self__.__class__)
+    moduleName = meth.__self__.__class__.__module__
     while moduleName is not None:
         module = sys.modules.get(moduleName, None)
         if module is None:
@@ -321,7 +321,7 @@
                 except KeyError:
                     # Python 2.4 has fixed this.  Yay!
                     pass
-                raise exc_info[0], exc_info[1], exc_info[2]
+                raise exc_info[0](exc_info[1]).with_traceback(exc_info[2])
             moduleNames.pop()
     obj = topLevelPackage
     for n in names[1:]:
--- twisted/trial/test/detests.py (original)
+++ twisted/trial/test/detests.py (refactored)
@@ -1,4 +1,4 @@
-from __future__ import generators
+
 from twisted.trial import unittest
 from twisted.internet import defer, threads, reactor
 
--- twisted/trial/test/erroneous.py (original)
+++ twisted/trial/test/erroneous.py (refactored)
@@ -9,7 +9,7 @@
 
 class TestFailureInSetUp(unittest.TestCase):
     def setUp(self):
-        raise FoolishError, "I am a broken setUp method"
+        raise FoolishError("I am a broken setUp method")
 
     def test_noop(self):
         pass
@@ -17,7 +17,7 @@
 
 class TestFailureInTearDown(unittest.TestCase):
     def tearDown(self):
-        raise FoolishError, "I am a broken tearDown method"
+        raise FoolishError("I am a broken tearDown method")
 
     def test_noop(self):
         pass
@@ -27,7 +27,7 @@
     _suppressUpDownWarning = True
 
     def setUpClass(self):
-        raise FoolishError, "I am a broken setUpClass method"
+        raise FoolishError("I am a broken setUpClass method")
 
     def test_noop(self):
         pass
@@ -37,7 +37,7 @@
     _suppressUpDownWarning = True
 
     def tearDownClass(self):
-        raise FoolishError, "I am a broken setUp method"
+        raise FoolishError("I am a broken setUp method")
 
     def test_noop(self):
         pass
@@ -91,7 +91,7 @@
     _suppressUpDownWarning = True
 
     def setUpClass(self):
-        raise unittest.SkipTest, "thi stest is fukct"
+        raise unittest.SkipTest("thi stest is fukct")
 
     def test_thisTestWillBeSkipped(self):
         pass
@@ -126,7 +126,7 @@
 class ReactorCleanupTests(unittest.TestCase):
     def test_leftoverPendingCalls(self):
         def _():
-            print 'foo!'
+            print('foo!')
         reactor.callLater(10000.0, _)
 
 class SocketOpenTest(unittest.TestCase):
--- twisted/trial/test/mockdoctest.py (original)
+++ twisted/trial/test/mockdoctest.py (refactored)
@@ -38,7 +38,7 @@
              True
         """
         if self.maxval is not None and ((self._count + other) > self.maxval):
-            raise ValueError, "sorry, counter got too big"
+            raise ValueError("sorry, counter got too big")
         else:
             self._count += other
         return self
--- twisted/trial/test/packages.py (original)
+++ twisted/trial/test/packages.py (refactored)
@@ -81,7 +81,7 @@
         return '.'.join(segs)
 
     def getModules(self):
-        return map(self._toModuleName, zip(*self.files)[0])
+        return list(map(self._toModuleName, zip(*self.files)[0]))
 
     def cleanUpModules(self):
         modules = self.getModules()
--- twisted/trial/test/test_assertions.py (original)
+++ twisted/trial/test/test_assertions.py (refactored)
@@ -5,7 +5,7 @@
 Tests for assertions provided by L{twisted.trial.unittest.TestCase}.
 """
 
-import warnings, StringIO
+import warnings, io
 from pprint import pformat
 
 from twisted.python import reflect, failure
@@ -43,7 +43,7 @@
     def testFail(self):
         try:
             self.fail("failed")
-        except self.failureException, e:
+        except self.failureException as e:
             if not str(e) == 'failed':
                 raise self.failureException("Exception had msg %s instead of %s"
                                             % str(e), 'failed')
@@ -52,7 +52,7 @@
 
     def test_failingException_fails(self):
         test = runner.TestLoader().loadClass(TestAssertions.FailingTest)
-        io = StringIO.StringIO()
+        io = io.StringIO()
         result = reporter.TestResult()
         test.run(result)
         self.failIf(result.wasSuccessful())
@@ -65,7 +65,7 @@
         for true in [1, True, 'cat', [1,2], (3,4)]:
             try:
                 self.failIf(true, "failed on %r" % (true,))
-            except self.failureException, e:
+            except self.failureException as e:
                 self.failUnlessEqual(str(e), "failed on %r" % (true,))
             else:
                 self.fail("Call to failIf(%r) didn't fail" % (true,))
@@ -74,7 +74,7 @@
         for notTrue in [0, 0.0, False, None, (), []]:
             try:
                 self.failUnless(notTrue, "failed on %r" % (notTrue,))
-            except self.failureException, e:
+            except self.failureException as e:
                 self.failUnlessEqual(str(e), "failed on %r" % (notTrue,))
             else:
                 self.fail("Call to failUnless(%r) didn't fail" % (notTrue,))
@@ -89,7 +89,7 @@
     def _testUnequalPair(self, first, second):
         try:
             self.failUnlessEqual(first, second)
-        except self.failureException, e:
+        except self.failureException as e:
             expected = 'not equal:\na = %s\nb = %s\n' % (
                 pformat(first), pformat(second))
             if str(e) != expected:
@@ -165,7 +165,7 @@
         except TypeError:
             self.fail("failUnlessRaises shouldn't re-raise unexpected "
                       "exceptions")
-        except self.failureException, e:
+        except self.failureException as e:
             # what we expect
             pass
         else:
@@ -174,7 +174,7 @@
     def test_failUnlessRaises_noException(self):
         try:
             self.failUnlessRaises(ValueError, lambda : None)
-        except self.failureException, e:
+        except self.failureException as e:
             self.failUnlessEqual(str(e),
                                  'ValueError not raised (None returned)')
         else:
@@ -189,7 +189,7 @@
         try:
             x = self.failUnlessRaises(self.failureException, self._raiseError,
                                       ValueError)
-        except self.failureException, e:
+        except self.failureException as e:
             # what we expect
             pass
         else:
@@ -639,8 +639,8 @@
                              dsu(failIfs, self._name))
 
     def test_equalSpelling(self):
-        for name, value in vars(self).items():
-            if not callable(value):
+        for name, value in list(vars(self).items()):
+            if not hasattr(value, '__call__'):
                 continue
             if name.endswith('Equal'):
                 self.failUnless(hasattr(self, name+'s'),
--- twisted/trial/test/test_class.py (original)
+++ twisted/trial/test/test_class.py (refactored)
@@ -188,7 +188,7 @@
         self.failUnlessEqual(self.factory._tearDownClassRun, 1)
 
     def test_createTwoAndRun(self):
-        tests = map(self.factory, ['test_1', 'test_2'])
+        tests = list(map(self.factory, ['test_1', 'test_2']))
         self.failUnlessEqual(tests[0]._isFirst(), True)
         self.failUnlessEqual(tests[1]._isFirst(), True)
         result = reporter.TestResult()
@@ -228,7 +228,7 @@
 
 
     def test_runMultipleCopies(self):
-        tests = map(self.factory, ['test_1', 'test_1'])
+        tests = list(map(self.factory, ['test_1', 'test_1']))
         result = reporter.TestResult()
         tests[0](result)
         self.failUnlessEqual(self.factory._setUpClassRun, 1)
@@ -238,7 +238,7 @@
         self.failUnlessEqual(self.factory._tearDownClassRun, 1)
 
     def test_skippingSetUpClass(self):
-        tests = map(self.subFactory, ['test_1', 'test_2'])
+        tests = list(map(self.subFactory, ['test_1', 'test_2']))
         result = reporter.TestResult()
         tests[0](result)
         self.failUnlessEqual(self.subFactory._setUpClassRun, 1)
--- twisted/trial/test/test_keyboard.py (original)
+++ twisted/trial/test/test_keyboard.py (refactored)
@@ -1,11 +1,11 @@
-import StringIO
+import io
 from twisted.trial import unittest
 from twisted.trial import reporter, runner
 
 
 class TrialTest(unittest.TestCase):
     def setUp(self):
-        self.output = StringIO.StringIO()
+        self.output = io.StringIO()
         self.reporter = reporter.TestResult()
         self.loader = runner.TestLoader()
 
--- twisted/trial/test/test_loader.py (original)
+++ twisted/trial/test/test_loader.py (refactored)
@@ -45,18 +45,18 @@
 
     def test_findModule(self):
         sample1 = self.loader.findByName('twisted.trial.test.sample')
-        import sample as sample2
+        from . import sample as sample2
         self.failUnlessEqual(sample1, sample2)
 
     def test_findFile(self):
         path = util.sibpath(__file__, 'sample.py')
         sample1 = self.loader.findByName(path)
-        import sample as sample2
+        from . import sample as sample2
         self.failUnlessEqual(sample1, sample2)
 
     def test_findObject(self):
         sample1 = self.loader.findByName('twisted.trial.test.sample.FooTest')
-        import sample
+        from . import sample
         self.failUnlessEqual(sample.FooTest, sample1)
 
     def test_findNonModule(self):
@@ -82,7 +82,7 @@
 
     def test_moduleInPath(self):
         sample1 = runner.filenameToModule(util.sibpath(__file__, 'sample.py'))
-        import sample as sample2
+        from . import sample as sample2
         self.failUnlessEqual(sample2, sample1)
 
     def test_moduleNotInPath(self):
@@ -155,26 +155,26 @@
         packages.SysPathManglingTest.setUp(self)
 
     def test_sortCases(self):
-        import sample
+        from . import sample
         suite = self.loader.loadClass(sample.AlphabetTest)
         self.failUnlessEqual(['test_a', 'test_b', 'test_c'],
                              [test._testMethodName for test in suite._tests])
         newOrder = ['test_b', 'test_c', 'test_a']
-        sortDict = dict(zip(newOrder, range(3)))
+        sortDict = dict(list(zip(newOrder, list(range(3)))))
         self.loader.sorter = lambda x : sortDict.get(x.shortDescription(), -1)
         suite = self.loader.loadClass(sample.AlphabetTest)
         self.failUnlessEqual(newOrder,
                              [test._testMethodName for test in suite._tests])
 
     def test_loadMethod(self):
-        import sample
+        from . import sample
         suite = self.loader.loadMethod(sample.FooTest.test_foo)
         self.failUnlessEqual(1, suite.countTestCases())
         self.failUnlessEqual('test_foo', suite._testMethodName)
 
     def test_loadFailingMethod(self):
         # test added for issue1353
-        import erroneous
+        from . import erroneous
         suite = self.loader.loadMethod(erroneous.TestRegularFail.test_fail)
         result = reporter.TestResult()
         suite.run(result)
@@ -182,7 +182,7 @@
         self.failUnlessEqual(len(result.failures), 1)
 
     def test_loadNonMethod(self):
-        import sample
+        from . import sample
         self.failUnlessRaises(TypeError, self.loader.loadMethod, sample)
         self.failUnlessRaises(TypeError,
                               self.loader.loadMethod, sample.FooTest)
@@ -191,7 +191,7 @@
                               self.loader.loadMethod, ('foo', 'bar'))
 
     def test_loadClass(self):
-        import sample
+        from . import sample
         suite = self.loader.loadClass(sample.FooTest)
         self.failUnlessEqual(2, suite.countTestCases())
         self.failUnlessEqual(['test_bar', 'test_foo'],
@@ -199,7 +199,7 @@
 
 
     def test_loadNonClass(self):
-        import sample
+        from . import sample
         self.failUnlessRaises(TypeError, self.loader.loadClass, sample)
         self.failUnlessRaises(TypeError,
                               self.loader.loadClass, sample.FooTest.test_foo)
@@ -208,17 +208,17 @@
                               self.loader.loadClass, ('foo', 'bar'))
 
     def test_loadNonTestCase(self):
-        import sample
+        from . import sample
         self.failUnlessRaises(ValueError, self.loader.loadClass,
                               sample.NotATest)
 
     def test_loadModule(self):
-        import sample
+        from . import sample
         suite = self.loader.loadModule(sample)
         self.failUnlessEqual(7, suite.countTestCases())
 
     def test_loadNonModule(self):
-        import sample
+        from . import sample
         self.failUnlessRaises(TypeError,
                               self.loader.loadModule, sample.FooTest)
         self.failUnlessRaises(TypeError,
@@ -233,7 +233,7 @@
         self.failUnlessEqual(7, suite.countTestCases())
 
     def test_loadNonPackage(self):
-        import sample
+        from . import sample
         self.failUnlessRaises(TypeError,
                               self.loader.loadPackage, sample.FooTest)
         self.failUnlessRaises(TypeError,
@@ -243,7 +243,7 @@
                               self.loader.loadPackage, ('foo', 'bar'))
 
     def test_loadModuleAsPackage(self):
-        import sample
+        from . import sample
         ## XXX -- should this instead raise a ValueError? -- jml
         self.failUnlessRaises(TypeError, self.loader.loadPackage, sample)
 
@@ -253,18 +253,18 @@
         self.failUnlessEqual(14, suite.countTestCases())
 
     def test_loadAnythingOnModule(self):
-        import sample
+        from . import sample
         suite = self.loader.loadAnything(sample)
         self.failUnlessEqual(sample.__name__,
                              suite._tests[0]._tests[0].__class__.__module__)
 
     def test_loadAnythingOnClass(self):
-        import sample
+        from . import sample
         suite = self.loader.loadAnything(sample.FooTest)
         self.failUnlessEqual(2, suite.countTestCases())
 
     def test_loadAnythingOnMethod(self):
-        import sample
+        from . import sample
         suite = self.loader.loadAnything(sample.FooTest.test_foo)
         self.failUnlessEqual(1, suite.countTestCases())
 
@@ -372,7 +372,7 @@
         """
         modules = ['goodpackage', 'package.test_module']
         suite1 = self.loader.loadByNames(modules)
-        suite2 = runner.TestSuite(map(self.loader.loadByName, modules))
+        suite2 = runner.TestSuite(list(map(self.loader.loadByName, modules)))
         self.assertSuitesEqual(suite1, suite2)
 
 
@@ -465,7 +465,7 @@
         resultingTests = list(unittest._iterateTests(suite))
         manifest = list(self._trialSortAlgorithm(sorter))
         for number, (manifestTest, actualTest) in enumerate(
-            zip(manifest, resultingTests)):
+            list(zip(manifest, resultingTests))):
             self.assertEqual(
                  manifestTest.name, actualTest.id(),
                  "#%d: %s != %s" %
--- twisted/trial/test/test_output.py (original)
+++ twisted/trial/test/test_output.py (refactored)
@@ -5,7 +5,7 @@
 Tests for the output generated by trial.
 """
 
-import os, StringIO
+import os, io
 
 from twisted.scripts import trial
 from twisted.trial import runner
@@ -16,7 +16,7 @@
     from twisted.trial import reporter
     config = trial.Options()
     config.parseOptions(args)
-    output = StringIO.StringIO()
+    output = io.StringIO()
     myRunner = runner.TrialRunner(
         reporter.VerboseTextReporter,
         stream=output,
@@ -37,7 +37,7 @@
         return runTrial('--temp-directory', self.mktemp(), *args)
 
     def _print(self, stuff):
-        print stuff
+        print(stuff)
         return stuff
 
     def failUnlessIn(self, container, containee, *args, **kwargs):
--- twisted/trial/test/test_pyunitcompat.py (original)
+++ twisted/trial/test/test_pyunitcompat.py (refactored)
@@ -50,7 +50,7 @@
         """
         Tests must be callable in order to be used with Python's unittest.py.
         """
-        self.assertTrue(callable(self.test),
+        self.assertTrue(hasattr(self.test, '__call__'),
                         "%r is not callable." % (self.test,))
 
 
--- twisted/trial/test/test_reporter.py (original)
+++ twisted/trial/test/test_reporter.py (refactored)
@@ -8,7 +8,7 @@
 """
 
 
-import errno, sys, os, re, StringIO
+import errno, sys, os, re, io
 
 from twisted.internet.utils import suppressWarnings
 from twisted.python import log
@@ -45,12 +45,12 @@
 
 class StringTest(unittest.TestCase):
     def stringComparison(self, expect, output):
-        output = filter(None, output)
+        output = [_f for _f in output if _f]
         self.failUnless(len(expect) <= len(output),
                         "Must have more observed than expected"
                         "lines %d < %d" % (len(output), len(expect)))
         REGEX_PATTERN_TYPE = type(re.compile(''))
-        for line_number, (exp, out) in enumerate(zip(expect, output)):
+        for line_number, (exp, out) in enumerate(list(zip(expect, output))):
             if exp is None:
                 continue
             elif isinstance(exp, str):
@@ -73,7 +73,7 @@
         # pyunit passes an exc_info tuple directly to addError
         try:
             raise RuntimeError('foo')
-        except RuntimeError, excValue:
+        except RuntimeError as excValue:
             self.result.addError(self, sys.exc_info())
         failure = self.result.errors[0][1]
         self.assertEqual(excValue, failure.value)
@@ -83,7 +83,7 @@
         # pyunit passes an exc_info tuple directly to addFailure
         try:
             raise self.failureException('foo')
-        except self.failureException, excValue:
+        except self.failureException as excValue:
             self.result.addFailure(self, sys.exc_info())
         failure = self.result.failures[0][1]
         self.assertEqual(excValue, failure.value)
@@ -92,7 +92,7 @@
 
 class TestReporterRealtime(TestTestResult):
     def setUp(self):
-        output = StringIO.StringIO()
+        output = io.StringIO()
         self.result = reporter.Reporter(output, realtime=True)
 
 
@@ -101,7 +101,7 @@
 
     def setUp(self):
         self.loader = runner.TestLoader()
-        self.output = StringIO.StringIO()
+        self.output = io.StringIO()
         self.result = reporter.Reporter(self.output)
 
     def getOutput(self, suite):
@@ -201,7 +201,7 @@
     """
     def setUp(self):
         self.loader = runner.TestLoader()
-        self.output = StringIO.StringIO()
+        self.output = io.StringIO()
         self.result = UncleanWarningsReporterWrapper(
             reporter.Reporter(self.output))
 
@@ -209,7 +209,7 @@
 
 class TracebackHandling(unittest.TestCase):
     def getErrorFrames(self, test):
-        stream = StringIO.StringIO()
+        stream = io.StringIO()
         result = reporter.Reporter(stream)
         test.run(result)
         bads = result.failures + result.errors
@@ -264,7 +264,7 @@
             ['foo', 'foo/bar.py', 5, [('x', 5)], [('y', 'orange')]],
             ['qux', 'foo/bar.py', 10, [('a', 'two')], [('b', 'MCMXCIX')]]
             ]
-        self.stream = StringIO.StringIO()
+        self.stream = io.StringIO()
         self.result = reporter.Reporter(self.stream)
 
     def test_formatDefault(self):
@@ -301,7 +301,7 @@
 class PyunitTestNames(unittest.TestCase):
     def setUp(self):
         from twisted.trial.test import sample
-        self.stream = StringIO.StringIO()
+        self.stream = io.StringIO()
         self.test = sample.PyunitTest('test_foo')
 
     def test_verboseReporter(self):
@@ -381,7 +381,7 @@
     def setUp(self):
         self.dirtyError = Failure(
             util.DirtyReactorAggregateError(['foo'], ['bar']))
-        self.output = StringIO.StringIO()
+        self.output = io.StringIO()
         self.test = TestDirtyReactor('test_errorByDefault')
 
 
@@ -445,7 +445,7 @@
 
     def setUp(self):
         from twisted.trial.test import sample
-        self.stream = StringIO.StringIO()
+        self.stream = io.StringIO()
         self.test = sample.FooTest('test_foo')
 
     def test_verboseReporter(self):
@@ -479,7 +479,7 @@
     """
     def setUp(self):
         from twisted.trial.test import sample
-        self.stream = StringIO.StringIO()
+        self.stream = io.StringIO()
         self.result = reporter.Reporter(self.stream)
         self.test = sample.FooTest('test_foo')
 
@@ -541,7 +541,7 @@
         """
         try:
             1/0
-        except Exception, e:
+        except Exception as e:
             error = e
         self.result.addSkip(self.test, error)
         self.result.done()
@@ -574,7 +574,7 @@
 
     def setUp(self):
         from twisted.trial.test import sample
-        self.stream = StringIO.StringIO()
+        self.stream = io.StringIO()
         self.result = reporter.Reporter(self.stream)
         self.test = sample.FooTest('test_foo')
 
@@ -667,7 +667,7 @@
         """
         try:
             1/0
-        except Exception, e:
+        except Exception as e:
             error = e
         self.result.addExpectedFailure(self.test, Failure(error),
                                        makeTodo("todo!"))
@@ -722,7 +722,7 @@
     def setUp(self):
         from twisted.trial.test import sample
         self.test = sample.FooTest('test_foo')
-        self.stream = StringIO.StringIO()
+        self.stream = io.StringIO()
         self.result = reporter.TreeReporter(self.stream)
         self.result._colorizer = MockColorizer(self.stream)
         self.log = self.result._colorizer.log
@@ -787,7 +787,7 @@
         """
         try:
             raise RuntimeError('foo')
-        except RuntimeError, excValue:
+        except RuntimeError as excValue:
             self.result.addError(self, sys.exc_info())
         self.result.done()
         self.assertEquals(self.log[1], (self.result.FAILURE, 'FAILED'))
@@ -818,7 +818,7 @@
     def setUp(self):
         from twisted.trial.test import sample
         self.test = sample.FooTest('test_foo')
-        self.stream = StringIO.StringIO()
+        self.stream = io.StringIO()
         self.publisher = log.LogPublisher()
         self.result = self.resultFactory(self.stream, publisher=self.publisher)
         self._timer = 0
@@ -1012,7 +1012,7 @@
         Test that L{reporter.SafeStream} successfully write to its original
         stream even if an interrupt happens during the write.
         """
-        stream = StringIO.StringIO()
+        stream = io.StringIO()
         broken = BrokenStream(stream)
         safe = reporter.SafeStream(broken)
         safe.write("Hello")
--- twisted/trial/test/test_runner.py (original)
+++ twisted/trial/test/test_runner.py (refactored)
@@ -5,7 +5,7 @@
 # Author: Robert Collins
 
 
-import StringIO, os
+import io, os
 from zope.interface import implements
 
 from twisted.trial.itrial import IReporter, ITestCase
@@ -158,7 +158,7 @@
     into warnings disabled.
     """
     def setUp(self):
-        self.stream = StringIO.StringIO()
+        self.stream = io.StringIO()
         self.runner = runner.TrialRunner(CapturingReporter, stream=self.stream)
         self.test = TestTrialRunner('test_empty')
 
@@ -181,7 +181,7 @@
     """
 
     def setUp(self):
-        self.stream = StringIO.StringIO()
+        self.stream = io.StringIO()
         self.runner = runner.TrialRunner(CapturingReporter, stream=self.stream,
                                          uncleanWarnings=True)
         self.test = TestTrialRunner('test_empty')
@@ -197,7 +197,7 @@
 
     def setUp(self):
         self.log = []
-        self.stream = StringIO.StringIO()
+        self.stream = io.StringIO()
         self.runner = runner.TrialRunner(CapturingReporter,
                                          runner.TrialRunner.DRY_RUN,
                                          stream=self.stream)
@@ -310,7 +310,7 @@
 
     def getRunner(self):
         r = trial._makeRunner(self.config)
-        r.stream = StringIO.StringIO()
+        r.stream = io.StringIO()
         # XXX The runner should always take care of cleaning this up itself.
         # It's not clear why this is necessary.  The runner always tears down
         # its log file.
@@ -504,7 +504,7 @@
     def setUp(self):
         TestUntilFailure.FailAfter.count = []
         self.test = TestUntilFailure.FailAfter('test_foo')
-        self.stream = StringIO.StringIO()
+        self.stream = io.StringIO()
         self.runner = runner.TrialRunner(reporter.Reporter, stream=self.stream)
 
 
@@ -592,7 +592,7 @@
     def run(self, result):
         try:
             raise RuntimeError("error that occurs outside of a test")
-        except RuntimeError, e:
+        except RuntimeError as e:
             log.err(failure.Failure())
 
 
@@ -690,7 +690,7 @@
         """
         Wrapper for one of the test method of L{ContainMalformed}.
         """
-        stream = StringIO.StringIO()
+        stream = io.StringIO()
         trialRunner = runner.TrialRunner(reporter.Reporter, stream=stream)
         test = TestMalformedMethod.ContainMalformed(method)
         result = trialRunner.run(test)
--- twisted/trial/test/test_script.py (original)
+++ twisted/trial/test/test_script.py (refactored)
@@ -2,7 +2,7 @@
 # See LICENSE for details.
 
 import gc
-import StringIO, sys, types
+import io, sys, types
 
 from twisted.trial import unittest, runner
 from twisted.scripts import trial
@@ -52,7 +52,7 @@
         Return a L{runner.TrialRunner} object that is safe to use in tests.
         """
         runner = trial._makeRunner(self.config)
-        runner.stream = StringIO.StringIO()
+        runner.stream = io.StringIO()
         return runner
 
 
@@ -128,7 +128,7 @@
     def assertSuitesEqual(self, test1, names):
         loader = runner.TestLoader()
         names1 = testNames(test1)
-        names2 = testNames(runner.TestSuite(map(loader.loadByName, names)))
+        names2 = testNames(runner.TestSuite(list(map(loader.loadByName, names))))
         names1.sort()
         names2.sort()
         self.assertEqual(names1, names2)
@@ -190,7 +190,7 @@
         Check that --testmodule displays a meaningful error message when
         passed a non-existent filename.
         """
-        buffy = StringIO.StringIO()
+        buffy = io.StringIO()
         stderr, sys.stderr = sys.stderr, buffy
         filename = 'test_thisbetternoteverexist.py'
         try:
@@ -214,7 +214,7 @@
         Check that --testmodule does *not* support module names as arguments
         and that it displays a meaningful error message.
         """
-        buffy = StringIO.StringIO()
+        buffy = io.StringIO()
         stderr, sys.stderr = sys.stderr, buffy
         moduleName = 'twisted.trial.test.test_script'
         try:
--- twisted/trial/test/test_tests.py (original)
+++ twisted/trial/test/test_tests.py (refactored)
@@ -5,7 +5,7 @@
 Tests for the behaviour of unit tests.
 """
 
-import gc, StringIO, sys, weakref
+import gc, io, sys, weakref
 
 from twisted.internet import defer, reactor
 from twisted.trial import unittest, runner, reporter, util
@@ -342,19 +342,19 @@
 class TestStrictTodo(unittest.TestCase, ResultsTestMixin):
     class Todos(unittest.TestCase):
         def test_todo1(self):
-            raise RuntimeError, "expected failure"
+            raise RuntimeError("expected failure")
         test_todo1.todo = (RuntimeError, "todo1")
 
         def test_todo2(self):
-            raise RuntimeError, "expected failure"
+            raise RuntimeError("expected failure")
         test_todo2.todo = ((RuntimeError, OSError), "todo2")
 
         def test_todo3(self):
-            raise RuntimeError, "we had no idea!"
+            raise RuntimeError("we had no idea!")
         test_todo3.todo = (OSError, "todo3")
 
         def test_todo4(self):
-            raise RuntimeError, "we had no idea!"
+            raise RuntimeError("we had no idea!")
         test_todo4.todo = ((OSError, SyntaxError), "todo4")
 
         def test_todo5(self):
@@ -403,7 +403,7 @@
 class TestCleanup(unittest.TestCase):
 
     def setUp(self):
-        self.result = reporter.Reporter(StringIO.StringIO())
+        self.result = reporter.Reporter(io.StringIO())
         self.loader = runner.TestLoader()
 
 
--- twisted/trial/test/test_util.py (original)
+++ twisted/trial/test/test_util.py (refactored)
@@ -37,7 +37,7 @@
 
 class TestIntrospection(TestCase):
     def test_containers(self):
-        import suppression
+        from . import suppression
         parents = util.getPythonContainers(
             suppression.TestSuppression2.testSuppressModule)
         expected = [suppression.TestSuppression2, suppression]
--- twisted/trial/test/test_warning.py (original)
+++ twisted/trial/test/test_warning.py (refactored)
@@ -6,7 +6,7 @@
 """
 
 import sys, warnings
-from StringIO import StringIO
+from io import StringIO
 
 from twisted.python.filepath import FilePath
 from twisted.trial.unittest import TestCase, _collectWarnings
@@ -51,7 +51,7 @@
         Assert that all the keys present in C{subset} are also present in
         C{set} and that the corresponding values are equal.
         """
-        for k, v in subset.iteritems():
+        for k, v in subset.items():
             self.assertEqual(set[k], v)
 
 
@@ -134,7 +134,7 @@
         self.assertEqual(warningsShown[0]['message'], 'some warning text')
         self.assertIdentical(warningsShown[0]['category'], UserWarning)
 
-        where = case.test_unflushed.im_func.func_code
+        where = case.test_unflushed.__func__.__code__
         filename = where.co_filename
         # If someone edits MockTests.test_unflushed, the value added to
         # firstlineno might need to change.
--- twisted/vfs/adapters/ftp.py (original)
+++ twisted/vfs/adapters/ftp.py (refactored)
@@ -67,7 +67,7 @@
         parent = self.filesystem.fetch(self._makePath(dirname))
         try:
             parent.createDirectory(basename)
-        except ivfs.VFSError, e:
+        except ivfs.VFSError as e:
             return vfsToFtpError(e)
         except:
             return defer.fail()
@@ -85,7 +85,7 @@
                 raise ftp.IsNotADirectoryError(
                     "removeDirectory can only remove directories.")
             node.remove()
-        except ivfs.VFSError, e:
+        except ivfs.VFSError as e:
             return vfsToFtpError(e)
         except:
             return defer.fail()
@@ -103,7 +103,7 @@
                 raise ftp.IsADirectoryError(
                     "removeFile can only remove files.")
             node.remove()
-        except ivfs.VFSError, e:
+        except ivfs.VFSError as e:
             return vfsToFtpError(e)
         except:
             return defer.fail()
@@ -120,7 +120,7 @@
         """
         try:
             node = self.filesystem.fetch(self._makePath(path))
-        except ivfs.VFSError, e:
+        except ivfs.VFSError as e:
             return vfsToFtpError(e)
         except:
             return defer.fail()
@@ -134,7 +134,7 @@
             else:
                 attrs = self._attrify(node, keys)
                 result.append((node.name, attrs))
-        except KeyError, e:
+        except KeyError as e:
             return defer.fail(AttributeError(e.args[0]))
 
         return defer.succeed(result)
@@ -172,7 +172,7 @@
         # See ticket 2875 in the tracker
         try:
             node = self.filesystem.fetch(self._makePath(path))
-        except ivfs.VFSError, e:
+        except ivfs.VFSError as e:
             return vfsToFtpError(e)
         except:
             return defer.fail()
@@ -188,7 +188,7 @@
             node = self.filesystem.fetch(self._makePath(path))
             if ivfs.IFileSystemContainer.providedBy(node):
                 raise ftp.IsADirectoryError("Can only open file for reading.")
-        except ivfs.VFSError, e:
+        except ivfs.VFSError as e:
             return vfsToFtpError(e)
         except:
             return defer.fail()
@@ -210,7 +210,7 @@
                  ivfs.IFileSystemContainer.providedBy(node.child(basename))):
                 raise ftp.IsADirectoryError("Can only open file for writing.")
             node = node.createFile(basename, exclusive=False)
-        except ivfs.VFSError, e:
+        except ivfs.VFSError as e:
             return vfsToFtpError(e)
         except:
             return defer.fail()
@@ -225,14 +225,14 @@
         """
         try:
             node = self.filesystem.fetch(self._makePath(path))
-        except ivfs.VFSError, e:
+        except ivfs.VFSError as e:
             return vfsToFtpError(e)
         except:
             return defer.fail()
         else:
             try:
                 attrs = self._attrify(node, keys)
-            except KeyError, e:
+            except KeyError as e:
                 return defer.fail(AttributeError(e.args[0]))
             return defer.succeed(attrs)
 
@@ -246,7 +246,7 @@
                 "Renaming into other directories isn't supported yet."))
         try:
             self.filesystem.fetch(self._makePath(fromPath)).rename(toPath[0])
-        except ivfs.VFSError, e:
+        except ivfs.VFSError as e:
             return vfsToFtpError(e)
         except:
             return defer.fail()
--- twisted/vfs/adapters/sftp.py (original)
+++ twisted/vfs/adapters/sftp.py (refactored)
@@ -34,15 +34,15 @@
             if isinstance(result, defer.Deferred):
                 result.addErrback(_ebtranslateErrors)
             return result
-        except ivfs.PermissionError, e:
+        except ivfs.PermissionError as e:
             raise SFTPError(FX_PERMISSION_DENIED, str(e))
-        except ivfs.NotFoundError, e:
+        except ivfs.NotFoundError as e:
             raise SFTPError(FX_NO_SUCH_FILE, e.args[0])
-        except ivfs.AlreadyExistsError, e:
+        except ivfs.AlreadyExistsError as e:
             raise SFTPError(FX_FILE_ALREADY_EXISTS, e.args[0])
-        except ivfs.VFSError, e:
+        except ivfs.VFSError as e:
             raise SFTPError(FX_FAILURE, str(e))
-        except NotImplementedError, e:
+        except NotImplementedError as e:
             raise SFTPError(FX_OP_UNSUPPORTED, str(e))
 
     util.mergeFunctionMetadata(function, f)
@@ -71,11 +71,11 @@
         NOTE: this function assumes it runs as the logged-in user:
         i.e. under _runAsUser()
         """
-        if attrs.has_key("uid") and attrs.has_key("gid"):
+        if "uid" in attrs and "gid" in attrs:
             os.lchown(path, attrs["uid"], attrs["gid"])
-        if attrs.has_key("permissions"):
+        if "permissions" in attrs:
             os.chmod(path, attrs["permissions"])
-        if attrs.has_key("atime") and attrs.has_key("mtime"):
+        if "atime" in attrs and "mtime" in attrs:
             os.utime(path, (attrs["atime"]. attrs["mtime"]))
 
     def gotVersion(self, otherVersion, extData):
@@ -159,9 +159,9 @@
             def __iter__(self):
                 return self
 
-            def next(self):
-
-                (name, attrs) = self.iter.next()
+            def __next__(self):
+
+                (name, attrs) = next(self.iter)
 
                 class st:
                     pass
--- twisted/vfs/backends/adhoc.py (original)
+++ twisted/vfs/backends/adhoc.py (refactored)
@@ -23,7 +23,7 @@
     def children(self):
         return [ ('.', self), ('..', self.parent) ] + [
             ( childName, self.child(childName) )
-            for childName in self._children.keys() ]
+            for childName in list(self._children.keys()) ]
 
     def child(self, childName):
         try:
@@ -35,7 +35,7 @@
         return {}
 
     def exists(self, childName):
-        return self._children.has_key(childName)
+        return childName in self._children
 
     def putChild(self, name, node):
         node.parent = self
--- twisted/vfs/backends/inmem.py (original)
+++ twisted/vfs/backends/inmem.py (refactored)
@@ -7,7 +7,7 @@
 
 import os
 
-from cStringIO import StringIO
+from io import StringIO
 
 from zope.interface import implements
 
@@ -59,7 +59,7 @@
     def children( self ) :
         implicit =  [('.', self), ('..', self.parent)]
         others = [(childName, self.child(childName))
-                  for childName in self._children.keys() ]
+                  for childName in list(self._children.keys()) ]
         return implicit + others
 
     def child(self, childName):
@@ -134,7 +134,7 @@
         pass
 
     def children(self):
-        print "this might break and if it does we should fix the caller"
+        print("this might break and if it does we should fix the caller")
         return []
 
 
--- twisted/vfs/backends/osfs.py (original)
+++ twisted/vfs/backends/osfs.py (refactored)
@@ -70,7 +70,7 @@
         newPath = os.path.join(newParent.realPath, pathutils.basename(newName))
         try:
             os.rename(self.realPath, newPath)
-        except OSError, e:
+        except OSError as e:
             if e.errno in (errno.EISDIR, errno.ENOTEMPTY, errno.EEXIST):
                 raise ivfs.AlreadyExistsError(
                     "Can't rename %s to %s: %s already exists"
@@ -95,7 +95,7 @@
             flags |= os.O_EXCL
         try:
             fd = os.open(self.realPath, flags)
-        except OSError, e:
+        except OSError as e:
             if e.errno == errno.EEXIST:
                 raise ivfs.AlreadyExistsError(self.name)
 
@@ -250,7 +250,7 @@
 
     def __getattr__(self, attrName):
         attr = _OSNodeProxy.__getattr__(self, attrName)
-        if callable(attr):
+        if hasattr(attr, '__call__'):
             return RunWithPrivSep(attr, self.euid, self.egid)
         return attr
 
--- twisted/vfs/test/test_sftp.py (original)
+++ twisted/vfs/test/test_sftp.py (refactored)
@@ -217,13 +217,13 @@
 
     def test_openDirectory(self):
         for name, lsline, attrs in self.sftp.openDirectory('/ned'):
-            keys = attrs.keys()
+            keys = list(attrs.keys())
             keys.sort()
             self.failUnless(sftpAttrs, keys)
 
     def test_getAttrsPath(self):
         # getAttrs by path name
-        attrs = self.sftp.getAttrs('/ned', None).keys()
+        attrs = list(self.sftp.getAttrs('/ned', None).keys())
         attrs.sort()
         self.failUnless(sftpAttrs, attrs)
 
@@ -239,7 +239,7 @@
         for mtime in [86401, 200000, int(time.time())]:
             try:
                 self.sftp.setAttrs('/file.txt', {'mtime': mtime})
-            except SFTPError, e:
+            except SFTPError as e:
                 if e.code == FX_OP_UNSUPPORTED:
                     raise unittest.SkipTest(
                         "The VFS backend %r doesn't support setAttrs"
@@ -267,7 +267,7 @@
     def test_dirlistWithoutAttrs(self):
         self.ned.getMetadata = self.f.getMetadata = lambda: {}
         for name, lsline, attrs in self.sftp.openDirectory('/'):
-            keys = attrs.keys()
+            keys = list(attrs.keys())
             keys.sort()
             self.failUnless(sftpAttrs, keys)
 
--- twisted/web/client.py (original)
+++ twisted/web/client.py (refactored)
@@ -7,7 +7,7 @@
 """
 
 import os, types
-from urlparse import urlunparse
+from urllib.parse import urlunparse
 
 from twisted.web import http
 from twisted.internet import defer, protocol, reactor
@@ -43,13 +43,13 @@
             self.sendHeader("Content-Length", str(len(data)))
 
         cookieData = []
-        for (key, value) in self.factory.headers.items():
+        for (key, value) in list(self.factory.headers.items()):
             if key.lower() not in self._specialHeaders:
                 # we calculated it on our own
                 self.sendHeader(key, value)
             if key.lower() == 'cookie':
                 cookieData.append(value)
-        for cookie, cookval in self.factory.cookies.items():
+        for cookie, cookval in list(self.factory.cookies.items()):
             cookieData.append('%s=%s' % (cookie, cookval))
         if cookieData:
             self.sendHeader('Cookie', '; '.join(cookieData))
@@ -288,7 +288,7 @@
 
     def gotHeaders(self, headers):
         self.response_headers = headers
-        if headers.has_key('set-cookie'):
+        if 'set-cookie' in headers:
             for cookie in headers['set-cookie']:
                 cookparts = cookie.split(';')
                 cook = cookparts[0]
@@ -325,7 +325,7 @@
                  method='GET', postdata=None, headers=None,
                  agent="Twisted client", supportPartial=0):
         self.requestedPartial = 0
-        if isinstance(fileOrName, types.StringTypes):
+        if isinstance(fileOrName, str):
             self.fileName = fileOrName
             self.file = None
             if supportPartial and os.path.exists(self.fileName):
@@ -367,7 +367,7 @@
         @param partialContent: tells us if the download is partial download we requested.
         """
         if partialContent and not self.requestedPartial:
-            raise ValueError, "we shouldn't get partial content response if we didn't want it!"
+            raise ValueError("we shouldn't get partial content response if we didn't want it!")
         if self.waiting:
             self.waiting = 0
             try:
--- twisted/web/distrib.py (original)
+++ twisted/web/distrib.py (refactored)
@@ -10,7 +10,7 @@
 """
 
 # System Imports
-import types, os, copy, string, cStringIO
+import types, os, copy, string, io
 if (os.sys.platform != 'win32') and (os.name != 'java'):
     import pwd
 
@@ -23,12 +23,12 @@
 from twisted.internet import address, reactor
 
 # Sibling Imports
-import resource
-import server
-import error
-import html
-import static
-from server import NOT_DONE_YET
+from . import resource
+from . import server
+from . import error
+from . import html
+from . import static
+from .server import NOT_DONE_YET
 
 class _ReferenceableProducerWrapper(pb.Referenceable):
     def __init__(self, producer):
@@ -56,7 +56,7 @@
             state[k] = addr
         pb.RemoteCopy.setCopyableState(self, state)
         # Emulate the local request interface --
-        self.content = cStringIO.StringIO(self.content_data)
+        self.content = io.StringIO(self.content_data)
         self.write            = self.remote.remoteMethod('write')
         self.finish           = self.remote.remoteMethod('finish')
         self.setHeader        = self.remote.remoteMethod('setHeader')
@@ -85,7 +85,7 @@
 
     def finished(self, result):
         if result != NOT_DONE_YET:
-            assert isinstance(result, types.StringType),\
+            assert isinstance(result, bytes),\
                    "return value not a string"
             self.request.write(result)
             self.request.finish()
--- twisted/web/domhelpers.py (original)
+++ twisted/web/domhelpers.py (refactored)
@@ -4,15 +4,15 @@
 
 # 
 
-from __future__ import nested_scopes
+
 
 from twisted.web import microdom
-from microdom import getElementsByTagName, escape, unescape
+from .microdom import getElementsByTagName, escape, unescape
 
 try:
-    import cStringIO as StringIO
+    import io as StringIO
 except ImportError:
-    import StringIO
+    import io
 
 class NodeLookupError(Exception): pass
 
@@ -54,7 +54,7 @@
     """
     result = _get(node, nodeId)
     if result: return result
-    raise NodeLookupError, nodeId
+    raise NodeLookupError(nodeId)
 
 def getIfExists(node, nodeId):
     """
@@ -242,7 +242,7 @@
 
 
 def getNodeText(node):
-    oldio = StringIO.StringIO()
+    oldio = io.StringIO()
     writeNodeData(node, oldio)
     return oldio.getvalue()
 
--- twisted/web/google.py (original)
+++ twisted/web/google.py (refactored)
@@ -4,7 +4,7 @@
 #
 """\"I'm Feeling Lucky\" with U{Google<http://google.com>}.
 """
-import urllib
+import urllib.request, urllib.parse, urllib.error
 from twisted.internet import protocol, reactor, defer
 from twisted.web import http
 
@@ -44,8 +44,8 @@
 
     def __init__(self, words):
         self.url = ('/search?q=%s&btnI=%s' %
-                    (urllib.quote_plus(' '.join(words)),
-                     urllib.quote_plus("I'm Feeling Lucky")))
+                    (urllib.parse.quote_plus(' '.join(words)),
+                     urllib.parse.quote_plus("I'm Feeling Lucky")))
         self.agent="Twisted/GoogleChecker"
         self.host = "www.google.com"
         self.deferred = defer.Deferred()
--- twisted/web/html.py (original)
+++ twisted/web/html.py (refactored)
@@ -12,8 +12,8 @@
 
 import traceback, string
 
-from cStringIO import StringIO
-from microdom import escape
+from io import StringIO
+from .microdom import escape
 
 def PRE(text):
     "Wrap <pre> tags around some text and HTML-escape it."
--- twisted/web/http.py (original)
+++ twisted/web/http.py (refactored)
@@ -16,7 +16,7 @@
 """
 
 # system imports
-from cStringIO import StringIO
+from io import StringIO
 import tempfile
 import base64, binascii
 import cgi
@@ -26,7 +26,7 @@
 import calendar
 import warnings
 import os
-from urlparse import urlparse as _urlparse
+from urllib.parse import urlparse as _urlparse
 
 from zope.interface import implements
 
@@ -37,7 +37,7 @@
 try: # try importing the fast, C version
     from twisted.protocols._c_urlarg import unquote
 except ImportError:
-    from urllib import unquote
+    from urllib.parse import unquote
 
 from twisted.web.http_headers import _DictHeaders, Headers
 
@@ -179,10 +179,10 @@
     @return: The scheme, net location, path, params, query string, and fragment
     of the URL.
     """
-    if isinstance(url, unicode):
+    if isinstance(url, str):
         raise TypeError("url must be str, not unicode")
     scheme, netloc, path, params, query, fragment = _urlparse(url)
-    if isinstance(scheme, unicode):
+    if isinstance(scheme, str):
         scheme = scheme.encode('ascii')
         netloc = netloc.encode('ascii')
         path = path.encode('ascii')
@@ -322,7 +322,7 @@
     day = int(day)
     month = int(monthname_lower.index(month.lower()))
     year = int(year)
-    hour, min, sec = map(int, time.split(':'))
+    hour, min, sec = list(map(int, time.split(':')))
     return int(timegm(year, month, day, hour, min, sec))
 
 def toChunk(data):
@@ -341,7 +341,7 @@
     if length < 0:
         raise ValueError("Chunk length must be >= 0, not %d" % (length,))
     if not rest[length:length + 2] == '\r\n':
-        raise ValueError, "chunk must end with CRLF"
+        raise ValueError("chunk must end with CRLF")
     return rest[:length], rest[length + 2:]
 
 
@@ -352,9 +352,9 @@
     """
     kind, other = header.strip().split()
     if kind.lower() != "bytes":
-        raise ValueError, "a range of type %r is not supported"
+        raise ValueError("a range of type %r is not supported")
     startend, realLength = other.split("/")
-    start, end = map(int, startend.split("-"))
+    start, end = list(map(int, startend.split("-")))
     if realLength == "*":
         realLength = None
     else:
@@ -546,14 +546,14 @@
         if name == 'received_headers':
             # A property would be nice, but Request is classic.
             self.requestHeaders = headers = Headers()
-            for k, v in value.iteritems():
+            for k, v in value.items():
                 headers.setRawHeaders(k, [v])
         elif name == 'requestHeaders':
             self.__dict__[name] = value
             self.__dict__['received_headers'] = _DictHeaders(value)
         elif name == 'headers':
             self.responseHeaders = headers = Headers()
-            for k, v in value.iteritems():
+            for k, v in value.items():
                 headers.setRawHeaders(k, [v])
         elif name == 'responseHeaders':
             self.__dict__[name] = value
@@ -586,7 +586,7 @@
         This method is not intended for users.
         """
         if not self.queued:
-            raise RuntimeError, "noLongerQueued() got called unnecessarily."
+            raise RuntimeError("noLongerQueued() got called unnecessarily.")
 
         self.queued = 0
 
@@ -699,7 +699,7 @@
             elif key == mfd:
                 try:
                     args.update(cgi.parse_multipart(self.content, pdict))
-                except KeyError, e:
+                except KeyError as e:
                     if e.args[0] == 'content-disposition':
                         # Parse_multipart can't cope with missing
                         # content-dispostion headers in multipart/form-data
@@ -730,7 +730,7 @@
     def registerProducer(self, producer, streaming):
         """Register a producer."""
         if self.producer:
-            raise ValueError, "registering producer %s before previous one (%s) was unregistered" % (producer, self.producer)
+            raise ValueError("registering producer %s before previous one (%s) was unregistered" % (producer, self.producer))
 
         self.streamingProducer = streaming
         self.producer = producer
@@ -886,7 +886,7 @@
     def setResponseCode(self, code, message=None):
         """Set the HTTP response code.
         """
-        if not isinstance(code, (int, long)):
+        if not isinstance(code, (int, int)):
             raise TypeError("HTTP response code must be int or long")
         self.code = code
         if message:
@@ -939,7 +939,7 @@
         """
         # time.time() may be a float, but the HTTP-date strings are
         # only good for whole seconds.
-        when = long(math.ceil(when))
+        when = int(math.ceil(when))
         if (not self.lastModified) or (self.lastModified < when):
             self.lastModified = when
 
@@ -1428,7 +1428,7 @@
         """
         connection = request.requestHeaders.getRawHeaders('connection')
         if connection:
-            tokens = map(str.lower, connection[0].split(' '))
+            tokens = list(map(str.lower, connection[0].split(' ')))
         else:
             tokens = []
 
--- twisted/web/http_headers.py (original)
+++ twisted/web/http_headers.py (refactored)
@@ -75,7 +75,7 @@
         Return a C{dict} mapping each header name to the last corresponding
         header value.
         """
-        return dict(self.items())
+        return dict(list(self.items()))
 
 
     # Python 2.3 DictMixin.setdefault is defined so as not to have a default
@@ -231,7 +231,7 @@
         object, as strings.  The keys are capitalized in canonical
         capitalization.
         """
-        for k, v in self._rawHeaders.iteritems():
+        for k, v in self._rawHeaders.items():
             yield self._canonicalNameCaps(k), v
 
 
--- twisted/web/microdom.py (original)
+++ twisted/web/microdom.py (refactored)
@@ -20,7 +20,7 @@
 
 # System Imports
 import re
-from cStringIO import StringIO
+from io import StringIO
 
 # create NodeList class
 from types import ListType as NodeList
@@ -432,7 +432,7 @@
     while True:
         yield  'p' + str(i)
         i = i + 1
-genprefix = _genprefix().next
+genprefix = _genprefix().__next__
 
 class _Attr(CharacterData):
     "Support class for getAttributeNode."
@@ -456,7 +456,7 @@
             self.attributes = {}
         else:
             self.attributes = attributes
-            for k, v in self.attributes.items():
+            for k, v in list(self.attributes.items()):
                 self.attributes[k] = unescape(v)
 
         if caseInsensitive:
@@ -523,7 +523,7 @@
 
     def getAttributeNS(self, ns, name, default=None):
         nsk = (ns, name)
-        if self.attributes.has_key(nsk):
+        if nsk in self.attributes:
             return self.attributes[nsk]
         if ns == self.namespace:
             return self.attributes.get(name, default)
@@ -562,7 +562,7 @@
         w = stream.write
         if self.nsprefixes:
             newprefixes = self.nsprefixes.copy()
-            for ns in nsprefixes.keys():
+            for ns in list(nsprefixes.keys()):
                 if ns in newprefixes:
                     del newprefixes[ns]
         else:
@@ -574,7 +574,7 @@
         bext = begin.extend
         writeattr = lambda _atr, _val: bext((' ', _atr, '="', escape(_val), '"'))
         if namespace != self.namespace and self.namespace is not None:
-            if nsprefixes.has_key(self.namespace):
+            if self.namespace in nsprefixes:
                 prefix = nsprefixes[self.namespace]
                 bext(prefix+':'+self.tagName)
             else:
@@ -583,10 +583,10 @@
         else:
             bext(self.tagName)
         j = ''.join
-        for attr, val in self.attributes.iteritems():
+        for attr, val in self.attributes.items():
             if isinstance(attr, tuple):
                 ns, key = attr
-                if nsprefixes.has_key(ns):
+                if ns in nsprefixes:
                     prefix = nsprefixes[ns]
                 else:
                     prefix = genprefix()
@@ -597,7 +597,7 @@
                 assert val is not None
                 writeattr(attr, val)
         if newprefixes:
-            for ns, prefix in newprefixes.iteritems():
+            for ns, prefix in newprefixes.items():
                 if prefix:
                     writeattr('xmlns:'+prefix, ns)
             newprefixes.update(nsprefixes)
@@ -643,7 +643,7 @@
             rep += " line %s column %s" % self._markpos
         if self._filename or self._markpos:
             rep += ")"
-        for item in self.attributes.items():
+        for item in list(self.attributes.items()):
             rep += " %s=%r" % item
         if self.hasChildNodes():
             rep += " >...</%s>" % self.nodeName
@@ -653,13 +653,13 @@
 
 def _unescapeDict(d):
     dd = {}
-    for k, v in d.items():
+    for k, v in list(d.items()):
         dd[k] = unescape(v)
     return dd
 
 def _reverseDict(d):
     dd = {}
-    for k, v in d.items():
+    for k, v in list(d.items()):
         dd[v]=k
     return dd
 
@@ -704,7 +704,7 @@
         # self.indentlevel = 0
 
     def shouldPreserveSpace(self):
-        for edx in xrange(len(self.elementstack)):
+        for edx in range(len(self.elementstack)):
             el = self.elementstack[-edx]
             if el.tagName == 'pre' or el.getAttribute("xml:space", '') == 'preserve':
                 return 1
@@ -770,7 +770,7 @@
         attributes = _unescapeDict(attributes)
         namespaces = self.nsstack[-1][0]
         newspaces = {}
-        for k, v in attributes.items():
+        for k, v in list(attributes.items()):
             if k.startswith('xmlns'):
                 spacenames = k.split(':',1)
                 if len(spacenames) == 2:
@@ -781,11 +781,11 @@
         if newspaces:
             namespaces = namespaces.copy()
             namespaces.update(newspaces)
-        for k, v in attributes.items():
+        for k, v in list(attributes.items()):
             ksplit = k.split(':', 1)
             if len(ksplit) == 2:
                 pfx, tv = ksplit
-                if pfx != 'xml' and namespaces.has_key(pfx):
+                if pfx != 'xml' and pfx in namespaces:
                     attributes[namespaces[pfx], tv] = v
                     del attributes[k]
         el = Element(name, attributes, parent,
@@ -861,7 +861,7 @@
             if self.beExtremelyLenient:
                 if self.elementstack:
                     lastEl = self.elementstack[0]
-                    for idx in xrange(len(self.elementstack)):
+                    for idx in range(len(self.elementstack)):
                         if self.elementstack[-(idx+1)].tagName == cname:
                             self.elementstack[-(idx+1)].endTag(name)
                             break
@@ -979,7 +979,7 @@
         newNode = Element(tagName, caseInsensitive=0, preserveCase=0)
         self.node.appendChild(newNode)
         xf = lmx(newNode)
-        for k, v in kw.items():
+        for k, v in list(kw.items()):
             if k[0] == '_':
                 k = k[1:]
             xf[k]=v
--- twisted/web/proxy.py (original)
+++ twisted/web/proxy.py (refactored)
@@ -19,8 +19,8 @@
 ReverseProxy is used on the server end.
 """
 
-import urlparse
-from urllib import quote as urlquote
+import urllib.parse
+from urllib.parse import quote as urlquote
 
 from twisted.internet import reactor
 from twisted.internet.protocol import ClientFactory
@@ -48,7 +48,7 @@
 
     def connectionMade(self):
         self.sendCommand(self.command, self.rest)
-        for header, value in self.headers.items():
+        for header, value in list(self.headers.items()):
             self.sendHeader(header, value)
         self.endHeaders()
         self.transport.write(self.data)
@@ -128,14 +128,14 @@
 
 
     def process(self):
-        parsed = urlparse.urlparse(self.uri)
+        parsed = urllib.parse.urlparse(self.uri)
         protocol = parsed[0]
         host = parsed[1]
         port = self.ports[protocol]
         if ':' in host:
             host, port = host.split(':')
             port = int(port)
-        rest = urlparse.urlunparse(('', '') + parsed[2:])
+        rest = urllib.parse.urlunparse(('', '') + parsed[2:])
         if not rest:
             rest = rest + '/'
         class_ = self.protocols[protocol]
@@ -277,7 +277,7 @@
             host = "%s:%d" % (self.host, self.port)
         request.received_headers['host'] = host
         request.content.seek(0, 0)
-        qs = urlparse.urlparse(request.uri)[4]
+        qs = urllib.parse.urlparse(request.uri)[4]
         if qs:
             rest = self.path + '?' + qs
         else:
--- twisted/web/resource.py (original)
+++ twisted/web/resource.py (refactored)
@@ -72,10 +72,10 @@
     ### Abstract Collection Interface
 
     def listStaticNames(self):
-        return self.children.keys()
+        return list(self.children.keys())
 
     def listStaticEntities(self):
-        return self.children.items()
+        return list(self.children.items())
 
     def listNames(self):
         return self.listStaticNames() + self.listDynamicNames()
@@ -93,7 +93,7 @@
         return self.children.get(name)
 
     def getDynamicEntity(self, name, request):
-        if not self.children.has_key(name):
+        if name not in self.children:
             return self.getChild(name, request)
         else:
             return None
@@ -145,7 +145,7 @@
         This will check to see if I have a pre-registered child resource of the
         given name, and call getChild if I do not.
         """
-        if self.children.has_key(path):
+        if path in self.children:
             return self.children[path]
 
         return self.getChild(path, request)
--- twisted/web/script.py (original)
+++ twisted/web/script.py (refactored)
@@ -6,15 +6,15 @@
 """I contain PythonScript, which is a very simple python script resource.
 """
 
-import server
-import resource
-import html
-import error
+from . import server
+from . import resource
+from . import html
+from . import error
 
 try:
-    import cStringIO as StringIO
+    import io as StringIO
 except ImportError:
-    import StringIO
+    import io
 
 from twisted.web import http
 from twisted import copyright
@@ -67,8 +67,8 @@
             'cache': cs.cache,
             'recache': cs.recache}
     try:
-        execfile(path, glob, glob)
-    except AlreadyCached, ac:
+        exec(open(path).read(), glob, glob)
+    except AlreadyCached as ac:
         return ac.args[0]
     rsrc = glob['resource']
     if cs.doCache and rsrc is not noRsrc:
@@ -84,7 +84,7 @@
             'registry': registry}
 
     e = ptl_compile.compile_template(open(path), path)
-    exec e in glob
+    exec(e, glob)
     return glob['resource']
 
 
@@ -150,13 +150,13 @@
                      '__file__': self.filename,
                      'registry': self.registry}
         try:
-            execfile(self.filename, namespace, namespace)
-        except IOError, e:
+            exec(open(self.filename).read(), namespace, namespace)
+        except IOError as e:
             if e.errno == 2: #file not found
                 request.setResponseCode(http.NOT_FOUND)
                 request.write(error.NoResource("File not found.").render(request))
         except:
-            io = StringIO.StringIO()
+            io = io.StringIO()
             traceback.print_exc(file=io)
             request.write(html.PRE(io.getvalue()))
         request.finish()
--- twisted/web/server.py (original)
+++ twisted/web/server.py (refactored)
@@ -16,11 +16,11 @@
 import copy
 import time
 import os
-from urllib import quote
+from urllib.parse import quote
 try:
     from twisted.protocols._c_urlarg import unquote
 except ImportError:
-    from urllib import unquote
+    from urllib.parse import unquote
 
 #some useful constants
 NOT_DONE_YET = 1
@@ -70,7 +70,7 @@
             why = "but my first argument is not a sequence."
             s = ("First argument must be a sequence of"
                  " supported methods, %s" % (why,))
-            raise TypeError, s
+            raise TypeError(s)
 
 def _addressToTuple(addr):
     if isinstance(addr, address.IPv4Address):
@@ -144,7 +144,7 @@
 
         # Resource Identification
         self.prepath = []
-        self.postpath = map(unquote, string.split(self.path[1:], '/'))
+        self.postpath = list(map(unquote, string.split(self.path[1:], '/')))
         try:
             resrc = self.site.getResourceFor(self)
             self.render(resrc)
@@ -155,7 +155,7 @@
     def render(self, resrc):
         try:
             body = resrc.render(self)
-        except UnsupportedMethod, e:
+        except UnsupportedMethod as e:
             allowedMethods = e.allowedMethods
             if (self.method == "HEAD") and ("GET" in allowedMethods):
                 # We must support HEAD (RFC 2616, 5.1.1).  If the
@@ -203,7 +203,7 @@
 
         if body == NOT_DONE_YET:
             return
-        if type(body) is not types.StringType:
+        if type(body) is not bytes:
             body = error.ErrorPage(http.INTERNAL_SERVER_ERROR,
                 "Request did not return a string",
                 "Request: "+html.PRE(reflect.safe_repr(self))+"<br />"+
@@ -568,5 +568,5 @@
         return resource.getChildForRequest(self.resource, request)
 
 
-import html
-
+from . import html
+
--- twisted/web/soap.py (original)
+++ twisted/web/soap.py (refactored)
@@ -55,9 +55,9 @@
         methodName, args, kwargs, ns = p._name, p._aslist, p._asdict, p._ns
 
         # deal with changes in SOAPpy 0.11
-        if callable(args):
+        if hasattr(args, '__call__'):
             args = args()
-        if callable(kwargs):
+        if hasattr(kwargs, '__call__'):
             kwargs = kwargs()
 
         function = self.lookupFunction(methodName)
@@ -68,7 +68,7 @@
         else:
             if hasattr(function, "useKeywords"):
                 keywords = {}
-                for k, v in kwargs.items():
+                for k, v in list(kwargs.items()):
                     keywords[str(k)] = v
                 d = defer.maybeDeferred(function, **keywords)
             else:
--- twisted/web/static.py (original)
+++ twisted/web/static.py (refactored)
@@ -8,7 +8,7 @@
 
 import os
 import warnings
-import urllib
+import urllib.request, urllib.parse, urllib.error
 import itertools
 import cgi
 
@@ -134,7 +134,7 @@
 def getTypeAndEncoding(filename, types, encodings, defaultType):
     p, ext = os.path.splitext(filename)
     ext = ext.lower()
-    if encodings.has_key(ext):
+    if ext in encodings:
         enc = encodings[ext]
         ext = os.path.splitext(p)[1].lower()
     else:
@@ -296,7 +296,7 @@
         kind = kind.strip()
         if kind != 'bytes':
             raise ValueError("Unsupported Bytes-Unit: %r" % (kind,))
-        byteRanges = filter(None, map(str.strip, value.split(',')))
+        byteRanges = [_f for _f in list(map(str.strip, value.split(','))) if _f]
         if len(byteRanges) > 1:
             # Support for multiple ranges should be added later.  For now, this
             # implementation gives up.
@@ -332,7 +332,7 @@
 
 
 
-    def _doRangeRequest(self, request, (start, end)):
+    def _doRangeRequest(self, request, xxx_todo_changeme):
         """
         Responds to simple Range-Header requests. Simple means that only the
         first byte range is handled.
@@ -342,6 +342,7 @@
         @return: A three-tuple of the start, length, and end byte of the
             response.
         """
+        (start, end) = xxx_todo_changeme
         size = self.getFileSize()
         if start is None:
             # Omitted start means that the end value is actually a start value
@@ -398,7 +399,7 @@
 
         try:
             f = self.openForReading()
-        except IOError, e:
+        except IOError as e:
             import errno
             if e[0] == errno.EACCES:
                 return error.ForbiddenResource().render(request)
@@ -416,7 +417,7 @@
             try:
                 start, contentLength, stop = self._doRangeRequest(
                     request, self._parseRangeHeader(byteRange))
-            except ValueError, e:
+            except ValueError as e:
                 log.msg("Ignoring malformed Range header %r" % (byteRange,))
                 request.setResponseCode(http.OK)
             else:
@@ -443,7 +444,7 @@
         return directory
 
     def listEntities(self):
-        return map(lambda fileName, self=self: self.createSimilarFile(os.path.join(self.path, fileName)), self.listNames())
+        return list(map(lambda fileName, self=self: self.createSimilarFile(os.path.join(self.path, fileName)), self.listNames()))
 
     def createPickleChild(self, name, child):
         if not os.path.isdir(self.path):
@@ -653,7 +654,7 @@
         files = []
         dirs = []
         for path in directory:
-            url = urllib.quote(path, "/")
+            url = urllib.parse.quote(path, "/")
             escapedPath = cgi.escape(path)
             if os.path.isdir(os.path.join(self.path, path)):
                 url = url + '/'
@@ -704,7 +705,7 @@
         tableContent = "".join(self._buildTableContent(dirs + files))
 
         header = "Directory listing for %s" % (
-            cgi.escape(urllib.unquote(request.uri)),)
+            cgi.escape(urllib.parse.unquote(request.uri)),)
 
         return self.template % {"header": header, "tableContent": tableContent}
 
--- twisted/web/sux.py (original)
+++ twisted/web/sux.py (refactored)
@@ -42,13 +42,13 @@
     for x in args:
         l.extend(x)
     d = dict([(x, 1) for x in l])
-    return d.keys()
+    return list(d.keys())
 
 
 def zipfndict(*args, **kw):
     default = kw.get('default', nop)
     d = {}
-    for key in unionlist(*[fndict.keys() for fndict in args]):
+    for key in unionlist(*[list(fndict.keys()) for fndict in args]):
         d[key] = tuple([x.get(key, default) for x in args])
     return d
 
@@ -117,7 +117,7 @@
         if self._prepend:
             data = self._prepend + data
         for encoding in self.encodings:
-            data = unicode(data, encoding)
+            data = str(data, encoding)
         return data
 
     def maybeBodyData(self):
@@ -133,7 +133,7 @@
         # -radix
 
         if (self.tagName == 'script'
-            and not self.tagAttributes.has_key('src')):
+            and 'src' not in self.tagAttributes):
             # we do this ourselves rather than having begin_waitforendscript
             # becuase that can get called multiple times and we don't want
             # bodydata to get reset other than the first time.
@@ -596,19 +596,19 @@
         '''Encountered an opening tag.
 
         Default behaviour is to print.'''
-        print 'begin', name, attributes
+        print('begin', name, attributes)
 
     def gotText(self, data):
         '''Encountered text
 
         Default behaviour is to print.'''
-        print 'text:', repr(data)
+        print('text:', repr(data))
 
     def gotEntityReference(self, entityRef):
         '''Encountered mnemonic entity reference
 
         Default behaviour is to print.'''
-        print 'entityRef: &%s;' % entityRef
+        print('entityRef: &%s;' % entityRef)
 
     def gotComment(self, comment):
         '''Encountered comment.
@@ -628,16 +628,16 @@
         This is really grotty: it basically just gives you everything between
         '<!DOCTYPE' and '>' as an argument.
         """
-        print '!DOCTYPE', repr(doctype)
+        print('!DOCTYPE', repr(doctype))
 
     def gotTagEnd(self, name):
         '''Encountered closing tag
 
         Default behaviour is to print.'''
-        print 'end', name
+        print('end', name)
 
 if __name__ == '__main__':
-    from cStringIO import StringIO
+    from io import StringIO
     testDocument = '''
 
     <!DOCTYPE ignore all this shit, hah its malformed!!!!@$>
--- twisted/web/twcgi.py (original)
+++ twisted/web/twcgi.py (refactored)
@@ -10,7 +10,7 @@
 import string
 import os
 import sys
-import urllib
+import urllib.request, urllib.parse, urllib.error
 
 # Twisted Imports
 from twisted.web import http
@@ -19,12 +19,12 @@
 from twisted.python import log, filepath
 
 # Sibling Imports
-import server
-import error
-import html
-import resource
-import static
-from server import NOT_DONE_YET
+from . import server
+from . import error
+from . import html
+from . import resource
+from . import static
+from .server import NOT_DONE_YET
 
 class CGIDirectory(resource.Resource, filepath.FilePath):
     def __init__(self, pathname):
@@ -100,20 +100,20 @@
             if '=' in qs:
                 qargs = []
             else:
-                qargs = [urllib.unquote(x) for x in qs.split('+')]
+                qargs = [urllib.parse.unquote(x) for x in qs.split('+')]
         else:
             env['QUERY_STRING'] = ''
             qargs = []
 
         # Propogate HTTP headers
-        for title, header in request.getAllHeaders().items():
+        for title, header in list(request.getAllHeaders().items()):
             envname = string.upper(string.replace(title, '-', '_'))
             if title not in ('content-type', 'content-length'):
                 envname = "HTTP_" + envname
             env[envname] = header
         # Propogate our environment
-        for key, value in os.environ.items():
-            if not env.has_key(key):
+        for key, value in list(os.environ.items()):
+            if key not in env:
                 env[key] = value
         # And they're off!
         self.runProcess(env, request, qargs)
--- twisted/web/util.py (original)
+++ twisted/web/util.py (refactored)
@@ -4,12 +4,12 @@
 # See LICENSE for details.
 
 
-from cStringIO import StringIO
+from io import StringIO
 
 from twisted.python import failure
 
-import html
-import resource
+from . import html
+from . import resource
 
 
 import linecache
@@ -253,7 +253,7 @@
     w = io.write
     w('<div class="dict"><span class="heading">Dictionary instance @ %s</span>' % hex(id(d)))
     w('<table class="dict">')
-    for k, v in d.items():
+    for k, v in list(d.items()):
 
         if k == '__builtins__':
             v = 'builtin dictionary'
@@ -285,14 +285,14 @@
 def htmlFunc(f):
     return ('<div class="function">' +
             html.escape("function %s in file %s at line %s" %
-                        (f.__name__, f.func_code.co_filename,
-                         f.func_code.co_firstlineno))+
+                        (f.__name__, f.__code__.co_filename,
+                         f.__code__.co_firstlineno))+
             '</div>')
 
-htmlReprTypes = {types.DictType: htmlDict,
-                 types.ListType: htmlList,
+htmlReprTypes = {dict: htmlDict,
+                 list: htmlList,
                  types.InstanceType: htmlInst,
-                 types.StringType: htmlString,
+                 bytes: htmlString,
                  types.FunctionType: htmlFunc}
 
 
@@ -361,7 +361,7 @@
         # Instance variables
         for name, var in localVars:
             if name == 'self' and hasattr(var, '__dict__'):
-                usedVars = [ (key, value) for (key, value) in var.__dict__.items()
+                usedVars = [ (key, value) for (key, value) in list(var.__dict__.items())
                              if re.search(r'\W'+'self.'+key+r'\W', textSnippet) ]
                 if usedVars:
                     w('<div class="variables"><b>Self</b>')
--- twisted/web/vhost.py (original)
+++ twisted/web/vhost.py (refactored)
@@ -13,8 +13,8 @@
 from twisted.python import roots
 
 # Sibling Imports
-import resource
-import error
+from . import resource
+from . import error
 
 class VirtualHostCollection(roots.Homogenous):
     """Wrapper for virtual hosts collection.
@@ -27,7 +27,7 @@
         self.nvh = nvh
     
     def listStaticEntities(self):
-        return self.nvh.hosts.items()
+        return list(self.nvh.hosts.items())
     
     def getStaticEntity(self, name):
         return self.nvh.hosts.get(self)
--- twisted/web/widgets.py (original)
+++ twisted/web/widgets.py (refactored)
@@ -16,7 +16,7 @@
 import string, time, types, traceback, pprint, sys, os
 import linecache
 import re
-from cStringIO import StringIO
+from io import StringIO
 
 # Twisted Imports
 from twisted.python import failure, log, rebuild, reflect, util
@@ -25,15 +25,15 @@
 
 # Sibling Imports
 import html, resource, error
-import util as webutil
+from . import util as webutil
 
 #backwards compatibility
-from util import formatFailure, htmlrepr, htmlUnknown, htmlDict, htmlList,\
+from .util import formatFailure, htmlrepr, htmlUnknown, htmlDict, htmlList,\
                  htmlInst, htmlString, htmlReprTypes
 
 
 
-from server import NOT_DONE_YET
+from .server import NOT_DONE_YET
 
 True = (1==1)
 False = not True
@@ -127,7 +127,7 @@
             if issubclass(base, Presentation) and base is not Presentation:
                 self.addClassVars(namespace, base)
         # 'lower' classes in the class heirarchy take precedence.
-        for k in Class.__dict__.keys():
+        for k in list(Class.__dict__.keys()):
             namespace[k] = getattr(self, k)
 
     def addVariables(self, namespace, request):
@@ -144,7 +144,7 @@
         """Utility: Call a method like StreamWidget's 'stream'.
         """
         io = StringIO()
-        apply(call, (io.write,) + args, kw)
+        call(*(io.write,) + args, **kw)
         return io.getvalue()
 
     def display(self, request):
@@ -168,11 +168,11 @@
                     log.deferr()
                     tm.append(webutil.formatFailure(failure.Failure()))
                 else:
-                    if isinstance(x, types.ListType):
+                    if isinstance(x, list):
                         tm.extend(x)
                     elif isinstance(x, Widget):
                         val = x.display(request)
-                        if not isinstance(val, types.ListType):
+                        if not isinstance(val, list):
                             raise Exception("%s.display did not return a list, it returned %s!" % (x.__class__, repr(val)))
                         tm.extend(val)
                     else:
@@ -369,7 +369,7 @@
                 description = ""
 
             if inputType == 'checkbox':
-                if request.args.has_key('__checkboxes__'):
+                if '__checkboxes__' in request.args:
                     if inputName in request.args['__checkboxes__']:
                         inputValue = 1
                     else:
@@ -377,7 +377,7 @@
                 else:
                     inputValue = 0
             elif inputType in ('checkgroup', 'radio'):
-                if request.args.has_key(inputName):
+                if inputName in request.args:
                     keys = request.args[inputName]
                 else:
                     keys = []
@@ -386,7 +386,7 @@
                 for optionName, optionDisplayName, checked in iv:
                     checked = optionName in keys
                     inputValue.append([optionName, optionDisplayName, checked])
-            elif request.args.has_key(inputName):
+            elif inputName in request.args:
                 iv = request.args[inputName][0]
                 if inputType in ['menu', 'multimenu']:
                     if iv in inputValue:
@@ -471,7 +471,7 @@
         for field in form:
             inputType, displayName, inputName, inputValue = field[:4]
             if inputType == 'checkbox':
-                if request.args.has_key('__checkboxes__'):
+                if '__checkboxes__' in request.args:
                     if inputName in request.args['__checkboxes__']:
                         formData = 1
                     else:
@@ -479,13 +479,13 @@
                 else:
                     formData = 0
             elif inputType in ['checkgroup', 'radio', 'multimenu']:
-                if args.has_key(inputName):
+                if inputName in args:
                     formData = args[inputName]
                     del args[inputName]
                 else:
                     formData = []
             else:
-                if not args.has_key(inputName):
+                if inputName not in args:
                     raise FormInputError("missing field %s." % repr(inputName))
                 formData = args[inputName]
                 del args[inputName]
@@ -503,11 +503,11 @@
         if submitAction:
             submitAction = submitAction[0]
         for field in ['submit', '__formtype__', '__checkboxes__']:
-            if args.has_key(field):
+            if field in args:
                 del args[field]
         if args and not self.formAcceptExtraArgs:
             raise FormInputError("unknown fields: %s" % repr(args))
-        return apply(self.process, (write, request, submitAction), kw)
+        return self.process(*(write, request, submitAction), **kw)
 
     def formatError(self,error):
         """Format an error message.
@@ -520,10 +520,10 @@
         args = request.args
         fid = self.getFormID()
         return (args and # there are arguments to the request
-                args.has_key('__formtype__') and # this is a widgets.Form request
+                '__formtype__' in args and # this is a widgets.Form request
                 args['__formtype__'][0] == reflect.qual(self.__class__) and # it is for a form of my type
                 ((not fid) or # I am only allowed one form per page
-                 (args.has_key('__formid__') and # if I distinguish myself from others, the request must too
+                 ('__formid__' in args and # if I distinguish myself from others, the request must too
                   args['__formid__'][0] == fid))) # I am in fact the same
 
     def tryAgain(self, err, req):
@@ -561,7 +561,7 @@
             val = self._doProcess(form, write, request)
             if val:
                 l.extend(val)
-        except FormInputError, fie:
+        except FormInputError as fie:
             write(self.formatError(str(fie)))
         return l
 
@@ -664,7 +664,7 @@
             result = [FORGET_IT]
 
         # Make sure result is a sequence,
-        if not type(result) in (types.ListType, types.TupleType):
+        if not type(result) in (list, tuple):
             result = [result]
 
         # If the deferred does not wish to produce its result all at
@@ -675,19 +675,19 @@
         if result[0] is NOT_DONE_YET:
             done = 0
             result = result[1]
-            if not type(result) in (types.ListType, types.TupleType):
+            if not type(result) in (list, tuple):
                 result = [result]
         else:
             done = 1
 
-        for i in xrange(len(result)):
+        for i in range(len(result)):
             item = result[i]
             if isinstance(item, defer.Deferred):
                 self._addDeferred(item, result, i)
 
         for position in range(len(self.lst)):
             item = self.lst[position]
-            if type(item) is types.TupleType and len(item) > 0:
+            if type(item) is tuple and len(item) > 0:
                 if item[0] is sentinel:
                     break
         else:
@@ -723,10 +723,10 @@
                 self.forgotten = 1
                 return
 
-            if isinstance(item, types.StringType):
+            if isinstance(item, bytes):
                 self.beforeBody = 0
                 self.request.write(item)
-            elif type(item) is types.TupleType and len(item) > 0:
+            elif type(item) is tuple and len(item) > 0:
                 if isinstance(item[0], self.Sentinel):
                     return
             elif isinstance(item, failure.Failure):
@@ -897,9 +897,9 @@
         #XXX: delete this after a while.
         if hasattr(self, "page"):
             log.msg("Gadget.page is deprecated, use Gadget.pageFactory instead")
-            return apply(self.page, args, kwargs)
+            return self.page(*args, **kwargs)
         else:
-            return apply(WidgetPage, args, kwargs)
+            return WidgetPage(*args, **kwargs)
 
     def getChild(self, path, request):
         if path == '':
@@ -914,14 +914,14 @@
                 p = self.pageFactory(widget)
                 p.isLeaf = getattr(widget,'isLeaf',0)
                 return p
-        elif self.paths.has_key(path):
+        elif path in self.paths:
             prefix = getattr(sys.modules[self.__module__], '__file__', '')
             if prefix:
                 prefix = os.path.abspath(os.path.dirname(prefix))
             return static.File(os.path.join(prefix, self.paths[path]))
 
         elif path == '__reload__':
-            return self.pageFactory(Reloader(map(reflect.namedModule, [self.__module__] + self.modules)))
+            return self.pageFactory(Reloader(list(map(reflect.namedModule, [self.__module__] + self.modules))))
         else:
             return error.NoResource("No such child resource in gadget.")
 
@@ -1047,4 +1047,4 @@
 
 components.registerAdapter(WebWidgetNodeMutator, Widget, template.INodeMutator)
 
-import static
+from . import static
--- twisted/web/wsgi.py (original)
+++ twisted/web/wsgi.py (refactored)
@@ -8,7 +8,7 @@
 
 __metaclass__ = type
 
-from urllib import unquote
+from urllib.parse import unquote
 
 from zope.interface import implements
 
@@ -218,7 +218,7 @@
         This will be called in a non-I/O thread.
         """
         if self.started and excInfo is not None:
-            raise excInfo[0], excInfo[1], excInfo[2]
+            raise excInfo[0](excInfo[1]).with_traceback(excInfo[2])
         self.status = status
         self.headers = headers
         return self.write
--- twisted/web/xmlrpc.py (original)
+++ twisted/web/xmlrpc.py (refactored)
@@ -9,8 +9,8 @@
 """
 
 # System Imports
-import xmlrpclib
-import urlparse
+from . import xmlrpc.client
+import urllib.parse
 
 # Sibling Imports
 from twisted.web import resource, server, http
@@ -23,10 +23,10 @@
 
 
 # Useful so people don't need to import xmlrpclib directly
-Fault = xmlrpclib.Fault
-Binary = xmlrpclib.Binary
-Boolean = xmlrpclib.Boolean
-DateTime = xmlrpclib.DateTime
+Fault = xmlrpc.client.Fault
+Binary = xmlrpc.client.Binary
+Boolean = xmlrpc.client.Boolean
+DateTime = xmlrpc.client.DateTime
 
 class NoSuchFunction(Fault):
     """
@@ -99,20 +99,20 @@
         return self.subHandlers.get(prefix, None)
 
     def getSubHandlerPrefixes(self):
-        return self.subHandlers.keys()
+        return list(self.subHandlers.keys())
 
     def render_POST(self, request):
         request.content.seek(0, 0)
         request.setHeader("content-type", "text/xml")
         try:
-            args, functionPath = xmlrpclib.loads(request.content.read())
-        except Exception, e:
+            args, functionPath = xmlrpc.client.loads(request.content.read())
+        except Exception as e:
             f = Fault(self.FAILURE, "Can't deserialize input: %s" % (e,))
             self._cbRender(f, request)
         else:
             try:
                 function = self._getFunction(functionPath)
-            except Fault, f:
+            except Fault as f:
                 self._cbRender(f, request)
             else:
                 defer.maybeDeferred(function, *args).addErrback(
@@ -128,11 +128,11 @@
         if not isinstance(result, Fault):
             result = (result,)
         try:
-            s = xmlrpclib.dumps(result, methodresponse=True,
+            s = xmlrpc.client.dumps(result, methodresponse=True,
                                 allow_none=self.allowNone)
-        except Exception, e:
+        except Exception as e:
             f = Fault(self.FAILURE, "Can't serialize output: %s" % (e,))
-            s = xmlrpclib.dumps(f, methodresponse=True,
+            s = xmlrpc.client.dumps(f, methodresponse=True,
                                 allow_none=self.allowNone)
         request.setHeader("content-length", str(len(s)))
         request.write(s)
@@ -169,7 +169,7 @@
         if not f:
             raise NoSuchFunction(self.NOT_FOUND,
                 "function %s not found" % functionPath)
-        elif not callable(f):
+        elif not hasattr(f, '__call__'):
             raise NoSuchFunction(self.NOT_FOUND,
                 "function %s not callable" % functionPath)
         else:
@@ -297,14 +297,14 @@
         self.path, self.host = path, host
         self.user, self.password = user, password
         self.payload = payloadTemplate % (method,
-            xmlrpclib.dumps(args, allow_none=allowNone))
+            xmlrpc.client.dumps(args, allow_none=allowNone))
         self.deferred = defer.Deferred()
 
     def parseResponse(self, contents):
         if not self.deferred:
             return
         try:
-            response = xmlrpclib.loads(contents)[0][0]
+            response = xmlrpc.client.loads(contents)[0][0]
         except:
             deferred, self.deferred = self.deferred, None
             deferred.errback(failure.Failure())
@@ -363,7 +363,7 @@
         @param allowNone: allow the use of None values in parameters. It's
         passed to the underlying xmlrpclib implementation. Default to False.
         """
-        scheme, netloc, path, params, query, fragment = urlparse.urlparse(url)
+        scheme, netloc, path, params, query, fragment = urllib.parse.urlparse(url)
         netlocParts = netloc.split('@')
         if len(netlocParts) == 2:
             userpass = netlocParts.pop(0).split(':')
--- twisted/web/_auth/wrapper.py (original)
+++ twisted/web/_auth/wrapper.py (refactored)
@@ -39,7 +39,7 @@
         """
         def generateWWWAuthenticate(scheme, challenge):
             l = []
-            for k,v in challenge.iteritems():
+            for k,v in challenge.items():
                 l.append("%s=%s" % (k, quoteString(v)))
             return "%s %s" % (scheme, ", ".join(l))
 
@@ -134,12 +134,13 @@
         return d
 
 
-    def _loginSucceeded(self, (interface, avatar, logout)):
+    def _loginSucceeded(self, xxx_todo_changeme):
         """
         Handle login success by wrapping the resulting L{IResource} avatar
         so that the C{logout} callback will be invoked when rendering is
         complete.
         """
+        (interface, avatar, logout) = xxx_todo_changeme
         class ResourceWrapper(proxyForInterface(IResource, 'resource')):
             """
             Wrap an L{IResource} so that whenever it or a child of it
--- twisted/web/test/test_http.py (original)
+++ twisted/web/test/test_http.py (refactored)
@@ -5,8 +5,8 @@
 Test HTTP support.
 """
 
-from urlparse import urlparse, urlunsplit, clear_cache
-import random, urllib, cgi
+from urllib.parse import urlparse, urlunsplit, clear_cache
+import random, urllib.request, urllib.parse, urllib.error, cgi
 
 from twisted.python.compat import set
 from twisted.trial import unittest
@@ -270,7 +270,7 @@
     Make a request with the given request headers for the persistence tests.
     """
     request = http.Request(DummyChannel(), None)
-    for k, v in headers.iteritems():
+    for k, v in headers.items():
         request.requestHeaders.setRawHeaders(k, v)
     return request
 
@@ -293,7 +293,7 @@
         for req, version, correctResult, resultHeaders in self.ptests:
             result = c.checkPersistence(req, version)
             self.assertEquals(result, correctResult)
-            for header in resultHeaders.keys():
+            for header in list(resultHeaders.keys()):
                 self.assertEquals(req.responseHeaders.getRawHeaders(header, None), resultHeaders[header])
 
 
@@ -687,16 +687,16 @@
             raise unittest.SkipTest("_c_urlarg module is not available")
         # work exactly like urllib.unquote, including stupid things
         # % followed by a non-hexdigit in the middle and in the end
-        self.failUnlessEqual(urllib.unquote("%notreally%n"),
+        self.failUnlessEqual(urllib.parse.unquote("%notreally%n"),
             _c_urlarg.unquote("%notreally%n"))
         # % followed by hexdigit, followed by non-hexdigit
-        self.failUnlessEqual(urllib.unquote("%1quite%1"),
+        self.failUnlessEqual(urllib.parse.unquote("%1quite%1"),
             _c_urlarg.unquote("%1quite%1"))
         # unquoted text, followed by some quoted chars, ends in a trailing %
-        self.failUnlessEqual(urllib.unquote("blah%21%40%23blah%"),
+        self.failUnlessEqual(urllib.parse.unquote("blah%21%40%23blah%"),
             _c_urlarg.unquote("blah%21%40%23blah%"))
         # Empty string
-        self.failUnlessEqual(urllib.unquote(""), _c_urlarg.unquote(""))
+        self.failUnlessEqual(urllib.parse.unquote(""), _c_urlarg.unquote(""))
 
     def testParseqs(self):
         self.failUnlessEqual(cgi.parse_qs("a=b&d=c;+=f"),
@@ -768,7 +768,7 @@
         """
         L{http.urlparse} should reject unicode input early.
         """
-        self.assertRaises(TypeError, http.urlparse, u'http://example.org/path')
+        self.assertRaises(TypeError, http.urlparse, 'http://example.org/path')
 
 
     def testEscchar(self):
@@ -941,7 +941,7 @@
         """
         req = http.Request(DummyChannel(), None)
         req.setResponseCode(1)
-        req.setResponseCode(1L)
+        req.setResponseCode(1)
         self.assertRaises(TypeError, req.setResponseCode, "1")
 
 
--- twisted/web/test/test_http_headers.py (original)
+++ twisted/web/test/test_http_headers.py (refactored)
@@ -184,7 +184,7 @@
         them both.
         """
         h = Headers()
-        for k, v in kw.iteritems():
+        for k, v in kw.items():
             h.setRawHeaders(k, v)
         return h, _DictHeaders(h)
 
@@ -396,8 +396,8 @@
         C{False} otherwise.
         """
         headers, wrapper = self.headers(foo=["lemur"])
-        self.assertTrue(wrapper.has_key("foo"))
-        self.assertFalse(wrapper.has_key("bar"))
+        self.assertTrue("foo" in wrapper)
+        self.assertFalse("bar" in wrapper)
 
 
     def test_contains(self):
--- twisted/web/test/test_httpauth.py (original)
+++ twisted/web/test/test_httpauth.py (refactored)
@@ -395,7 +395,7 @@
         return ', '.join([
                 '%s=%s%s%s' % (k, quote, v, quote)
                 for (k, v)
-                in kw.iteritems()
+                in kw.items()
                 if v is not None])
 
 
@@ -436,7 +436,7 @@
         self.assertEquals(challenge['algorithm'], 'md5')
         self.assertIn('nonce', challenge)
         self.assertIn('opaque', challenge)
-        for v in challenge.values():
+        for v in list(challenge.values()):
             self.assertNotIn('\n', v)
 
 
--- twisted/web/test/test_mvc.py (original)
+++ twisted/web/test/test_mvc.py (refactored)
@@ -7,7 +7,7 @@
 import random
 
 try:
-    import cPickle as pickle
+    import pickle as pickle
 except ImportError:
     import pickle
 
@@ -36,9 +36,9 @@
         self.controller = interfaces.IController(self.model, None)
 
     def modelChanged(self, changed):
-        if changed.has_key('foo'):
+        if 'foo' in changed:
             self.foo = changed['foo']
-        if changed.has_key('random'):
+        if 'random' in changed:
             self.random = changed['random']
 
     def twiddleControl(self, newValue):
@@ -63,7 +63,7 @@
         self.persist()
     
     def doRandom(self):
-        rnd = random.choice(range(100))
+        rnd = random.choice(list(range(100)))
         self.model.random = rnd
         self.model.notify({'random': rnd})
         self.persist()
--- twisted/web/test/test_static.py (original)
+++ twisted/web/test/test_static.py (refactored)
@@ -585,7 +585,7 @@
         """
         lister = static.DirectoryLister(None)
         elements = [{"href": "", "text": "", "size": "", "type": "",
-                     "encoding": ""}  for i in xrange(5)]
+                     "encoding": ""}  for i in range(5)]
         content = lister._buildTableContent(elements)
 
         self.assertEquals(len(content), 5)
--- twisted/web/test/test_web.py (original)
+++ twisted/web/test/test_web.py (refactored)
@@ -5,7 +5,7 @@
 Tests for various parts of L{twisted.web}.
 """
 
-from cStringIO import StringIO
+from io import StringIO
 
 from zope.interface import implements
 
@@ -195,7 +195,7 @@
             self.written.write(bytes)
 
         def writeSequence(self, iovec):
-            map(self.write, iovec)
+            list(map(self.write, iovec))
 
         def getHost(self):
             return IPv4Address("TCP", '10.0.0.1', self.port)
--- twisted/web/test/test_webclient.py (original)
+++ twisted/web/test/test_webclient.py (refactored)
@@ -7,7 +7,7 @@
 
 import os
 
-from urlparse import urlparse
+from urllib.parse import urlparse
 
 from twisted.trial import unittest
 from twisted.web import server, static, client, error, util, resource
@@ -30,7 +30,7 @@
 class CookieMirrorResource(resource.Resource):
     def render(self, request):
         l = []
-        for k,v in request.received_cookies.items():
+        for k,v in list(request.received_cookies.items()):
             l.append((k, v))
         l.sort()
         return repr(l)
@@ -143,7 +143,7 @@
         elements of its return tuple, even when passed an URL which has
         previously been passed to L{urlparse} as a C{unicode} string.
         """
-        badInput = u'http://example.com/path'
+        badInput = 'http://example.com/path'
         goodInput = badInput.encode('ascii')
         urlparse(badInput)
         scheme, host, port, path = client._parse(goodInput)
@@ -294,7 +294,7 @@
         def cleanup(passthrough):
             # Clean up the server which is hanging around not doing
             # anything.
-            connected = self.wrapper.protocols.keys()
+            connected = list(self.wrapper.protocols.keys())
             # There might be nothing here if the server managed to already see
             # that the connection was lost.
             if connected:
@@ -322,7 +322,7 @@
     def testDownloadPageError1(self):
         class errorfile:
             def write(self, data):
-                raise IOError, "badness happened during write"
+                raise IOError("badness happened during write")
             def close(self):
                 pass
         ef = errorfile()
@@ -335,7 +335,7 @@
             def write(self, data):
                 pass
             def close(self):
-                raise IOError, "badness happened during close"
+                raise IOError("badness happened during close")
         ef = errorfile()
         return self.assertFailure(
             client.downloadPage(self.getURL("file"), ef),
@@ -354,7 +354,7 @@
         return d
 
     def _cleanupDownloadPageError3(self, ignored):
-        os.chmod("unwritable", 0700)
+        os.chmod("unwritable", 0o700)
         os.unlink("unwritable")
         return ignored
 
@@ -514,8 +514,8 @@
         tlsRoot.putChild('four', static.Data('FOUND IT!', 'text/plain'))
 
     def tearDown(self):
-        ds = map(defer.maybeDeferred,
-                 [self.plainPort.stopListening, self.tlsPort.stopListening])
+        ds = list(map(defer.maybeDeferred,
+                 [self.plainPort.stopListening, self.tlsPort.stopListening]))
         return defer.gatherResults(ds)
 
     def testHoppingAround(self):
--- twisted/web/test/test_woven.py (original)
+++ twisted/web/test/test_woven.py (refactored)
@@ -244,7 +244,7 @@
     def testOutput(self):
         listNode = self.d.getElementById("first")
         assert listNode, "Test %s failed" % outputNum
-        liNodes = filter(lambda x: hasattr(x, 'tagName') and x.tagName == 'li', listNode.childNodes)
+        liNodes = [x for x in listNode.childNodes if hasattr(x, 'tagName') and x.tagName == 'li']
 #        print len(liNodes), len(self.m.data), liNodes, self.m.data
         assert len(liNodes) == len(self.m.data), "Test %s failed" % outputNum
         for i in range(len(liNodes)):
@@ -433,7 +433,7 @@
     def __init__(self, *args, **kw):
         server.Request.__init__(self, *args, **kw)
         self._cookieCache = {}
-        from cStringIO import StringIO
+        from io import StringIO
         self.content = StringIO()
         self.received_headers['host'] = 'fake.com'
         self.written = StringIO()
@@ -444,7 +444,7 @@
     
     def addCookie(self, k, v, *args,**kw):
         server.Request.addCookie(self,k,v,*args,**kw)
-        assert not self._cookieCache.has_key(k), "Should not be setting duplicate cookies!"
+        assert k not in self._cookieCache, "Should not be setting duplicate cookies!"
         self._cookieCache[k] = v
         self.channel.received_cookies[k] = v
 
@@ -476,17 +476,17 @@
         # session
         req = FakeHTTPRequest(chan, queued=0)
         req.requestReceived("GET", "/xxx/yyy", "1.0")
-        assert len(req._cookieCache.values()) == 0, req._cookieCache.values()
+        assert len(list(req._cookieCache.values())) == 0, list(req._cookieCache.values())
         self.assertEquals(req.getSession(),None)
 
         # now we're going to make sure that the redirect and cookie are properly set
         req = FakeHTTPRequest(chan, queued=0)
         req.requestReceived("GET", "/xxx/"+guard.INIT_SESSION, "1.0")
-        ccv = req._cookieCache.values()
+        ccv = list(req._cookieCache.values())
         self.assertEquals(len(ccv),1)
         cookie = ccv[0]
         # redirect set?
-        self.failUnless(req.headers.has_key('location'))
+        self.failUnless('location' in req.headers)
         # redirect matches cookie?
         self.assertEquals(req.headers['location'].split('/')[-1], guard.SESSION_KEY+cookie)
         # URL is correct?
@@ -499,7 +499,7 @@
         req = chan.makeFakeRequest(url)
         self.assertEquals(req.headers['location'].split('?')[0],
                           'http://fake.com/xxx/')
-        for sz in swrap.sessions.values():
+        for sz in list(swrap.sessions.values()):
             sz.expire()
 
 
--- twisted/web/test/test_wsgi.py (original)
+++ twisted/web/test/test_wsgi.py (refactored)
@@ -8,9 +8,9 @@
 __metaclass__ = type
 
 from sys import exc_info
-from urllib import quote
-from StringIO import StringIO
-from thread import get_ident
+from urllib.parse import quote
+from io import StringIO
+from _thread import get_ident
 
 from zope.interface.verify import verifyObject
 
@@ -200,7 +200,8 @@
     object by L{twisted.web.wsgi.WSGIResource}.
     """
     def environKeyEqual(self, key, value):
-        def assertEnvironKeyEqual((environ, startResponse)):
+        def assertEnvironKeyEqual(xxx_todo_changeme):
+            (environ, startResponse) = xxx_todo_changeme
             self.assertEqual(environ[key], value)
         return assertEnvironKeyEqual
 
@@ -211,7 +212,8 @@
         parameter which is exactly of type C{dict}.
         """
         d = self.render('GET', '1.1', [], [''])
-        def cbRendered((environ, startResponse)):
+        def cbRendered(xxx_todo_changeme1):
+            (environ, startResponse) = xxx_todo_changeme1
             self.assertIdentical(type(environ), dict)
         d.addCallback(cbRendered)
         return d
@@ -425,7 +427,8 @@
         """
         singleValue = self.render(
             'GET', '1.1', [], [''], None, [('foo', 'bar'), ('baz', 'quux')])
-        def cbRendered((environ, startResponse)):
+        def cbRendered(xxx_todo_changeme2):
+            (environ, startResponse) = xxx_todo_changeme2
             self.assertEqual(environ['HTTP_FOO'], 'bar')
             self.assertEqual(environ['HTTP_BAZ'], 'quux')
         singleValue.addCallback(cbRendered)
@@ -522,7 +525,8 @@
         self.addCleanup(removeObserver, events.append)
 
         errors = self.render('GET', '1.1', [], [''])
-        def cbErrors((environ, startApplication)):
+        def cbErrors(xxx_todo_changeme3):
+            (environ, startApplication) = xxx_todo_changeme3
             errors = environ['wsgi.errors']
             errors.write('some message\n')
             errors.writelines(['another\nmessage\n'])
--- twisted/web/test/test_xml.py (original)
+++ twisted/web/test/test_xml.py (refactored)
@@ -543,8 +543,8 @@
     def testUnicodeTolerance(self):
         import struct
         s = '<foo><bar><baz /></bar></foo>'
-        j =(u'<?xml version="1.0" encoding="UCS-2" ?>\r\n<JAPANESE>\r\n'
-            u'<TITLE>\u5c02\u9580\u5bb6\u30ea\u30b9\u30c8 </TITLE></JAPANESE>')
+        j =('<?xml version="1.0" encoding="UCS-2" ?>\r\n<JAPANESE>\r\n'
+            '<TITLE>\u5c02\u9580\u5bb6\u30ea\u30b9\u30c8 </TITLE></JAPANESE>')
         j2=('\xff\xfe<\x00?\x00x\x00m\x00l\x00 \x00v\x00e\x00r\x00s\x00i\x00o'
             '\x00n\x00=\x00"\x001\x00.\x000\x00"\x00 \x00e\x00n\x00c\x00o\x00d'
             '\x00i\x00n\x00g\x00=\x00"\x00U\x00C\x00S\x00-\x002\x00"\x00 \x00?'
@@ -568,14 +568,14 @@
 
         # test that raw text still gets encoded
         # test that comments get encoded
-        j3=microdom.parseString(u'<foo/>')
+        j3=microdom.parseString('<foo/>')
         hdr='<?xml version="1.0"?>'
-        div=microdom.lmx().text(u'\u221a', raw=1).node
+        div=microdom.lmx().text('\u221a', raw=1).node
         de=j3.documentElement
         de.appendChild(div)
-        de.appendChild(j3.createComment(u'\u221a'))
+        de.appendChild(j3.createComment('\u221a'))
         self.assertEquals(j3.toxml(), hdr+
-                          u'<foo><div>\u221a</div><!--\u221a--></foo>'.encode('utf8'))
+                          '<foo><div>\u221a</div><!--\u221a--></foo>'.encode('utf8'))
 
     def testNamedChildren(self):
         tests = {"<foo><bar /><bar unf='1' /><bar>asdfadsf</bar>"
@@ -583,7 +583,7 @@
                  '<foo>asdf</foo>' : 0,
                  '<foo><bar><bar></bar></bar></foo>' : 1,
                  }
-        for t in tests.keys():
+        for t in list(tests.keys()):
             node = microdom.parseString(t).documentElement
             result = domhelpers.namedChildren(node, 'bar')
             self.assertEquals(len(result), tests[t])
--- twisted/web/test/test_xmlrpc.py (original)
+++ twisted/web/test/test_xmlrpc.py (refactored)
@@ -8,7 +8,7 @@
 """
 
 try:
-    import xmlrpclib
+    import xmlrpc.client
 except ImportError:
     xmlrpclib = None
     class XMLRPC: pass
@@ -211,7 +211,7 @@
         d = client.getPage("http://127.0.0.1:%d/" % (self.port,),
                            method="POST", postdata="foo")
         def cb(result):
-            self.assertRaises(xmlrpc.Fault, xmlrpclib.loads, result)
+            self.assertRaises(xmlrpc.Fault, xmlrpc.client.loads, result)
         d.addCallback(cb)
         return d
 
@@ -402,7 +402,7 @@
             path=None, host=None, method='POST', user=None, password=None,
             allowNone=False, args=())
         # An XML-RPC response that will parse without raising an error.
-        self.goodContents = xmlrpclib.dumps(('',))
+        self.goodContents = xmlrpc.client.dumps(('',))
         # An 'XML-RPC response' that will raise a parsing error.
         self.badContents = 'invalid xml'
         # A dummy 'reason' to pass to clientConnectionLost. We don't care
--- twisted/web/woven/controller.py (original)
+++ twisted/web/woven/controller.py (refactored)
@@ -4,7 +4,7 @@
 # See LICENSE for details.
 
 
-from __future__ import nested_scopes
+
 
 __version__ = "$Revision: 1.67 $"[11:-2]
 
@@ -60,7 +60,7 @@
         if inputhandlers is None and controllers is None:
             self._inputhandlers = []
         elif inputhandlers:
-            print "The inputhandlers arg is deprecated, please use controllers instead"
+            print("The inputhandlers arg is deprecated, please use controllers instead")
             self._inputhandlers = inputhandlers
         else:
             self._inputhandlers = controllers
@@ -96,7 +96,7 @@
                 warnings.warn("factory_ methods are deprecated; please use "
                               "wcfactory_ instead", DeprecationWarning)
         if cm:
-            if cm.func_code.co_argcount == 1 and not type(cm) == types.LambdaType:
+            if cm.__code__.co_argcount == 1 and not type(cm) == types.LambdaType:
                 warnings.warn("A Controller Factory takes "
                               "(request, node, model) "
                               "now instead of (model)", DeprecationWarning)
@@ -186,7 +186,7 @@
             ih._parent = self
             ih.handle(request)
         self._inputhandlers = []
-        for key, value in self._valid.items():
+        for key, value in list(self._valid.items()):
             key.commit(request, None, value)
         self._valid = {}
         return self.renderView(request)
@@ -212,7 +212,7 @@
     def gatheredControllers(self, v, d, request):
         process = {}
         request.args = {}
-        for key, value in self._valid.items():
+        for key, value in list(self._valid.items()):
             key.commit(request, None, value)
             process[key.submodel] = value
         self.process(request, **process)
@@ -277,10 +277,10 @@
         # Check to see if we're hooking up an output conduit
         sess = request.getSession(interfaces.IWovenLivePage)
         #print "REQUEST.ARGS", request.args
-        if request.args.has_key('woven_hookupOutputConduitToThisFrame'):
+        if 'woven_hookupOutputConduitToThisFrame' in request.args:
             sess.hookupOutputConduit(request)
             return server.NOT_DONE_YET
-        if request.args.has_key('woven_clientSideEventName'):
+        if 'woven_clientSideEventName' in request.args:
             try:
                 request.d = microdom.parseString('<xml/>', caseInsensitive=0, preserveCase=0)
                 eventName = request.args['woven_clientSideEventName'][0]
@@ -311,9 +311,9 @@
         sess = request.getSession(interfaces.IWovenLivePage)
         self.view = sess.getCurrentPage().view
         #request.d = self.view.d
-        print "clientToServerEvent", eventTarget
+        print("clientToServerEvent", eventTarget)
         target = self.view.subviews[eventTarget]
-        print "target, parent", target, target.parent
+        print("target, parent", target, target.parent)
         #target.parent = self.view
         #target.controller._parent = self
 
@@ -349,7 +349,7 @@
 
     def domChanged(self, request, widget, node):
         sess = request.getSession(interfaces.IWovenLivePage)
-        print "domchanged"
+        print("domchanged")
         if sess is not None:
             if not hasattr(node, 'getAttribute'):
                 return
@@ -374,7 +374,7 @@
             #for key in widget.subviews.keys():
             #    view.subviews[key].unlinkViews()
             oldNode = page.view.subviews[nodeId]
-            for id, subview in oldNode.subviews.items():
+            for id, subview in list(oldNode.subviews.items()):
                 subview.unlinkViews()
             topSubviews = page.view.subviews
             #print "Widgetid, subviews", id(widget), widget.subviews
@@ -382,7 +382,7 @@
                 def recurseSubviews(w):
                     #print "w.subviews", w.subviews
                     topSubviews.update(w.subviews)
-                    for id, sv in w.subviews.items():
+                    for id, sv in list(w.subviews.items()):
                         recurseSubviews(sv)
                 #print "recursing"
                 recurseSubviews(widget)
--- twisted/web/woven/dirlist.py (original)
+++ twisted/web/woven/dirlist.py (refactored)
@@ -6,7 +6,7 @@
 
 # system imports
 from os.path import join as joinpath
-import urllib, os
+import urllib.request, urllib.parse, urllib.error, os
 
 # sibling imports
 import page, model, widgets, view
@@ -89,7 +89,7 @@
         files = []; dirs = []
 
         for path in directory:
-            url = urllib.quote(path, "/")
+            url = urllib.parse.quote(path, "/")
             if os.path.isdir(os.path.join(self.path, path)):
                 url = url + '/'
                 dirs.append({'link':{"text": path + "/", "href":url},
@@ -106,7 +106,7 @@
         return files + dirs
 
     def wmfactory_header(self, request):
-        return "Directory listing for %s" % urllib.unquote(request.uri)
+        return "Directory listing for %s" % urllib.parse.unquote(request.uri)
 
     def __repr__(self):  
         return '<DirectoryLister of %r>' % self.path
--- twisted/web/woven/flashconduit.py (original)
+++ twisted/web/woven/flashconduit.py (refactored)
@@ -8,11 +8,11 @@
     delimiter = '\0'
     keepalive = 1
     def connectionMade(self):
-        print "connection with flash movie opened"
+        print("connection with flash movie opened")
         #self.transport.write("alert('helllllllo')\0")
 
     def connectionLost(self, reason):
-        print "connection lost"
+        print("connection lost")
         #self.lp.unhookOutputConduit()
 
     def lineReceived(self, line):
--- twisted/web/woven/form.py (original)
+++ twisted/web/woven/form.py (refactored)
@@ -3,7 +3,7 @@
 # WORK IN PROGRESS: HARD HAT REQUIRED
 # 
 
-from __future__ import nested_scopes
+
 
 # Twisted Imports
 
@@ -30,7 +30,7 @@
     The renderer function should act in the same way
     as the 'input_XXX' methods of C{FormFillerWidget}.
     """
-    assert callable(renderer)
+    assert hasattr(renderer, '__call__')
     global _renderers
     _renderers[argumentClass] = renderer
 
@@ -96,7 +96,7 @@
         return content.input(**arguments)
 
     def input_string(self, request, content, model, templateAttributes={}):
-        if not templateAttributes.has_key("size"):
+        if "size" not in templateAttributes:
             templateAttributes["size"] = '60'
         return self.input_single(request, content, model, templateAttributes)
 
@@ -263,7 +263,7 @@
     def input_verifiedpassword(self, request, content, model, templateAttributes={}):
         breakLines = model.getHint('breaklines', 1)
         values = self.getValues(request, model)
-        if isinstance(values, (str, unicode)):
+        if isinstance(values, (str, str)):
             values = (values, values)
         if not values:
             p1, p2 = "", ""
@@ -285,7 +285,7 @@
 
     def convergeInput(self, request, content, model, templateNode):
         name = model.__class__.__name__.lower()
-        if _renderers.has_key(model.__class__):
+        if model.__class__ in _renderers:
             imeth = _renderers[model.__class__]
         else:
             imeth = getattr(self,"input_"+name)
@@ -294,7 +294,7 @@
     
     def createInput(self, request, shell, model, templateAttributes={}):
         name = model.__class__.__name__.lower()
-        if _renderers.has_key(model.__class__):
+        if model.__class__ in _renderers:
             imeth = _renderers[model.__class__]
         else:
             imeth = getattr(self,"input_"+name)
@@ -344,7 +344,7 @@
             if not inNode.hasAttribute("name"):
                 continue
             nName = inNode.getAttribute("name")
-            if argz.has_key(nName):
+            if nName in argz:
                 #send an empty content shell - we just want the node
                 inputNodes[nName] = self.convergeInput(request, lmx(),
                                                        argz[nName], inNode)
@@ -358,7 +358,7 @@
         if argz:
             shell = self.createShell(request, node, data)
             # create inputs, in the same order they were passed to us:
-            for remArg in [arg for arg in argList if argz.has_key(arg.name)]:
+            for remArg in [arg for arg in argList if arg.name in argz]:
                 inputNode, errorNode = self.createInput(request, shell, remArg)
                 errorNodes[remArg.name] = errorNode
                 inputNodes[remArg.name] = inputNode
@@ -370,7 +370,7 @@
 class FormErrorWidget(FormFillerWidget):
     def setUp(self, request, node, data):
         FormFillerWidget.setUp(self, request, node, data)
-        for k, f in self.model.err.items():
+        for k, f in list(self.model.err.items()):
             en = self.errorNodes[k]
             tn = self.inputNodes[k]
             en.setAttribute('class', 'formError')
@@ -405,7 +405,7 @@
 class _RequestHack(model.MethodModel):
     def wmfactory_hack(self, request):
         rv = [[str(a), repr(b)] for (a, b)
-              in request._outDict.items()]
+              in list(request._outDict.items())]
         #print 'hack', rv
         return rv
 
@@ -454,7 +454,7 @@
                     outObj = self.formMethod.call(request=request, **outDict)
                 else:
                     outObj = self.formMethod.call(**outDict)
-            except formmethod.FormException, e:
+            except formmethod.FormException as e:
                 err = request.errorInfo = self.errorModelFactory(
                     request.args, outDict, e)
                 return self.errback(err).render(request)
--- twisted/web/woven/guard.py (original)
+++ twisted/web/woven/guard.py (refactored)
@@ -10,13 +10,13 @@
 L{UsernamePasswordWrapper}.
 """
 
-from __future__ import nested_scopes
+
 
 __version__ = "$Revision: 1.34 $"[11:-2]
 
 import random
 import time
-import urllib
+import urllib.request, urllib.parse, urllib.error
 
 # Twisted Imports
 
@@ -67,7 +67,7 @@
             return x
 
     def setClientForService(self, ident, perspective, client, service):
-        if self.services.has_key(service):
+        if service in self.services:
             p, c, i = self.services[service]
             p.detached(c, ident)
             del self.services[service]
@@ -135,7 +135,7 @@
         self.checkExpiredID = None
         # If I haven't been touched in 15 minutes:
         if time.time() - self.lastModified > self.lifetime / 2:
-            if self.guard.sessions.has_key(self.uid):
+            if self.uid in self.guard.sessions:
                 self.expire()
             else:
                 log.msg("no session to expire: %s" % self.uid)
@@ -145,7 +145,7 @@
                                                     self.checkExpired)
     def __getstate__(self):
         d = self.__dict__.copy()
-        if d.has_key('checkExpiredID'):
+        if 'checkExpiredID' in d:
             del d['checkExpiredID']
         return d
 
@@ -173,7 +173,7 @@
     args = request.args.copy()
     args.update(kw)
     if args:
-        ret += '?'+urllib.urlencode(args)
+        ret += '?'+urllib.parse.urlencode(args)
     return ret
 
 def redirectToSession(request, garbage):
@@ -370,9 +370,9 @@
                 return DeferredResource(
                     self.portal.login(Anonymous(), None, IResource
                                       ).addCallback(
-                    lambda (interface, avatarAspect, logout):
-                    getResource(s.setResourceForPortal(avatarAspect,
-                                           self.portal, logout),
+                    lambda interface_avatarAspect_logout:
+                    getResource(s.setResourceForPortal(interface_avatarAspect_logout[1],
+                                           self.portal, interface_avatarAspect_logout[2]),
                                 path, request)))
 
 
--- twisted/web/woven/input.py (original)
+++ twisted/web/woven/input.py (refactored)
@@ -149,7 +149,7 @@
         else:
             func = self._commit
             if hasattr(func, 'im_func'):
-                func = func.im_func
+                func = func.__func__
             args, varargs, varkw, defaults = inspect.getargspec(func)
             if args[1] == 'request':
                 self._commit(request, data)
@@ -263,7 +263,7 @@
             # keyword arguments it takes
             func = self._commit
             if hasattr(func, 'im_func'):
-                func = func.im_func
+                func = func.__func__
             args, varargs, varkw, defaults = inspect.getargspec(
                 func)
             wantsRequest = len(args) > 1 and args[1] == 'request'
@@ -310,7 +310,7 @@
             #arguments it takes
             func = self._commit
             if hasattr(func, 'im_func'):
-                func = func.im_func
+                func = func.__func__
             args, varargs, varkw, defaults = inspect.getargspec(func)
             self.numArgs = len(args)
             wantsRequest = args[1] == 'request'
--- twisted/web/woven/model.py (original)
+++ twisted/web/woven/model.py (refactored)
@@ -115,8 +115,8 @@
                 retVal.append((ref, ref.modelChanged(changed)))
             else:
                 self.views.remove(view)
-        for key, value in self.subviews.items():
-            if value.wantsAllNotifications or changed.has_key(key):
+        for key, value in list(self.subviews.items()):
+            if value.wantsAllNotifications or key in changed:
                 for item in list(value):
                     ref = item()
                     if ref is not None:
@@ -192,7 +192,7 @@
         Deferred, then I ought to check for cached values (created by
         L{setSubmodel}) before doing a regular Deferred lookup.
         """
-        if self.submodels.has_key(name):
+        if name in self.submodels:
             return self.submodels[name]
         if not self.submodelCheck(request, name):
             return None
@@ -211,7 +211,7 @@
         cache.
         """
         if self.submodelCheck(request, name):
-            if self.submodels.has_key(name):
+            if name in self.submodels:
                 del self.submodels[name]
             setattr(self, name, value)
 
@@ -256,7 +256,7 @@
             name = request
             request = None
 
-        cached = self.submodels.has_key(name)
+        cached = name in self.submodels
         sm = Model.getSubmodel(self, request, name)
         if sm is not None:
             if not cached:
@@ -312,7 +312,7 @@
             warnings.warn("Warning!")
             name = request
             request = None
-        if self.submodels.has_key(name):
+        if name in self.submodels:
             return self.submodels[name]
         orig = self.original
         try:
@@ -378,7 +378,7 @@
             warnings.warn("getSubmodel must get a request argument now")
             name = request
             request = None
-        if self.submodels.has_key(name):
+        if name in self.submodels:
             return self.submodels[name]
         orig = self.original
         if name not in orig:
@@ -418,7 +418,7 @@
             warnings.warn("Warning!")
             name = request
             request = None
-        if self.submodels.has_key(name):
+        if name in self.submodels:
             return self.submodels[name]
         sm = adaptToIModel(getattr(self.original, name), self, name)
         self.submodels[name] = sm
@@ -444,10 +444,10 @@
             warnings.warn("Warning!")
             name = request
             request = None
-        if self.submodels.has_key(name):
+        if name in self.submodels:
             return self.submodels[name]
         value = getattr(self.original, name)
-        if callable(value):
+        if hasattr(value, '__call__'):
             return value()
         sm = adaptToIModel(value, self, name)
         self.submodels = sm
@@ -476,10 +476,10 @@
         self.text = text
 
 try:
-    components.registerAdapter(StringModel, types.StringType, interfaces.IModel)
-    components.registerAdapter(ListModel, types.ListType, interfaces.IModel)
-    components.registerAdapter(ListModel, types.TupleType, interfaces.IModel)
-    components.registerAdapter(DictionaryModel, types.DictionaryType, interfaces.IModel)
+    components.registerAdapter(StringModel, bytes, interfaces.IModel)
+    components.registerAdapter(ListModel, list, interfaces.IModel)
+    components.registerAdapter(ListModel, tuple, interfaces.IModel)
+    components.registerAdapter(DictionaryModel, dict, interfaces.IModel)
     components.registerAdapter(DeferredWrapper, defer.Deferred, interfaces.IModel)
     components.registerAdapter(DeferredWrapper, defer.DeferredList, interfaces.IModel)
 except ValueError:
--- twisted/web/woven/simpleguard.py (original)
+++ twisted/web/woven/simpleguard.py (refactored)
@@ -26,7 +26,7 @@
     def __init__(self, name=None):
         self.name = name
 
-    def __nonzero__(self):
+    def __bool__(self):
         return bool(self.name)
 
 
--- twisted/web/woven/tapestry.py (original)
+++ twisted/web/woven/tapestry.py (refactored)
@@ -5,7 +5,7 @@
 THIS MODULE IS HIGHLY EXPERIMENTAL AND MAY BE DEPRECATED SOON.
 """
 
-from __future__ import nested_scopes
+
 
 __version__ = "$Revision: 1.13 $"[11:-2]
 
--- twisted/web/woven/template.py (original)
+++ twisted/web/woven/template.py (refactored)
@@ -57,7 +57,7 @@
 import warnings
 
 try:
-    import cPickle as pickle
+    import pickle as pickle
 except ImportError:
     import pickle
 
@@ -130,7 +130,7 @@
         if self.data:
             try:
                 child = microdom.parseString(self.data)
-            except Exception, e:
+            except Exception as e:
                 log.msg("Error parsing return value, probably invalid xml:", e)
                 child = request.d.createTextNode(self.data)
         else:
@@ -171,7 +171,7 @@
             self.d = microdom.parseString(template)
         else:
             if not self.templateFile:
-                raise AttributeError, "%s does not define self.templateFile to operate on" % self.__class__
+                raise AttributeError("%s does not define self.templateFile to operate on" % self.__class__)
             self.d = self.lookupTemplate(request)
         self.handleDocument(request, self.d)
         return NOT_DONE_YET
@@ -297,7 +297,7 @@
         if viewName:
             method = getattr(self, "factory_" + viewName, None)
             if not method:
-                raise NotImplementedError, "You specified view name %s on a node, but no factory_%s method was found." % (viewName, viewName)
+                raise NotImplementedError("You specified view name %s on a node, but no factory_%s method was found." % (viewName, viewName))
 
             result = method(request, node)
             node = self.dispatchResult(request, node, result)
--- twisted/web/woven/utils.py (original)
+++ twisted/web/woven/utils.py (refactored)
@@ -1,4 +1,4 @@
-from __future__ import nested_scopes
+
 
 from types import ClassType
 
@@ -58,14 +58,14 @@
         """
         if self.output is None:
             self.cached.append(text)
-            print "CACHING", `self.cached`
+            print("CACHING", repr(self.cached))
         else:
             if isinstance(text, Script):
                 if hasattr(self.output, 'writeScript'):
                     self.output.writeScript(text.script)
                     return
                 text = '<script language="%s">%s</script>\r\n' % (text.type, text.script)
-            print "WRITING", text
+            print("WRITING", text)
             if text[-1] != '\n':
                 text += '\n'
             self.output.write(text)
@@ -73,7 +73,7 @@
     def sendScript(self, js):
         self.write(Script(js))
         if self.output is not None and not getattr(self.output, 'keepalive', None):
-            print "## woot, teh connection was open"
+            print("## woot, teh connection was open")
             ## Close the connection; the javascript will have to open it again to get the next event.
             self.output.finish()
             self.output = None
@@ -82,7 +82,7 @@
         """Hook up the given request as the output conduit for this
         session.
         """
-        print "TOOT! WE HOOKED UP OUTPUT!", `self.cached`
+        print("TOOT! WE HOOKED UP OUTPUT!", repr(self.cached))
         self.output = request
         for text in self.cached:
             self.write(text)
@@ -100,17 +100,17 @@
         """Hook up the given object as the input conduit for this
         session.
         """
-        print "HOOKING UP", self.inputCache
+        print("HOOKING UP", self.inputCache)
         self.input = obj
         for text in self.inputCache:
             self.pushThroughInputConduit(text)
         self.inputCache = []
-        print "DONE HOOKING", self.inputCache
+        print("DONE HOOKING", self.inputCache)
 
     def pushThroughInputConduit(self, inp):
         """Push some text through the input conduit.
         """
-        print "PUSHING INPUT", inp
+        print("PUSHING INPUT", inp)
         if self.input is None:
             self.inputCache.append(inp)
         else:
@@ -181,10 +181,10 @@
             top = wid
             while getattr(top, 'parent', None) is not None:
                 top = top.parent
-            if top.subviews.has_key(self.theId):
+            if self.theId in top.subviews:
                 del top.subviews[self.theId]
             top.subviews[id] = wid
-            if wid.parent.subviews.has_key(self.theId):
+            if self.theId in wid.parent.subviews:
                 del wid.parent.subviews[self.theId]
             wid.parent.subviews[id] = wid
 
--- twisted/web/woven/view.py (original)
+++ twisted/web/woven/view.py (refactored)
@@ -4,16 +4,16 @@
 # See LICENSE for details.
 
 
-from __future__ import nested_scopes
+
 
 __version__ = "$Revision: 1.91 $"[11:-2]
 
 # Sibling imports
-import interfaces
-import utils
-import controller
-from utils import doSendPage
-import model
+from . import interfaces
+from . import utils
+from . import controller
+from .utils import doSendPage
+from . import model
 
 # Twisted imports
 from twisted.internet import defer
@@ -24,7 +24,7 @@
 from zope.interface import implements
 
 try:
-    import cPickle as pickle
+    import pickle as pickle
 except ImportError:
     import pickle
 
@@ -112,7 +112,7 @@
             if doneCallback is None and self.doneCallback is None:
                 self.doneCallback = doSendPage
             else:
-                print "DoneCallback", doneCallback
+                print("DoneCallback", doneCallback)
                 self.doneCallback = doneCallback
         if template is not None:
             self.template = template
@@ -164,7 +164,7 @@
             self.d = microdom.parseString(template, caseInsensitive=0, preserveCase=0)
         else:
             if not self.templateFile:
-                raise AttributeError, "%s does not define self.templateFile to operate on" % self.__class__
+                raise AttributeError("%s does not define self.templateFile to operate on" % self.__class__)
             self.d = self.lookupTemplate(request)
         request.d = self.d
         self.handleDocument(request, self.d)
@@ -193,7 +193,7 @@
         # First see if templateDirectory + templateFile is a file
         templatePath = os.path.join(self.templateDirectory, self.templateFile)
         if not os.path.exists(templatePath):
-            raise RuntimeError, "The template %r was not found." % templatePath
+            raise RuntimeError("The template %r was not found." % templatePath)
         # Check to see if there is an already parsed copy of it
         mtime = os.path.getmtime(templatePath)
         cachedTemplate = templateCache.get(templatePath, None)
@@ -270,7 +270,7 @@
             if node.parentNode is not None:
                 node.parentNode.replaceChild(result, node)
             else:
-                raise RuntimeError, "We're dying here, please report this immediately"
+                raise RuntimeError("We're dying here, please report this immediately")
         else:
             self.outstandingCallbacks += 1
             result.addCallback(self.dispatchResultCallback, request, node)
@@ -407,7 +407,7 @@
                 warnings.warn("factory_ methods are deprecated; please use "
                               "wvfactory_ instead", DeprecationWarning)
         if vm:
-            if vm.func_code.co_argcount == 3 and not type(vm) == types.LambdaType:
+            if vm.__code__.co_argcount == 3 and not type(vm) == types.LambdaType:
                  warnings.warn("wvfactory_ methods take (request, node, "
                                "model) instead of (request, node) now. \n"
                                "Please instantiate your widgets with a "
@@ -604,7 +604,7 @@
     def unlinkViews(self):
         #print "unlinking views"
         self.model.removeView(self)
-        for key, value in self.subviews.items():
+        for key, value in list(self.subviews.items()):
             value.unlinkViews()
 #            value.model.removeView(value)
 
@@ -655,7 +655,7 @@
         #print "updating flash thingie"
         uid = request.getSession().uid
         n = wid.templateNode
-        if n.attributes.has_key('src'):
+        if 'src' in n.attributes:
             n.attributes['src'] = n.attributes.get('src') + '?twisted_session=' + str(uid)
         else:
             n.attributes['value'] = n.attributes.get('value') + '?twisted_session=' + str(uid)
@@ -682,6 +682,6 @@
 # If no widget/handler was found in the container controller or view, these
 # modules will be searched.
 
-import input
-import widgets
-
+from . import input
+from . import widgets
+
--- twisted/web/woven/widgets.py (original)
+++ twisted/web/woven/widgets.py (refactored)
@@ -5,20 +5,20 @@
 
 # DOMWidgets
 
-from __future__ import nested_scopes
-
-import urllib
+
+
+import urllib.request, urllib.parse, urllib.error
 import warnings
 from twisted.web.microdom import parseString, Element, Node
 from twisted.web import domhelpers
 
 
 #sibling imports
-import model
-import template
-import view
-import utils
-import interfaces
+from . import model
+from . import template
+from . import view
+from . import utils
+from . import interfaces
 
 from twisted.python import components, failure
 from twisted.python import reflect
@@ -180,11 +180,11 @@
         Do your part, prevent infinite recursion!
         """
         if not DEBUG:
-            if node.attributes.has_key('model'):
+            if 'model' in node.attributes:
                 del node.attributes['model']
-            if node.attributes.has_key('view'):
+            if 'view' in node.attributes:
                 del node.attributes['view']
-            if node.attributes.has_key('controller'):
+            if 'controller' in node.attributes:
                 del node.attributes['controller']
         return node
 
@@ -269,7 +269,7 @@
             old = node.cloneNode(1)
             node.parentNode = parent
             gen = become.generateDOM(request, node)
-            if old.attributes.has_key('model'):
+            if 'model' in old.attributes:
                 del old.attributes['model']
             del old.attributes['controller']
             gen.appendChild(old)
@@ -312,7 +312,7 @@
             request = Dummy()
             request.d = document
         oldNode = self.node
-        if payload.has_key(self.submodel):
+        if self.submodel in payload:
             data = payload[self.submodel]
         else:
             data = self.getData(request)
@@ -371,7 +371,7 @@
     def getAllPatterns(self, name, default=missingPattern, clone=1, deep=1):
         """Get all nodes below this one which have a matching pattern attribute.
         """
-        if self.slots.has_key(name):
+        if name in self.slots:
             slots = self.slots[name]
         else:
             sm = self.submodel.split('/')[-1]
@@ -379,14 +379,14 @@
             if not slots:
 #                slots = domhelpers.locateNodes(self.templateNode, "pattern", name, noNesting=1)
                 matcher = lambda n, name=name: isinstance(n, Element) and \
-                            n.attributes.has_key("pattern") and n.attributes["pattern"] == name
-                recurseMatcher = lambda n: isinstance(n, Element) and not n.attributes.has_key("view") and not n.attributes.has_key('model')
+                            "pattern" in n.attributes and n.attributes["pattern"] == name
+                recurseMatcher = lambda n: isinstance(n, Element) and "view" not in n.attributes and 'model' not in n.attributes
                 slots = domhelpers.findNodesShallowOnMatch(self.templateNode, matcher, recurseMatcher)
                 if not slots:
                     msg = 'WARNING: No template nodes were found '\
                               '(tagged %s="%s"'\
                               ' or pattern="%s") for node %s (full submodel path %s)' % (name + "Of",
-                                            sm, name, self.templateNode, `self.submodel`)
+                                            sm, name, self.templateNode, repr(self.submodel))
                     if default is _RAISE:
                         raise Exception(msg)
                     if DEBUG:
@@ -417,9 +417,9 @@
             parentNode = slot.parentNode
             slot.parentNode = None
             clone = slot.cloneNode(deep)
-            if clone.attributes.has_key('pattern'):
+            if 'pattern' in clone.attributes:
                 del clone.attributes['pattern']
-            elif clone.attributes.has_key(name + 'Of'):
+            elif name + 'Of' in clone.attributes:
                 del clone.attributes[name + 'Of']
             slot.parentNode = parentNode
             if DEBUG:
@@ -498,7 +498,7 @@
     """
 
     def setUp(self, request, node, data):
-        for k, v in data.items():
+        for k, v in list(data.items()):
             self[k] = v
 
 
@@ -588,7 +588,7 @@
         self['name'] = submodel
 
     def setUp(self, request, node, data):
-        if not self.attributes.has_key('name') and not node.attributes.get('name'):
+        if 'name' not in self.attributes and not node.attributes.get('name'):
             if self.submodel:
                 id = self.submodel
             else:
@@ -596,7 +596,7 @@
             self['name'] = id
         if data is None:
             data = ''
-        if not self.attributes.has_key('value'):
+        if 'value' not in self.attributes:
             self['value'] = str(data)
 
 
@@ -667,7 +667,7 @@
         self.add(Text(self.text or data))
         if data is None:
             data = ''
-        if not self.attributes.has_key('value'):
+        if 'value' not in self.attributes:
             self['value'] = str(data)
 
 class Anchor(Widget):
@@ -693,7 +693,7 @@
 
     def setUp(self, request, node, data):
         href = self.baseHREF
-        params = urllib.urlencode(self.parameters)
+        params = urllib.parse.urlencode(self.parameters)
         if params:
             href = href + '?' + params
         self['href'] = href or str(data) + self.trailingSlash
@@ -817,7 +817,7 @@
         """
         """
         currentListItem = 0
-        keys = data.keys()
+        keys = list(data.keys())
         # Keys may be a tuple, if this is not a true dictionary but a dictionary-like object
         if hasattr(keys, 'sort'):
             keys.sort()
--- twisted/web2/compat.py (original)
+++ twisted/web2/compat.py (refactored)
@@ -1,9 +1,8 @@
-from __future__ import generators
-
-from urllib import quote, string
+
+from urllib.parse import quote
 
 import UserDict, math, time
-from cStringIO import StringIO
+from io import StringIO
 
 from twisted.web2 import http_headers, iweb, stream, responsecode
 from twisted.internet import defer, address
@@ -35,10 +34,10 @@
             yield k, ', '.join(v)
 
     def keys(self):
-        return [k for k, _ in self.iteritems()]
+        return [k for k, _ in self.items()]
 
     def __iter__(self):
-        for k, _ in self.iteritems():
+        for k, _ in self.items():
             yield k
 
     def has_key(self, name):
@@ -85,7 +84,7 @@
 
         def _set(self, newheaders):
             headers = http_headers.Headers()
-            for n,v in newheaders.items():
+            for n,v in list(newheaders.items()):
                 headers.setRawHeaders(n, (v,))
             newheaders = headers
             getattr(self, where).headers = newheaders
@@ -192,7 +191,7 @@
 
     def setLastModified(self, when):
         # Never returns CACHED -- can it and still be compliant?
-        when = long(math.ceil(when))
+        when = int(math.ceil(when))
         self.response.headers.setHeader('last-modified', when)
         return None
 
@@ -201,7 +200,7 @@
         return None
 
     def getAllHeaders(self):
-        return dict(self.headers.iteritems())
+        return dict(iter(self.headers.items()))
 
     def getRequestHostname(self):
         return self.request.host
@@ -411,7 +410,7 @@
         return "<%s @ 0x%x adapting %r>" % (self.__class__.__name__, id(self), self.original)
 
     def locateChild(self, req, segments):
-        import server
+        from . import server
         request = iweb.IOldRequest(req)
         if self.original.isLeaf:
             return self, server.StopTraversal
--- twisted/web2/dirlist.py (original)
+++ twisted/web2/dirlist.py (refactored)
@@ -5,7 +5,7 @@
 
 # system imports
 import os
-import urllib
+import urllib.request, urllib.parse, urllib.error
 import stat
 import time
 
@@ -45,7 +45,7 @@
         files = []
 
         for path in directory:
-            url = urllib.quote(path, '/')
+            url = urllib.parse.quote(path, '/')
             fullpath = os.path.join(self.path, path)
             try:
                 st = os.stat(fullpath)
@@ -84,7 +84,7 @@
 
 
     def render(self, request):
-        title = "Directory listing for %s" % urllib.unquote(request.path)
+        title = "Directory listing for %s" % urllib.parse.unquote(request.path)
     
         s= """<html><head><title>%s</title><style>
           th, .even td, .odd td { padding-right: 0.5em; font-family: monospace}
--- twisted/web2/fileupload.py (original)
+++ twisted/web2/fileupload.py (refactored)
@@ -1,15 +1,15 @@
-from __future__ import generators
+
 
 import re
 from zope.interface import implements
-import urllib
+import urllib.request, urllib.parse, urllib.error
 import tempfile
 
 from twisted.internet import defer
 from twisted.web2.stream import IStream, FileStream, BufferedStream, readStream
 from twisted.web2.stream import generatorToStream, readAndDiscard
 from twisted.web2 import http_headers
-from cStringIO import StringIO
+from io import StringIO
 
 ###################################
 #####  Multipart MIME Reader  #####
@@ -307,7 +307,7 @@
     while still_going:
         try:
             yield input.wait
-            data = input.next()
+            data = next(input)
         except StopIteration:
             pairs = [lastdata]
             still_going=0
@@ -324,11 +324,11 @@
             nv = name_value.split('=', 1)
             if len(nv) != 2:
                 if strict_parsing:
-                    raise MimeFormatError("bad query field: %s") % `name_value`
+                    raise MimeFormatError("bad query field: %s") % repr(name_value)
                 continue
             if len(nv[1]) or keep_blank_values:
-                name = urllib.unquote(nv[0].replace('+', ' '))
-                value = urllib.unquote(nv[1].replace('+', ' '))
+                name = urllib.parse.unquote(nv[0].replace('+', ' '))
+                value = urllib.parse.unquote(nv[1].replace('+', ' '))
                 yield name, value
 parse_urlencoded_stream = generatorToStream(parse_urlencoded_stream)
 
@@ -368,7 +368,7 @@
     from twisted.python import log
     d.addErrback(log.err)
     def pr(s):
-        print s
+        print(s)
     d.addCallback(pr)
 
 __all__ = ['parseMultipartFormData', 'parse_urlencoded', 'parse_urlencoded_stream', 'MultipartMimeStream', 'MimeFormatError']
--- twisted/web2/http.py (original)
+++ twisted/web2/http.py (refactored)
@@ -144,7 +144,7 @@
             "</html>",
         ))
 
-        if type(output) == unicode:
+        if type(output) == str:
             output = output.encode("utf-8")
             mime_params = {"charset": "utf-8"}
         else:
--- twisted/web2/http_headers.py (original)
+++ twisted/web2/http_headers.py (refactored)
@@ -29,11 +29,11 @@
 
 def casemappingify(d):
     global header_case_mapping
-    newd = dict([(key.lower(),key) for key in d.keys()])
+    newd = dict([(key.lower(),key) for key in list(d.keys())])
     header_case_mapping.update(newd)
 
 def lowerify(d):
-    return dict([(key.lower(),value) for key,value in d.items()])
+    return dict([(key.lower(),value) for key,value in list(d.items())])
 
 
 class HeaderHandler(object):
@@ -79,7 +79,7 @@
                 header = p(header)
                 # if isinstance(h, types.GeneratorType):
                 #     h=list(h)
-        except ValueError,v:
+        except ValueError as v:
             # print v
             header=None
 
@@ -207,7 +207,7 @@
     day = int(day)
     month = int(monthname_lower.index(month.lower()))
     year = int(year)
-    hour, min, sec = map(int, time.split(':'))
+    hour, min, sec = list(map(int, time.split(':')))
     return int(timegm((year, month, day, hour, min, sec)))
 
 
@@ -299,9 +299,9 @@
         cur = cur+1
 
     if qpair:
-        raise ValueError, "Missing character after '\\'"
+        raise ValueError("Missing character after '\\'")
     if quoted:
-        raise ValueError, "Missing end quote"
+        raise ValueError("Missing end quote")
 
     if start != cur:
         if foldCase:
@@ -351,7 +351,7 @@
 ##### parser utilities:
 def checkSingleToken(tokens):
     if len(tokens) != 1:
-        raise ValueError, "Expected single token, not %s." % (tokens,)
+        raise ValueError("Expected single token, not %s." % (tokens,))
     return tokens[0]
 
 def parseKeyValue(val):
@@ -359,11 +359,11 @@
         return val[0],None
     elif len(val) == 3 and val[1] == Token('='):
         return val[0],val[2]
-    raise ValueError, "Expected key or key=value, but got %s." % (val,)
+    raise ValueError("Expected key or key=value, but got %s." % (val,))
 
 def parseArgs(field):
     args=split(field, Token(';'))
-    val = args.next()
+    val = next(args)
     args = [parseKeyValue(arg) for arg in args]
     return val,args
 
@@ -477,14 +477,14 @@
         return "MimeType(%r, %r, %r)" % (self.mediaType, self.mediaSubtype, self.params)
 
     def __hash__(self):
-        return hash(self.mediaType)^hash(self.mediaSubtype)^hash(tuple(self.params.iteritems()))
+        return hash(self.mediaType)^hash(self.mediaSubtype)^hash(tuple(self.params.items()))
 
 ##### Specific header parsers.
 def parseAccept(field):
     type,args = parseArgs(field)
 
     if len(type) != 3 or type[1] != Token('/'):
-        raise ValueError, "MIME Type "+str(type)+" invalid."
+        raise ValueError("MIME Type "+str(type)+" invalid.")
 
     # okay, this spec is screwy. A 'q' parameter is used as the separator
     # between MIME parameters and (as yet undefined) additional HTTP
@@ -547,7 +547,7 @@
     type,args = parseArgs(header)
 
     if len(type) != 3 or type[1] != Token('/'):
-        raise ValueError, "MIME Type "+str(type)+" invalid."
+        raise ValueError("MIME Type "+str(type)+" invalid.")
 
     args = [(kv[0].lower(), kv[1]) for kv in args]
 
@@ -556,7 +556,7 @@
 def parseContentMD5(header):
     try:
         return base64.decodestring(header)
-    except Exception,e:
+    except Exception as e:
         raise ValueError(e)
 
 def parseContentRange(header):
@@ -572,7 +572,7 @@
     if startend.strip() == '*':
         start,end=None,None
     else:
-        start, end = map(int, startend.split("-"))
+        start, end = list(map(int, startend.split("-")))
     if realLength == "*":
         realLength = None
     else:
@@ -708,7 +708,7 @@
 
     out="%s/%s"%(mimeType.mediaType, mimeType.mediaSubtype)
     if mimeType.params:
-        out+=';'+generateKeyValues(mimeType.params.iteritems())
+        out+=';'+generateKeyValues(iter(mimeType.params.items()))
 
     if q != 1.0:
         out+=(';q=%.3f' % (q,)).rstrip('0').rstrip('.')
@@ -744,7 +744,8 @@
             v = [field.strip().lower() for field in v.split(',')]
     return k, v
 
-def generateCacheControl((k, v)):
+def generateCacheControl(xxx_todo_changeme):
+    (k, v) = xxx_todo_changeme
     if v is None:
         return str(k)
     else:
@@ -810,7 +811,7 @@
 def generateContentType(mimeType):
     out="%s/%s"%(mimeType.mediaType, mimeType.mediaSubtype)
     if mimeType.params:
-        out+=';'+generateKeyValues(mimeType.params.iteritems())
+        out+=';'+generateKeyValues(iter(mimeType.params.items()))
     return out
 
 def generateIfRange(dateOrETag):
@@ -831,7 +832,7 @@
 
         try:
             l = []
-            for k,v in dict(challenge).iteritems():
+            for k,v in dict(challenge).items():
                 l.append("%s=%s" % (k, quoteString(v)))
 
             _generated.append("%s %s" % (scheme, ", ".join(l)))
@@ -1296,10 +1297,10 @@
         self._headers = {}
         self.handler = handler
         if headers is not None:
-            for key, value in headers.iteritems():
+            for key, value in headers.items():
                 self.setHeader(key, value)
         if rawHeaders is not None:
-            for key, value in rawHeaders.iteritems():
+            for key, value in rawHeaders.items():
                 self.setRawHeaders(key, value)
 
     def _setRawHeaders(self, headers):
@@ -1323,7 +1324,7 @@
     def hasHeader(self, name):
         """Does a header with the given name exist?"""
         name=name.lower()
-        return self._raw_headers.has_key(name)
+        return name in self._raw_headers
 
     def getRawHeaders(self, name, default=None):
         """Returns a list of headers matching the given name as the raw string given."""
@@ -1389,7 +1390,7 @@
         """Removes the header named."""
 
         name=name.lower()
-        if self._raw_headers.has_key(name):
+        if name in self._raw_headers:
             del self._raw_headers[name]
             del self._headers[name]
 
@@ -1405,7 +1406,7 @@
         """Return an iterator of key,value pairs of all headers
         contained in this object, as strings. The keys are capitalized
         in canonical capitalization."""
-        for k,v in self._raw_headers.iteritems():
+        for k,v in self._raw_headers.items():
             if v is _RecalcNeeded:
                 v = self._toRaw(k)
             yield self.canonicalNameCaps(k), v
@@ -1427,7 +1428,7 @@
    is strictly an error, but we're nice.).
    """
 
-iteritems = lambda x: x.iteritems()
+iteritems = lambda x: iter(x.items())
 
 
 parser_general_headers = {
--- twisted/web2/log.py (original)
+++ twisted/web2/log.py (refactored)
@@ -104,7 +104,7 @@
 
     logFormat = '%s - %s [%s] "%s" %s %d "%s" "%s"'
     def logMessage(self, message):
-        raise NotImplemented, 'You must provide an implementation.'
+        raise NotImplemented('You must provide an implementation.')
 
     def computeTimezoneForLog(self, tz):
         if tz > 0:
--- twisted/web2/proxy.py (original)
+++ twisted/web2/proxy.py (refactored)
@@ -27,7 +27,7 @@
 from zope.interface import implements, Interface
 
 # system imports
-import urlparse
+import urllib.parse
 
 
 class ProxyClient(http.HTTPClient):
@@ -37,7 +37,7 @@
         self.father = father
         self.command = command
         self.rest = rest
-        if headers.has_key("proxy-connection"):
+        if "proxy-connection" in headers:
             del headers["proxy-connection"]
         headers["connection"] = "close"
         self.headers = headers
@@ -45,7 +45,7 @@
 
     def connectionMade(self):
         self.sendCommand(self.command, self.rest)
-        for header, value in self.headers.items():
+        for header, value in list(self.headers.items()):
             self.sendHeader(header, value)
         self.endHeaders()
         self.transport.write(self.data)
@@ -99,19 +99,19 @@
     ports = {'http': 80}
 
     def process(self):
-        parsed = urlparse.urlparse(self.uri)
+        parsed = urllib.parse.urlparse(self.uri)
         protocol = parsed[0]
         host = parsed[1]
         port = self.ports[protocol]
         if ':' in host:
             host, port = host.split(':')
             port = int(port)
-        rest = urlparse.urlunparse(('','')+parsed[2:])
+        rest = urllib.parse.urlunparse(('','')+parsed[2:])
         if not rest:
             rest = rest+'/'
         class_ = self.protocols[protocol]
         headers = self.getAllHeaders().copy()
-        if not headers.has_key('host'):
+        if 'host' not in headers:
             headers['host'] = host
         self.content.seek(0, 0)
         s = self.content.read()
@@ -199,7 +199,7 @@
     def render(self, request):
         request.received_headers['host'] = self.connector.name
         request.content.seek(0, 0)
-        qs = urlparse.urlparse(request.uri)[4]
+        qs = urllib.parse.urlparse(request.uri)[4]
         path = self.path+'/'.join(request.postpath)
         if qs:
             rest = path + '?' + qs
--- twisted/web2/server.py (original)
+++ twisted/web2/server.py (refactored)
@@ -8,9 +8,9 @@
 """
 
 # System Imports
-import cgi, time, urlparse
-from urllib import quote, unquote
-from urlparse import urlsplit
+import cgi, time, urllib.parse
+from urllib.parse import quote, unquote
+from urllib.parse import urlsplit
 
 import weakref
 
@@ -171,10 +171,10 @@
                        error.defaultErrorHandler, defaultHeadersFilter]
 
     def __init__(self, *args, **kw):
-        if kw.has_key('site'):
+        if 'site' in kw:
             self.site = kw['site']
             del kw['site']
-        if kw.has_key('prepathuri'):
+        if 'prepathuri' in kw:
             self._initialprepath = kw['prepathuri']
             del kw['prepathuri']
 
@@ -210,7 +210,7 @@
         else:
             hostport = host + ':' + str(port)
 
-        return urlparse.urlunparse((
+        return urllib.parse.urlunparse((
             scheme, hostport, path,
             params, querystring, fragment))
 
@@ -229,19 +229,19 @@
         else:
             # It is an absolute uri, use standard urlparse
             (self.scheme, self.host, self.path,
-             self.params, self.querystring, fragment) = urlparse.urlparse(self.uri)
+             self.params, self.querystring, fragment) = urllib.parse.urlparse(self.uri)
 
         if self.querystring:
             self.args = cgi.parse_qs(self.querystring, True)
         else:
             self.args = {}
 
-        path = map(unquote, self.path[1:].split('/'))
+        path = list(map(unquote, self.path[1:].split('/')))
         if self._initialprepath:
             # We were given an initial prepath -- this is for supporting
             # CGI-ish applications where part of the path has already
             # been processed
-            prepath = map(unquote, self._initialprepath[1:].split('/'))
+            prepath = list(map(unquote, self._initialprepath[1:].split('/')))
 
             if path[:len(prepath)] == prepath:
                 self.prepath = prepath
@@ -361,7 +361,7 @@
 
         if updatepaths:
             # We found a Resource... update the request.prepath and postpath
-            for x in xrange(len(path) - len(newpath)):
+            for x in range(len(path) - len(newpath)):
                 self.prepath.append(self.postpath.pop(0))
 
         child = self._getChild(None, newres, newpath, updatepaths=updatepaths)
@@ -437,7 +437,7 @@
 
         segments = path.split("/")
         assert segments[0] == "", "URL path didn't begin with '/': %s" % (path,)
-        segments = map(unquote, segments[1:])
+        segments = list(map(unquote, segments[1:]))
 
         def notFound(f):
             f.trap(http.HTTPError)
--- twisted/web2/static.py (original)
+++ twisted/web2/static.py (refactored)
@@ -204,7 +204,7 @@
         if processors is not None:
             self.processors = dict([
                 (key.lower(), value)
-                for key, value in processors.items()
+                for key, value in list(processors.items())
                 ])
 
         if indexNames is not None:
@@ -323,7 +323,7 @@
         """
         @return: a sequence of the names of all known children of this resource.
         """
-        children = self.putChildren.keys()
+        children = list(self.putChildren.keys())
         if self.fp.isdir():
             children += [c for c in self.fp.listdir() if c not in children]
         return children
@@ -398,7 +398,7 @@
 
         try:
             f = self.fp.open()
-        except IOError, e:
+        except IOError as e:
             import errno
             if e[0] == errno.EACCES:
                 return responsecode.FORBIDDEN
@@ -429,7 +429,7 @@
                     http_headers.MimeType('text', 'html'),
                     http_headers.MimeType('text', 'css'))
 
-    def __init__(self, destination, expectedFields=[], allowedTypes=None, maxBytes=1000000, permissions=0644):
+    def __init__(self, destination, expectedFields=[], allowedTypes=None, maxBytes=1000000, permissions=0o644):
         self.destination = destination
         self.allowedTypes = allowedTypes or self.allowedTypes
         self.maxBytes = maxBytes
@@ -489,7 +489,7 @@
                         try:
                             outname = self.writeFile(*finfo)
                             content.append("Saved file %s<br />" % outname)
-                        except IOError, err:
+                        except IOError as err:
                             content.append(str(err) + "<br />")
                 else:
                     content.append("%s is not a valid field" % fieldName)
@@ -575,7 +575,7 @@
 def getTypeAndEncoding(filename, types, encodings, defaultType):
     p, ext = os.path.splitext(filename)
     ext = ext.lower()
-    if encodings.has_key(ext):
+    if ext in encodings:
         enc = encodings[ext]
         ext = os.path.splitext(p)[1].lower()
     else:
--- twisted/web2/stream.py (original)
+++ twisted/web2/stream.py (refactored)
@@ -30,7 +30,7 @@
 consumer which is a stream, so that other producers can write to it.
 """
 
-from __future__ import generators
+
 
 import copy, os, types, sys
 from zope.interface import Interface, Attribute, implements
@@ -270,7 +270,7 @@
         SimpleStream.close(self)
 
 components.registerAdapter(MemoryStream, str, IByteStream)
-components.registerAdapter(MemoryStream, types.BufferType, IByteStream)
+components.registerAdapter(MemoryStream, memoryview, IByteStream)
 
 ##############################
 ####    CompoundStream    ####
@@ -865,7 +865,7 @@
 
     def __iter__(self):
         return self
-    def next(self):
+    def __next__(self):
         if self.done:
             raise StopIteration
         return self.value
@@ -881,7 +881,7 @@
         
     def read(self):
         try:
-            val = self._gen.next()
+            val = next(self._gen)
         except StopIteration:
             return None
         else:
--- twisted/web2/twcgi.py (original)
+++ twisted/web2/twcgi.py (refactored)
@@ -16,7 +16,7 @@
 # System Imports
 import os
 import sys
-import urllib
+import urllib.request, urllib.parse, urllib.error
 
 # Twisted Imports
 from twisted.internet import defer, protocol, reactor
@@ -30,7 +30,7 @@
 from twisted.web2 import stream
 
 
-headerNameTranslation = ''.join([c.isalnum() and c.upper() or '_' for c in map(chr, range(256))])
+headerNameTranslation = ''.join([c.isalnum() and c.upper() or '_' for c in map(chr, list(range(256)))])
 
 def createCGIEnvironment(request):
     # See http://hoohoo.ncsa.uiuc.edu/cgi/env.html for CGI interface spec
@@ -97,11 +97,11 @@
             envname = "HTTP_" + envname
         env[envname] = ','.join(header)
 
-    for k,v in env.items():
+    for k,v in list(env.items()):
         if type(k) is not str:
-            print "is not string:",k
+            print("is not string:",k)
         if type(v) is not str:
-            print k, "is not string:",v
+            print(k, "is not string:",v)
     return env
 
 def runCGI(request, filename, filterscript=None):
@@ -113,7 +113,7 @@
     if '=' in request.querystring:
         qargs = []
     else:
-        qargs = [urllib.unquote(x) for x in request.querystring.split('+')]
+        qargs = [urllib.parse.unquote(x) for x in request.querystring.split('+')]
 
     if filterscript is None:
         filterscript = filename
--- twisted/web2/twscgi.py (original)
+++ twisted/web2/twscgi.py (refactored)
@@ -61,7 +61,7 @@
         scgiHeaders = []
         scgiHeaders.append('%s\x00%s\x00'%('CONTENT_LENGTH', str(contentLength)))
         scgiHeaders.append('SCGI\x001\x00')
-        for name, value in env.iteritems():
+        for name, value in env.items():
             if name in ('CONTENT_LENGTH', 'SCGI'):
                 continue
             scgiHeaders.append('%s\x00%s\x00'%(name,value))
--- twisted/web2/vhost.py (original)
+++ twisted/web2/vhost.py (refactored)
@@ -6,9 +6,9 @@
 """
 
 # System Imports
-import urlparse
+import urllib.parse
 from zope.interface import implements
-import urllib 
+import urllib.request, urllib.parse, urllib.error 
 import warnings
 
 from twisted.internet import address
@@ -78,7 +78,7 @@
         host = req.host.lower()
         
         if self.supportNested:
-            while not self.hosts.has_key(host) and len(host.split('.')) > 1:
+            while host not in self.hosts and len(host.split('.')) > 1:
                 host = '.'.join(host.split('.')[1:])
 
         # Default being None is okay, it'll turn into a 404
@@ -169,7 +169,7 @@
         req.remoteAddr = address.IPv4Address('TCP', remote_ip, 0)
             
         req.prepath = app_location[1:].split('/')[:-1]
-        req.path = '/'+('/'.join([urllib.quote(s, '') for s in (req.prepath + segments)]))
+        req.path = '/'+('/'.join([urllib.parse.quote(s, '') for s in (req.prepath + segments)]))
         
         return self.resource, segments
         
@@ -214,10 +214,10 @@
         self.resource = resource
         
         (self.scheme, self.host, self.path,
-         params, querystring, fragment) = urlparse.urlparse(uri)
+         params, querystring, fragment) = urllib.parse.urlparse(uri)
         if params or querystring or fragment:
             raise ValueError("Must not specify params, query args, or fragment to VHostURIRewrite")
-        self.path = map(urllib.unquote, self.path[1:].split('/'))[:-1]
+        self.path = map(urllib.parse.unquote, self.path[1:].split('/'))[:-1]
         self.host, self.port = http.splitHostPort(self.scheme, self.host)
         
     def renderHTTP(self, req):
@@ -228,7 +228,7 @@
         req.host = self.host
         req.port = self.port
         req.prepath=self.path[:]
-        req.path = '/'+('/'.join([urllib.quote(s, '') for s in (req.prepath + segments)]))
+        req.path = '/'+('/'.join([urllib.parse.quote(s, '') for s in (req.prepath + segments)]))
         # print req.prepath, segments, req.postpath, req.path
         
         return self.resource, segments
--- twisted/web2/wsgi.py (original)
+++ twisted/web2/wsgi.py (refactored)
@@ -172,11 +172,11 @@
         if exc_info is not None:
             try:
                 if self.headersSent:
-                    raise exc_info[0], exc_info[1], exc_info[2]
+                    raise exc_info[0](exc_info[1]).with_traceback(exc_info[2])
             finally:
                 exc_info = None
         elif self.response is not None:
-            raise AlreadyStartedResponse, 'startWSGIResponse(%r)' % status
+            raise AlreadyStartedResponse('startWSGIResponse(%r)' % status)
         status = int(status.split(' ')[0])
         self.response = http.Response(status)
         for key, value in response_headers:
@@ -325,7 +325,7 @@
     def __iter__(self):
         return self
 
-    def next(self):
+    def __next__(self):
         data = self.filelike.read(self.blksize)
         if data:
             return data
--- twisted/web2/xmlrpc.py (original)
+++ twisted/web2/xmlrpc.py (refactored)
@@ -11,7 +11,7 @@
 """
 
 # System Imports
-import xmlrpclib
+from . import xmlrpc.client
 
 # Sibling Imports
 from twisted.web2 import resource, stream
@@ -20,10 +20,10 @@
 from twisted.python import log, reflect
 
 # Useful so people don't need to import xmlrpclib directly
-Fault = xmlrpclib.Fault
-Binary = xmlrpclib.Binary
-Boolean = xmlrpclib.Boolean
-DateTime = xmlrpclib.DateTime
+Fault = xmlrpc.client.Fault
+Binary = xmlrpc.client.Binary
+Boolean = xmlrpc.client.Boolean
+DateTime = xmlrpc.client.DateTime
 
 
 class NoSuchFunction(Fault):
@@ -64,7 +64,7 @@
         return self.subHandlers.get(prefix, None)
 
     def getSubHandlerPrefixes(self):
-        return self.subHandlers.keys()
+        return list(self.subHandlers.keys())
 
     def render(self, request):
         # For GET/HEAD: Return an error message
@@ -76,7 +76,7 @@
             s)
     
     def http_POST(self, request):
-        parser, unmarshaller = xmlrpclib.getparser()
+        parser, unmarshaller = xmlrpc.client.getparser()
         deferred = stream.readStream(request.stream, parser.feed)
         deferred.addCallback(lambda x: self._cbDispatch(
             request, parser, unmarshaller))
@@ -95,10 +95,10 @@
         if not isinstance(result, Fault):
             result = (result,)
         try:
-            s = xmlrpclib.dumps(result, methodresponse=1)
+            s = xmlrpc.client.dumps(result, methodresponse=1)
         except:
             f = Fault(self.FAILURE, "can't serialize output")
-            s = xmlrpclib.dumps(f, methodresponse=1)
+            s = xmlrpc.client.dumps(f, methodresponse=1)
         return http.Response(responsecode.OK,
             {'content-type': http_headers.MimeType('text', 'xml')},
             s)
@@ -131,7 +131,7 @@
         f = getattr(self, "xmlrpc_%s" % functionPath, None)
         if not f:
             raise NoSuchFunction(self.NOT_FOUND, "function %s not found" % functionPath)
-        elif not callable(f):
+        elif not hasattr(f, '__call__'):
             raise NoSuchFunction(self.NOT_FOUND, "function %s not callable" % functionPath)
         else:
             return f
--- twisted/web2/auth/digest.py (original)
+++ twisted/web2/auth/digest.py (refactored)
@@ -204,12 +204,12 @@
         self.algorithm = algorithm
         self.realm = realm
 
-        c = tuple([random.randrange(sys.maxint) for _ in range(3)])
+        c = tuple([random.randrange(sys.maxsize) for _ in range(3)])
 
         self.privateKey = '%d%d%d' % c
 
     def generateNonce(self):
-        c = tuple([random.randrange(sys.maxint) for _ in range(3)])
+        c = tuple([random.randrange(sys.maxsize) for _ in range(3)])
         c = '%d%d%d' % c
         return c
 
--- twisted/web2/auth/wrapper.py (original)
+++ twisted/web2/auth/wrapper.py (refactored)
@@ -28,7 +28,7 @@
             "You are not authorized to access this resource.")
 
         authHeaders = []
-        for factory in factories.itervalues():
+        for factory in factories.values():
             authHeaders.append((factory.scheme,
                                 factory.getChallenge(remoteAddr)))
 
--- twisted/web2/channel/cgi.py (original)
+++ twisted/web2/channel/cgi.py (refactored)
@@ -1,6 +1,6 @@
 import warnings
 import os
-import urllib
+import urllib.request, urllib.parse, urllib.error
 from zope.interface import implements
 
 from twisted.internet import protocol, address
@@ -32,10 +32,10 @@
         if not uri:
             qstr = vars.get('QUERY_STRING', '')
             if qstr:
-                qstr = "?"+urllib.quote(qstr, safe="")
-            uri = urllib.quote(vars['SCRIPT_NAME'])+urllib.quote(vars.get('PATH_INFO',  ''))+qstr
+                qstr = "?"+urllib.parse.quote(qstr, safe="")
+            uri = urllib.parse.quote(vars['SCRIPT_NAME'])+urllib.parse.quote(vars.get('PATH_INFO',  ''))+qstr
             
-        for name,val in vars.iteritems():
+        for name,val in vars.items():
             if name.startswith('HTTP_'):
                 name = name[5:].replace('_', '-')
             elif name == 'CONTENT_TYPE':
--- twisted/web2/channel/http.py (original)
+++ twisted/web2/channel/http.py (refactored)
@@ -1,6 +1,6 @@
 import warnings
 import socket
-from cStringIO import StringIO
+from io import StringIO
 from zope.interface import implements
 
 from twisted.python import log
@@ -553,7 +553,7 @@
         This method is not intended for users.
         """
         if not self.queued:
-            raise RuntimeError, "noLongerQueued() got called unnecessarily."
+            raise RuntimeError("noLongerQueued() got called unnecessarily.")
 
         self.queued = 0
 
@@ -578,7 +578,7 @@
         """
         
         if self.producer:
-            raise ValueError, "registering producer %s before previous one (%s) was unregistered" % (producer, self.producer)
+            raise ValueError("registering producer %s before previous one (%s) was unregistered" % (producer, self.producer))
         
         self.producer = producer
         
@@ -889,7 +889,7 @@
         
         p = protocol.ServerFactory.buildProtocol(self, addr)
         
-        for arg,value in self.protocolArgs.iteritems():
+        for arg,value in self.protocolArgs.items():
             setattr(p, arg, value)
         return p
 
--- twisted/web2/filter/gzip.py (original)
+++ twisted/web2/filter/gzip.py (refactored)
@@ -1,4 +1,4 @@
-from __future__ import generators
+
 import struct
 import zlib
 from twisted.web2 import stream
@@ -29,7 +29,7 @@
         yield input.wait
     
     yield compress.flush()
-    yield struct.pack('<LL', crc & 0xFFFFFFFFL, size & 0xFFFFFFFFL)
+    yield struct.pack('<LL', crc & 0xFFFFFFFF, size & 0xFFFFFFFF)
 gzipStream=stream.generatorToStream(gzipStream)
 
 def deflateStream(input, compressLevel=6):
--- twisted/web2/filter/location.py (original)
+++ twisted/web2/filter/location.py (refactored)
@@ -1,5 +1,5 @@
 from twisted.web2 import responsecode
-import urlparse
+import urllib.parse
 
 __all__ = ['addLocation']
 
@@ -16,7 +16,7 @@
             # Check to see whether we have an absolute URI or not.
             # If not, have the request turn it into an absolute URI.
             #
-            (scheme, host, path, params, querystring, fragment) = urlparse.urlparse(location)
+            (scheme, host, path, params, querystring, fragment) = urllib.parse.urlparse(location)
 
             if scheme == "":
                 uri = request.unparseURL(path=location)
--- twisted/web2/filter/range.py (original)
+++ twisted/web2/filter/range.py (refactored)
@@ -9,14 +9,13 @@
 class UnsatisfiableRangeRequest(Exception):
     pass
 
-def canonicalizeRange((start, end), size):
+def canonicalizeRange(xxx_todo_changeme, size):
     """Return canonicalized (start, end) or raises UnsatisfiableRangeRequest
     exception.
 
     NOTE: end is the last byte *inclusive*, which is not the usual convention
     in python! Be very careful! A range of 0,1 should return 2 bytes."""
-    
-    # handle "-500" ranges
+    (start, end) = xxx_todo_changeme
     if start is None:
         start = max(0, size-end)
         end = None
--- twisted/web2/test/simple_client.py (original)
+++ twisted/web2/test/simple_client.py (refactored)
@@ -16,13 +16,13 @@
     send=s.send
     recv=s.recv
     
-print >> sys.stderr, ">> Making %s request to port %d" % (socket_type, port)
+print(">> Making %s request to port %d" % (socket_type, port), file=sys.stderr)
 
 send("GET /error HTTP/1.0\r\n")
 send("Host: localhost\r\n")
 
 if test_type == "lingeringClose":
-    print >> sys.stderr, ">> Sending lots of data"
+    print(">> Sending lots of data", file=sys.stderr)
     send("Content-Length: 1000000\r\n\r\n")
     send("X"*1000000)
 else:
@@ -30,7 +30,7 @@
 
 #import time
 #time.sleep(5)
-print >> sys.stderr, ">> Getting data"
+print(">> Getting data", file=sys.stderr)
 data=''
 while len(data) < 299999:
     try:
--- twisted/web2/test/test_cgi.py (original)
+++ twisted/web2/test/test_cgi.py (refactored)
@@ -246,7 +246,7 @@
         cgiFile.write("#!%s\n\n%s" % (sys.executable,
                                       DUMMY_CGI))
         cgiFile.close()
-        os.chmod(filename, 0700)
+        os.chmod(filename, 0o700)
 
     def test_scriptsExecute(self):
         """
--- twisted/web2/test/test_client.py (original)
+++ twisted/web2/test/test_client.py (refactored)
@@ -393,7 +393,7 @@
         req = http.ClientRequest('GET', '/', None, None)
 
         def gotResp(r):
-            print r
+            print(r)
 
         d = cxn.client.submitRequest(req).addCallback(gotResp)
 
--- twisted/web2/test/test_fileupload.py (original)
+++ twisted/web2/test/test_fileupload.py (refactored)
@@ -77,7 +77,7 @@
 
             # Read file data back into memory to compare.
             out = {}
-            for name, l in files.items():
+            for name, l in list(files.items()):
                 out[name] = [(filename, ctype, f.read()) for (filename, ctype, f) in l]
             self.assertEquals(out, expected_files)
 
--- twisted/web2/test/test_http.py (original)
+++ twisted/web2/test/test_http.py (refactored)
@@ -1,5 +1,5 @@
 
-from __future__ import nested_scopes
+
 
 import time, sys
 
@@ -23,7 +23,7 @@
 
         try:
             http.checkPreconditions(request, response, **kw)
-        except http.HTTPError, e:
+        except http.HTTPError as e:
             preconditionsPass = False
             self.assertEquals(e.response.code, expectedCode)
         self.assertEquals(preconditionsPass, expectedResult)
--- twisted/web2/test/test_httpauth.py (original)
+++ twisted/web2/test/test_httpauth.py (refactored)
@@ -149,8 +149,8 @@
         self.assertEquals(challenge['qop'], 'auth')
         self.assertEquals(challenge['realm'], 'test realm')
         self.assertEquals(challenge['algorithm'], 'md5')
-        self.assertTrue(challenge.has_key("nonce"))
-        self.assertTrue(challenge.has_key("opaque"))
+        self.assertTrue("nonce" in challenge)
+        self.assertTrue("opaque" in challenge)
 
     def test_response(self):
         """
--- twisted/web2/test/test_scgi.py (original)
+++ twisted/web2/test/test_scgi.py (refactored)
@@ -15,7 +15,7 @@
 from twisted.web2 import twscgi
 
 def parseSCGIHeaders(headers):
-    return zip(*[iter(headers.split(':', 1)[1].split('\x00'))]*2)
+    return list(zip(*[iter(headers.split(':', 1)[1].split('\x00'))]*2))
 
 class SCGITests(HTTPTests):
     def connect(self, logFile=None):
--- twisted/web2/test/test_server.py (original)
+++ twisted/web2/test/test_server.py (refactored)
@@ -307,12 +307,13 @@
 
         return d
 
-    def _cbGotResponse(self, (code, headers, data, failed), expected_response, expectedfailure=False):
+    def _cbGotResponse(self, xxx_todo_changeme, expected_response, expectedfailure=False):
+        (code, headers, data, failed) = xxx_todo_changeme
         expected_code, expected_headers, expected_data = expected_response
         self.assertEquals(code, expected_code)
         if expected_data is not None:
             self.assertEquals(data, expected_data)
-        for key, value in expected_headers.iteritems():
+        for key, value in expected_headers.items():
             self.assertEquals(headers.getHeader(key), value)
         self.assertEquals(failed, expectedfailure)
 
@@ -707,10 +708,10 @@
                 http_headers.Headers({'content-type': ctype}), content)
         def cb(ign):
             self.assertEquals(request.args, {})
-            self.assertEquals(request.files.keys(), ['FileNameOne'])
-            self.assertEquals(request.files.values()[0][0][:2],
+            self.assertEquals(list(request.files.keys()), ['FileNameOne'])
+            self.assertEquals(list(request.files.values())[0][0][:2],
                   ('myfilename', http_headers.MimeType('text', 'html', {})))
-            f = request.files.values()[0][0][2]
+            f = list(request.files.values())[0][0][2]
             self.assertEquals(f.read(), "my great content wooo")
         return server.parsePOSTData(request).addCallback(cb)
 
--- twisted/web2/test/test_static.py (original)
+++ twisted/web2/test/test_static.py (refactored)
@@ -90,16 +90,17 @@
 -----weeboundary--\r
 """ % (fieldname, filename, mimetype, content))
 
-    def _CbAssertInResponse(self, (code, headers, data, failed),
+    def _CbAssertInResponse(self, xxx_todo_changeme,
                             expected_response, expectedFailure=False):
 
+        (code, headers, data, failed) = xxx_todo_changeme
         expected_code, expected_headers, expected_data = expected_response
         self.assertEquals(code, expected_code)
 
         if expected_data is not None:
             self.failUnlessSubstring(expected_data, data)
 
-        for key, value in expected_headers.iteritems():
+        for key, value in expected_headers.items():
             self.assertEquals(headers.getHeader(key), value)
 
         self.assertEquals(failed, expectedFailure)
--- twisted/web2/test/test_vhost.py (original)
+++ twisted/web2/test/test_vhost.py (refactored)
@@ -122,7 +122,7 @@
 
 def raw(d):
     headers=http_headers.Headers()
-    for k,v in d.iteritems():
+    for k,v in d.items():
         headers.setRawHeaders(k, [v])
     return headers
 
--- twisted/web2/test/test_wsgi.py (original)
+++ twisted/web2/test/test_wsgi.py (refactored)
@@ -278,9 +278,9 @@
         Check the value of the rendering envirnment against
         the string returned by the testing WSGIApp.
         """
-        keys = env.keys()
+        keys = list(env.keys())
         keys.sort()
-        envstring = ''.join(['%s=%r;' % (k, v) for k, v in env.items()])
+        envstring = ''.join(['%s=%r;' % (k, v) for k, v in list(env.items())])
         return self.assertResponse(
             (WSGI(self.envApp(*keys)), uri, None, None, version, prepath),
             (200, {}, envstring))
--- twisted/web2/test/test_xmlrpc.py (original)
+++ twisted/web2/test/test_xmlrpc.py (refactored)
@@ -7,7 +7,7 @@
 
 """Test XML-RPC support."""
 
-import xmlrpclib
+import xmlrpc.client
 
 from twisted.web2 import xmlrpc
 from twisted.web2.xmlrpc import XMLRPC, addIntrospection
@@ -145,8 +145,8 @@
             ("complex", (), {"a": ["b", "c", 12, []], "D": "foo"})]
         dl = []
         for meth, args, outp in inputOutput:
-            postdata = xmlrpclib.dumps(args, meth)
-            respdata = xmlrpclib.dumps((outp,))
+            postdata = xmlrpc.client.dumps(args, meth)
+            respdata = xmlrpc.client.dumps((outp,))
             reqdata = (self.root, 'http://host/', {}, None, None, '', postdata)
             d = self.assertResponse(reqdata, (200, {}, self.xml % respdata))
             dl.append(d)
@@ -163,8 +163,8 @@
             (17, "deferFault", 'hi'),
             (42, "SESSION_TEST", 'Session non-existant/expired.')]
         for code, meth, fault in codeMethod:
-            postdata = xmlrpclib.dumps((), meth)
-            respdata = xmlrpclib.dumps(xmlrpc.Fault(code, fault))
+            postdata = xmlrpc.client.dumps((), meth)
+            respdata = xmlrpc.client.dumps(xmlrpc.Fault(code, fault))
             reqdata = (self.root, 'http://host/', {}, None, None, '', postdata)
             d = self.assertResponse(reqdata, (200, {}, respdata))
             dl.append(d)
@@ -180,8 +180,8 @@
             (666, "fail"),
             (666, "deferFail")]
         for code, meth in codeMethod:
-            postdata = xmlrpclib.dumps((), meth)
-            respdata = xmlrpclib.dumps(xmlrpc.Fault(code, 'error'))
+            postdata = xmlrpc.client.dumps((), meth)
+            respdata = xmlrpc.client.dumps(xmlrpc.Fault(code, 'error'))
             reqdata = (self.root, 'http://host/', {}, None, None, '', postdata)
             d = self.assertResponse(reqdata, (200, {}, respdata))
             d.addCallback(self.flushLoggedErrors, TestRuntimeError, TestValueError)
@@ -212,8 +212,8 @@
             self.failUnlessEqual(
                 meths,
                 )
-        postdata = xmlrpclib.dumps((), 'system.listMethods')
-        respdata = xmlrpclib.dumps((self.methodList,))
+        postdata = xmlrpc.client.dumps((), 'system.listMethods')
+        respdata = xmlrpc.client.dumps((self.methodList,))
         reqdata = (self.root, 'http://host/', {}, None, None, '', postdata)
         return self.assertResponse(reqdata, (200, {}, self.xml % respdata))
 
@@ -228,8 +228,8 @@
 
         dl = []
         for meth, outp in inputOutput:
-            postdata = xmlrpclib.dumps((meth,), 'system.methodHelp')
-            respdata = xmlrpclib.dumps((outp,))
+            postdata = xmlrpc.client.dumps((meth,), 'system.methodHelp')
+            respdata = xmlrpc.client.dumps((outp,))
             reqdata = (self.root, 'http://host/', {}, None, None, '', postdata)
             d = self.assertResponse(reqdata, (200, {}, self.xml % respdata))
             dl.append(d)
@@ -248,8 +248,8 @@
 
         dl = []
         for meth, outp in inputOutput:
-            postdata = xmlrpclib.dumps((meth,), 'system.methodSignature')
-            respdata = xmlrpclib.dumps((outp,))
+            postdata = xmlrpc.client.dumps((meth,), 'system.methodSignature')
+            respdata = xmlrpc.client.dumps((outp,))
             reqdata = (self.root, 'http://host/', {}, None, None, '', postdata)
             d = self.assertResponse(reqdata, (200, {}, self.xml % respdata))
             dl.append(d)
--- twisted/words/service.py (original)
+++ twisted/words/service.py (refactored)
@@ -70,7 +70,7 @@
         if user.name not in self.users:
             additions = []
             self.users[user.name] = user
-            for p in self.users.itervalues():
+            for p in self.users.values():
                 if p is not user:
                     d = defer.maybeDeferred(p.userJoined, self, user)
                     d.addErrback(self._ebUserCall, p=p)
@@ -80,14 +80,14 @@
 
 
     def remove(self, user, reason=None):
-        assert reason is None or isinstance(reason, unicode)
+        assert reason is None or isinstance(reason, str)
         try:
             del self.users[user.name]
         except KeyError:
             pass
         else:
             removals = []
-            for p in self.users.itervalues():
+            for p in self.users.values():
                 if p is not user:
                     d = defer.maybeDeferred(p.userLeft, self, user, reason)
                     d.addErrback(self._ebUserCall, p=p)
@@ -103,7 +103,7 @@
     def receive(self, sender, recipient, message):
         assert recipient is self
         receives = []
-        for p in self.users.itervalues():
+        for p in self.users.values():
             if p is not sender:
                 d = defer.maybeDeferred(p.receive, sender, self, message)
                 d.addErrback(self._ebUserCall, p=p)
@@ -115,7 +115,7 @@
     def setMetadata(self, meta):
         self.meta = meta
         sets = []
-        for p in self.users.itervalues():
+        for p in self.users.values():
             d = defer.maybeDeferred(p.groupMetaUpdate, self, meta)
             d.addErrback(self._ebUserCall, p=p)
             sets.append(d)
@@ -125,7 +125,7 @@
 
     def iterusers(self):
         # XXX Deferred?
-        return iter(self.users.values())
+        return iter(list(self.users.values()))
 
 
 class User(object):
@@ -206,9 +206,9 @@
 
     # Make sendMessage a bit more useful to us
     def sendMessage(self, command, *parameter_list, **kw):
-        if not kw.has_key('prefix'):
+        if 'prefix' not in kw:
             kw['prefix'] = self.hostname
-        if not kw.has_key('to'):
+        if 'to' not in kw:
             kw['to'] = self.name.encode(self.encoding)
 
         arglist = [self, command, kw['to']] + list(parameter_list)
@@ -223,11 +223,11 @@
 
 
     def userLeft(self, group, user, reason=None):
-        assert reason is None or isinstance(reason, unicode)
+        assert reason is None or isinstance(reason, str)
         self.part(
             "%s!%s@%s" % (user.name, user.name, self.hostname),
             '#' + group.name,
-            (reason or u"leaving").encode(self.encoding, 'replace'))
+            (reason or "leaving").encode(self.encoding, 'replace'))
 
 
     def receive(self, sender, recipient, message):
@@ -363,7 +363,8 @@
         ]
 
 
-    def _cbLogin(self, (iface, avatar, logout)):
+    def _cbLogin(self, xxx_todo_changeme):
+        (iface, avatar, logout) = xxx_todo_changeme
         assert iface is iwords.IUser, "Realm is buggy, got %r" % (iface,)
 
         # Let them send messages to the world
@@ -914,7 +915,7 @@
             PBUser(self.realm, self.avatar, user))
 
     def userLeft(self, group, user, reason=None):
-        assert reason is None or isinstance(reason, unicode)
+        assert reason is None or isinstance(reason, str)
         return self.callRemote(
             'userLeft',
             PBGroup(self.realm, self.avatar, group),
@@ -983,7 +984,7 @@
 
 
     def remote_join(self, groupName):
-        assert isinstance(groupName, unicode)
+        assert isinstance(groupName, str)
         def cbGroup(group):
             def cbJoin(ignored):
                 return PBGroup(self.avatar.realm, self.avatar, group)
@@ -1097,7 +1098,7 @@
 
 
     def getGroup(self, name):
-        assert isinstance(name, unicode)
+        assert isinstance(name, str)
         if self.createGroupOnRequest:
             def ebGroup(err):
                 err.trap(ewords.DuplicateGroup)
@@ -1107,7 +1108,7 @@
 
 
     def getUser(self, name):
-        assert isinstance(name, unicode)
+        assert isinstance(name, str)
         if self.createUserOnRequest:
             def ebUser(err):
                 err.trap(ewords.DuplicateUser)
@@ -1117,7 +1118,7 @@
 
 
     def createUser(self, name):
-        assert isinstance(name, unicode)
+        assert isinstance(name, str)
         def cbLookup(user):
             return failure.Failure(ewords.DuplicateUser(name))
         def ebLookup(err):
@@ -1132,7 +1133,7 @@
 
 
     def createGroup(self, name):
-        assert isinstance(name, unicode)
+        assert isinstance(name, str)
         def cbLookup(group):
             return failure.Failure(ewords.DuplicateGroup(name))
         def ebLookup(err):
@@ -1154,7 +1155,7 @@
 
 
     def itergroups(self):
-        return defer.succeed(self.groups.itervalues())
+        return defer.succeed(iter(self.groups.values()))
 
 
     def addUser(self, user):
@@ -1172,7 +1173,7 @@
 
 
     def lookupUser(self, name):
-        assert isinstance(name, unicode)
+        assert isinstance(name, str)
         name = name.lower()
         try:
             user = self.users[name]
@@ -1183,7 +1184,7 @@
 
 
     def lookupGroup(self, name):
-        assert isinstance(name, unicode)
+        assert isinstance(name, str)
         name = name.lower()
         try:
             group = self.groups[name]
--- twisted/words/im/baseaccount.py (original)
+++ twisted/words/im/baseaccount.py (refactored)
@@ -26,7 +26,7 @@
             boolean:autoLogin, string:gatewayType)
         """
         data = []
-        for account in self.accounts.values():
+        for account in list(self.accounts.values()):
             data.append((account.accountName, account.isOnline(),
                          account.autoLogin, account.gatewayType))
         return data
@@ -36,7 +36,7 @@
 
     def getConnectionInfo(self):
         connectioninfo = []
-        for account in self.accounts.values():
+        for account in list(self.accounts.values()):
             connectioninfo.append(account.isOnline())
         return connectioninfo
 
--- twisted/words/im/basechat.py (original)
+++ twisted/words/im/basechat.py (refactored)
@@ -24,12 +24,12 @@
 
         @type person: L{Person<interfaces.IPerson>}
         """
-        if not self.contacts.has_key(person.name):
+        if person.name not in self.contacts:
             self.contacts[person.name] = person
-        if not self.onlineContacts.has_key(person.name) and \
+        if person.name not in self.onlineContacts and \
             (person.status == ONLINE or person.status == AWAY):
             self.onlineContacts[person.name] = person
-        if self.onlineContacts.has_key(person.name) and \
+        if person.name in self.onlineContacts and \
            person.status == OFFLINE:
             del self.onlineContacts[person.name]
 
@@ -52,11 +52,11 @@
 
     def contactChangedNick(self, person, newnick):
         oldname = person.name
-        if self.contacts.has_key(oldname):
+        if oldname in self.contacts:
             del self.contacts[oldname]
             person.name = newnick
             self.contacts[newnick] = person
-            if self.onlineContacts.has_key(oldname):
+            if oldname in self.onlineContacts:
                 del self.onlineContacts[oldname]
                 self.onlineContacts[newnick] = person
 
@@ -199,7 +199,7 @@
         @type client: L{Client<interfaces.IClient>}
         @returns: client, so that I may be used in a callback chain
         """
-        print "signing onto", client.accountName
+        print("signing onto", client.accountName)
         self.onlineClients.append(client)
         self.contactsList.registerAccountClient(client)
         return client
@@ -209,7 +209,7 @@
 
         @type client: L{Client<interfaces.IClient>}
         """
-        print "signing off from", client.accountName
+        print("signing off from", client.accountName)
         self.onlineClients.remove(client)
         self.contactsList.unregisterAccountClient(client)
 
@@ -304,7 +304,7 @@
         @type oldnick: string
         @type newnick: string
         """
-        if self.persons.has_key((person.name, person.account)):
+        if (person.name, person.account) in self.persons:
             conv = self.conversations.get(person)
             if conv:
                 conv.contactChangedNick(person, newnick)
--- twisted/words/im/gtkaccount.py (original)
+++ twisted/words/im/gtkaccount.py (refactored)
@@ -3,7 +3,7 @@
 
 
 try:
-    import cPickle as pickle
+    import pickle as pickle
 except ImportError:
     import pickle
 
@@ -23,18 +23,18 @@
         self.xml = openGlade(GLADE_FILE, root="MainIMWindow")
         self.chatui = gtkchat.GtkChatClientUI(self.xml)
         self.chatui._accountmanager = self # TODO: clean this up... it's used in gtkchat
-        print self.xml._o
+        print(self.xml._o)
         autoConnectMethods(self, self.chatui.theContactsList)
         self.widget = self.xml.get_widget("AccountManWidget")
         self.widget.show_all()
         try:
             f = open(SETTINGS_FILE)
             self.accounts = pickle.load(f)
-            print 'loaded!'
+            print('loaded!')
             self.refreshAccounts()
         except IOError:
             self.accounts = []
-            print 'initialized!'
+            print('initialized!')
 
     def on_ConsoleButton_clicked(self, b):
         #### For debugging purposes...
@@ -62,9 +62,9 @@
         NewAccount(self)
 
     def on_MainIMWindow_destroy(self, w):
-        print 'Saving...'
+        print('Saving...')
         pickle.dump(self.accounts, open(SETTINGS_FILE,'wb'))
-        print 'Saved.'
+        print('Saved.')
         gtk.mainquit()
 
 
@@ -173,9 +173,9 @@
         pasw = self.xml.get_widget("password").get_text()
         serviceList = self.xml.get_widget("serviceList")
         services = []
-        for r in xrange(0, serviceList.rows):
+        for r in range(0, serviceList.rows):
             row = []
-            for c in xrange(0, serviceList.columns):
+            for c in range(0, serviceList.columns):
                 row.append(serviceList.get_text(r, c))
             services.append(row)
         if not services:
--- twisted/words/im/gtkchat.py (original)
+++ twisted/words/im/gtkchat.py (refactored)
@@ -28,7 +28,7 @@
 
 
     def registerAccountClient(self, account):
-        print 'registering account client', self, account
+        print('registering account client', self, account)
         self.accountMenuItems.append(account)
         self._updateAccountMenu()
         self.chat._accountmanager.refreshAccounts()
@@ -36,20 +36,20 @@
     def _updateAccountMenu(self):
         # This seems to be necessary -- I don't understand gtk's handling of
         # GtkOptionMenus
-        print 'updating account menu', self.accountMenuItems
+        print('updating account menu', self.accountMenuItems)
         self.accountMenu = gtk.GtkMenu()
         for account in self.accountMenuItems:
             i = gtk.GtkMenuItem(account.accountName)
             i.connect('activate', self.on_AccountsListPopup_activate, account)
             self.accountMenu.append(i)
         if self.accountMenuItems:
-            print "setting default account to", self.accountMenuItems[0]
+            print("setting default account to", self.accountMenuItems[0])
             self.currentAccount = self.accountMenuItems[0]
         self.accountMenu.show_all()
         self.optionMenu.set_menu(self.accountMenu)
 
     def on_AccountsListPopup_activate(self, w, account):
-        print 'setting current account', account
+        print('setting current account', account)
         self.currentAccount = account
 
     def on_AddContactButton_clicked(self, b):
@@ -57,7 +57,7 @@
             self.xml.get_widget("ContactNameEntry").get_text())
 
     def unregisterAccountClient(self,account):
-        print 'unregistering account client', self, account
+        print('unregistering account client', self, account)
         self.accountMenuItems.remove(account)
         self._updateAccountMenu()
 
@@ -150,8 +150,8 @@
         alloc_color = self.output.get_colormap().alloc
         self.personColor = alloc_color("#%s" % colorhash(person.name))
         self.myColor = alloc_color("#0000ff")
-        print "allocated my color %s and person color %s" % (
-            self.myColor, self.personColor)
+        print("allocated my color %s and person color %s" % (
+            self.myColor, self.personColor))
 
     def getTitle(self):
         return "Conversation - %s (%s)" % (self.person.name,
@@ -221,20 +221,20 @@
         self.xml.get_widget("TopicEntry").set_text(self._topic)
 
     def on_TopicEntry_activate(self, e):
-        print "ACTIVATING TOPIC!!"
+        print("ACTIVATING TOPIC!!")
         self.group.setTopic(e.get_text())
         # self.xml.get_widget("TopicEntry").set_editable(0)
         self.xml.get_widget("GroupInput").grab_focus()
 
     def on_ParticipantList_unselect_row(self, w, row, column, event):
-        print 'row unselected'
+        print('row unselected')
         personBox = self.xml.get_widget("PersonActionsBox")
         for child in personBox.children():
             personBox.remove(child)
 
     def on_ParticipantList_select_row(self, w, row, column, event):
         self.selectedPerson = self.group.account.client.getPerson(self.members[row])
-        print 'selected', self.selectedPerson
+        print('selected', self.selectedPerson)
         personBox = self.xml.get_widget("PersonActionsBox")
         personFrame = self.xml.get_widget("PersonFrame")
         # clear out old buttons
@@ -339,7 +339,7 @@
         pl.thaw()
 
     def _cacheColorHash(self, name):
-        if self._colorcache.has_key(name):
+        if name in self._colorcache:
             return self._colorcache[name]
         else:
             alloc_color = self.output.get_colormap().alloc
@@ -360,12 +360,12 @@
         self.onlineAccounts = []     # list of message sources currently online
 
     def registerAccountClient(self,account):
-        print 'registering account client'
+        print('registering account client')
         self.onlineAccounts.append(account)
         self.getContactsList().registerAccountClient(account)
 
     def unregisterAccountClient(self,account):
-        print 'unregistering account client'
+        print('unregistering account client')
         self.onlineAccounts.remove(account)
         self.getContactsList().unregisterAccountClient(account)
 
--- twisted/words/im/gtkcommon.py (original)
+++ twisted/words/im/gtkcommon.py (refactored)
@@ -92,12 +92,12 @@
         ##
         elif ((event.keyval == gtk.GDK.Up and isCursorOnFirstLine(entry))
               or (isMeta and event.string == 'p')):
-            print "history up"
+            print("history up")
             self.historyUp()
             stopSignal = True
         elif ((event.keyval == gtk.GDK.Down and isCursorOnLastLine(entry))
               or (isMeta and event.string == 'n')):
-            print "history down"
+            print("history down")
             self.historyDown()
             stopSignal = True
 
--- twisted/words/im/ircsupport.py (original)
+++ twisted/words/im/ircsupport.py (refactored)
@@ -48,7 +48,7 @@
     implements(interfaces.IGroup)
 
     def imgroup_testAction(self):
-        print 'action test!'
+        print('action test!')
 
     def imtarget_kick(self, target):
         if self.account.client is None:
@@ -102,7 +102,7 @@
     def connectionMade(self):
         # XXX: Why do I duplicate code in IRCClient.register?
         try:
-            print 'connection made on irc service!?', self
+            print('connection made on irc service!?', self)
             if self.account.password:
                 self.sendLine("PASS :%s" % self.account.password)
             self.setNick(self.account.username)
@@ -110,7 +110,7 @@
             for channel in self.account.channels:
                 self.joinGroup(channel)
             self.account._isOnline=1
-            print 'uh, registering irc acct'
+            print('uh, registering irc acct')
             if self._logonDeferred is not None:
                 self._logonDeferred.callback(self)
             self.chat.getContactsList()
@@ -126,12 +126,12 @@
     def kickedFrom(self, channel, kicker, message):
         """Called when I am kicked from a channel.
         """
-        print 'ono i was kicked', channel, kicker, message
+        print('ono i was kicked', channel, kicker, message)
         return self.chat.getGroupConversation(
             self.chat.getGroup(channel[1:], self), 1)
 
     def userKicked(self, kickee, channel, kicker, message):
-        print 'whew somebody else', kickee, channel, kicker, message
+        print('whew somebody else', kickee, channel, kicker, message)
 
     def noticed(self, username, channel, message):
         self.privmsg(username, channel, message, {"dontAutoRespond": 1})
@@ -168,7 +168,7 @@
         for ui in range(len(users)):
             while users[ui][0] in ["@","+"]: # channel modes
                 users[ui]=users[ui][1:]
-        if not self._namreplies.has_key(group):
+        if group not in self._namreplies:
             self._namreplies[group]=[]
         self._namreplies[group].extend(users)
         for nickname in users:
@@ -214,22 +214,22 @@
                 self._ingroups[nickname].remove(group)
                 self.getGroupConversation(group).memberLeft(nickname)
             else:
-                print "%s left %s, but wasn't in the room."%(nickname,group)
+                print("%s left %s, but wasn't in the room."%(nickname,group))
 
     def irc_QUIT(self,prefix,params):
         nickname=string.split(prefix,"!")[0]
-        if self._ingroups.has_key(nickname):
+        if nickname in self._ingroups:
             for group in self._ingroups[nickname]:
                 self.getGroupConversation(group).memberLeft(nickname)
             self._ingroups[nickname]=[]
         else:
-            print '*** WARNING: ingroups had no such key %s' % nickname
+            print('*** WARNING: ingroups had no such key %s' % nickname)
 
     def irc_NICK(self, prefix, params):
         fromNick = string.split(prefix, "!")[0]
         toNick = params[0]
-        if not self._ingroups.has_key(fromNick):
-            print "%s changed nick to %s. But she's not in any groups!?" % (fromNick, toNick)
+        if fromNick not in self._ingroups:
+            print("%s changed nick to %s. But she's not in any groups!?" % (fromNick, toNick))
             return
         for group in self._ingroups[fromNick]:
             self.getGroupConversation(group).memberChangedNick(fromNick, toNick)
@@ -237,7 +237,7 @@
         del self._ingroups[fromNick]
 
     def irc_unknown(self, prefix, command, params):
-        print "unknown message from IRCserver. prefix: %s, command: %s, params: %s" % (prefix, command, params)
+        print("unknown message from IRCserver. prefix: %s, command: %s, params: %s" % (prefix, command, params))
 
     # GTKIM calls
     def joinGroup(self,name):
@@ -255,7 +255,7 @@
                  channels=''):
         basesupport.AbstractAccount.__init__(self, accountName, autoLogin,
                                              username, password, host, port)
-        self.channels = map(string.strip,string.split(channels,','))
+        self.channels = list(map(string.strip,string.split(channels,',')))
         if self.channels == ['']:
             self.channels = []
 
--- twisted/words/im/jyaccount.py (original)
+++ twisted/words/im/jyaccount.py (refactored)
@@ -78,7 +78,7 @@
     def buildpane(self):
         gw = JPanel(GridLayout(1, 2), doublebuffered)
         gw.add(JLabel("Gateway"))
-        self.gwlist = JComboBox(self.gateways.keys())#, actionPerformed=self.changegw)
+        self.gwlist = JComboBox(list(self.gateways.keys()))#, actionPerformed=self.changegw)
         self.gwlist.setSelectedItem("Twisted")
         gw.add(self.gwlist)
 
@@ -136,11 +136,11 @@
                                           host, port, channels))
 
         self.amgui.update()
-        print "Added new account"
+        print("Added new account")
         self.mainframe.dispose()
 
     def cancel(self, ae):
-        print "Cancelling new account creation"
+        print("Cancelling new account creation")
         self.mainframe.dispose()
 
 
@@ -200,10 +200,10 @@
 
     #callable button actions
     def connect(self, ae):
-        print "Trying to connect"
+        print("Trying to connect")
         row = self.table.getSelectedRow()
         if row < 0:
-            print "Trying to connect to an account but no account selected"
+            print("Trying to connect to an account but no account selected")
         else:
             acctname = self.data.getValueAt(row, 0)
             if not self.chatui:
@@ -212,24 +212,24 @@
             self.update()
 
     def disconnect(self, ae):
-        print "Trying to disconnect"
+        print("Trying to disconnect")
         row = self.table.getSelectedRow()
         if row < 0:
-            print "Trying to logoff an account but no account was selected."
+            print("Trying to logoff an account but no account was selected.")
         else:
             acctname = self.data.getValueAt(row, 0)
             self.acctmanager.disconnect(acctname)
             self.update()
 
     def addNewAccount(self, ae):
-        print "Starting new account creation"
+        print("Starting new account creation")
         NewAccountGUI(self).show()
 
     def deleteAccount(self, ae):
-        print "Deleting account"
+        print("Deleting account")
         row = self.table.getSelectedRow()
         if row < 0:
-            print "Trying to delete an account but no account selected"
+            print("Trying to delete an account but no account selected")
         else:
             acctname = self.data.getValueAt(row, 0)
             self.acctmanager.delAccount(acctname)
--- twisted/words/im/jychat.py (original)
+++ twisted/words/im/jychat.py (refactored)
@@ -25,7 +25,7 @@
     def __init__(self, contactslist):
         self.contactslist = contactslist
         self.mainframe = JFrame("Add New Contact")
-        self.account = JComboBox(self.contactslist.clientsByName.keys())
+        self.account = JComboBox(list(self.contactslist.clientsByName.keys()))
         self.contactname = JTextField()
         self.buildpane()
 
@@ -77,12 +77,12 @@
 
     def registerAccountClient(self, client):
         ContactsList.registerAccountClient(self, client)
-        if not client.accountName in self.clientsByName.keys():
+        if not client.accountName in list(self.clientsByName.keys()):
             self.clientsByName[client.accountName] = client
 
     def unregisterAccount(self, client):
         ContactsList.unregisterAccountClient(self, client)
-        if client.accountName in self.clientsByName.keys():
+        if client.accountName in list(self.clientsByName.keys()):
             del self.clientsByName[client.accountName]
 
     def contactChangedNick(self, person, newnick):
@@ -104,7 +104,7 @@
 
     def update(self):
         contactdata = []
-        for contact in self.onlineContacts.values():
+        for contact in list(self.onlineContacts.values()):
             if contact.status == AWAY:
                 stat = "(away)"
             else:
@@ -117,7 +117,7 @@
     def message(self, ae):
         row = self.table.getSelectedRow()
         if row < 0:
-            print "Trying to send IM to person, but no person selected"
+            print("Trying to send IM to person, but no person selected")
         else:
             person = self.onlineContacts[self.data.getValueAt(row, 0)]
             self.chat.getConversation(person)
--- twisted/words/im/pbsupport.py (original)
+++ twisted/words/im/pbsupport.py (refactored)
@@ -4,7 +4,7 @@
 
 """L{twisted.words} support for Instance Messenger."""
 
-from __future__ import nested_scopes
+
 
 from twisted.internet import defer
 from twisted.internet import error
@@ -44,7 +44,7 @@
             return self.account.client.perspective.callRemote('directMessage',self.name, text)
 
     def metadataFailed(self, result, text):
-        print "result:",result,"text:",text
+        print("result:",result,"text:",text)
         return self.account.client.perspective.directMessage(self.name, text)
 
     def setStatus(self, status):
@@ -77,7 +77,7 @@
             self.name)
 
     def metadataFailed(self, result, text):
-        print "result:",result,"text:",text
+        print("result:",result,"text:",text)
         return self.account.client.perspective.callRemote('groupMessage',
                                                           self.name, text)
 
@@ -101,7 +101,7 @@
                  _logonDeferred=None):
         self.accountName = "%s (%s:%s)" % (acct.accountName, serviceName, perspectiveName)
         self.name = perspectiveName
-        print "HELLO I AM A PB SERVICE", serviceName, perspectiveName
+        print("HELLO I AM A PB SERVICE", serviceName, perspectiveName)
         self.chat = chatui
         self.account = acct
         self._logonDeferred = _logonDeferred
@@ -119,19 +119,19 @@
         self.perspective.callRemote('addContact', name)
 
     def remote_receiveGroupMembers(self, names, group):
-        print 'received group members:', names, group
+        print('received group members:', names, group)
         self.getGroupConversation(group).setGroupMembers(names)
 
     def remote_receiveGroupMessage(self, sender, group, message, metadata=None):
-        print 'received a group message', sender, group, message, metadata
+        print('received a group message', sender, group, message, metadata)
         self.getGroupConversation(group).showGroupMessage(sender, message, metadata)
 
     def remote_memberJoined(self, member, group):
-        print 'member joined', member, group
+        print('member joined', member, group)
         self.getGroupConversation(group).memberJoined(member)
 
     def remote_memberLeft(self, member, group):
-        print 'member left'
+        print('member left')
         self.getGroupConversation(group).memberLeft(member)
 
     def remote_notifyStatusChanged(self, name, status):
@@ -145,7 +145,7 @@
             self.chat.getPerson(name, self).setStatus(status)
 
     def remote_setGroupMetadata(self, dict_, groupName):
-        if dict_.has_key("topic"):
+        if "topic" in dict_:
             self.getGroupConversation(groupName).setTopic(dict_["topic"], dict_.get("topic_author", None))
 
     def joinGroup(self, name):
@@ -162,12 +162,12 @@
         self.perspective.callRemote('getGroupMembers', name)
 
     def _cbGroupLeft(self, result, name):
-        print 'left',name
+        print('left',name)
         groupConv = self.chat.getGroupConversation(self.getGroup(name), 1)
         groupConv.showGroupMessage("sys", "you left")
 
     def connected(self, perspective):
-        print 'Connected Words Client!', perspective
+        print('Connected Words Client!', perspective)
         if self._logonDeferred is not None:
             self._logonDeferred.callback(self)
         self.perspective = perspective
@@ -227,15 +227,15 @@
 
 
     def _startLogOn(self, chatui):
-        print 'Connecting...',
+        print('Connecting...', end=' ')
         d = pb.getObjectAt(self.host, self.port)
         d.addCallbacks(self._cbConnected, self._ebConnected,
                        callbackArgs=(chatui,))
         return d
 
     def _cbConnected(self, root, chatui):
-        print 'Connected!'
-        print 'Identifying...',
+        print('Connected!')
+        print('Identifying...', end=' ')
         d = pb.authIdentity(root, self.username, self.password)
         d.addCallbacks(self._cbIdent, self._ebConnected,
                        callbackArgs=(chatui,))
@@ -243,9 +243,9 @@
 
     def _cbIdent(self, ident, chatui):
         if not ident:
-            print 'falsely identified.'
+            print('falsely identified.')
             return self._ebConnected(Failure(Exception("username or password incorrect")))
-        print 'Identified!'
+        print('Identified!')
         dl = []
         for handlerClass, sname, pname in self.services:
             d = defer.Deferred()
@@ -255,6 +255,6 @@
         return defer.DeferredList(dl)
 
     def _ebConnected(self, error):
-        print 'Not connected.'
+        print('Not connected.')
         return error
 
--- twisted/words/im/tocsupport.py (original)
+++ twisted/words/im/tocsupport.py (refactored)
@@ -102,7 +102,7 @@
 
     def addContact(self, name):
         self.add_buddy([name])
-        if not self._buddylist.has_key('TwistedIM'):
+        if 'TwistedIM' not in self._buddylist:
             self._buddylist['TwistedIM'] = []
         if name in self._buddylist['TwistedIM']:
             # whoops, don't add again
@@ -130,7 +130,7 @@
             self._debug('adding deny')
             self.add_deny(deny)
         clist=[]
-        for k in buddylist.keys():
+        for k in list(buddylist.keys()):
             self.add_buddy(buddylist[k])
             for name in buddylist[k]:
                 self.getPerson(name).setStatusAndIdle(OFFLINE, '--')
@@ -138,12 +138,12 @@
     name = None
     def tocNICK(self,data):
         if not self.name:
-            print 'Waiting for second NICK', data
+            print('Waiting for second NICK', data)
             self.name=data[0]
             self.accountName = '%s (TOC)' % self.name
             self.chat.getContactsList()
         else:
-            print 'reregistering...?', data
+            print('reregistering...?', data)
             self.name=data[0]
             # self.accountName = "%s (TOC)"%data[0]
             if self._logonDeferred is not None:
@@ -152,9 +152,9 @@
 
     ### Error Messages
     def hearError(self, code, args):
-        print '*** TOC ERROR ***', repr(code), repr(args)
+        print('*** TOC ERROR ***', repr(code), repr(args))
     def hearWarning(self, newamount, username):
-        print '*** TOC WARNING ***', repr(newamount), repr(username)
+        print('*** TOC WARNING ***', repr(newamount), repr(username))
     ### Buddy Messages
     def hearMessage(self,username,message,autoreply):
         if autoreply:
@@ -187,18 +187,18 @@
         group=self.roomIDreverse[roomid]
         self.getGroupConversation(group).showGroupMessage(username, dehtml(message))
     def chatHearWhisper(self, roomid, username, message):
-        print '*** user whispered *** ', roomid, username, message
+        print('*** user whispered *** ', roomid, username, message)
     def chatInvited(self, roomid, roomname, username, message):
-        print '*** user invited us to chat *** ',roomid, roomname, username, message
+        print('*** user invited us to chat *** ',roomid, roomname, username, message)
     def chatLeft(self, roomid):
         group=self.roomIDreverse[roomid]
         self.getGroupConversation(group,1)
         del self.roomID[group]
         del self.roomIDreverse[roomid]
     def rvousProposal(self,type,cookie,user,vip,port,**kw):
-        print '*** rendezvous. ***', type, cookie, user, vip, port, kw
+        print('*** rendezvous. ***', type, cookie, user, vip, port, kw)
     def receiveBytes(self, user, file, chunk, sofar, total):
-        print '*** File transfer! ***', user, file, chunk, sofar, total
+        print('*** File transfer! ***', user, file, chunk, sofar, total)
 
     def joinGroup(self,name):
         self.chat_join(4,toc.normalize(name))
--- twisted/words/protocols/irc.py (original)
+++ twisted/words/protocols/irc.py (refactored)
@@ -38,10 +38,10 @@
 from twisted.python import log, reflect, text
 
 NUL = chr(0)
-CR = chr(015)
-NL = chr(012)
+CR = chr(0o15)
+NL = chr(0o12)
 LF = NL
-SPC = chr(040)
+SPC = chr(0o40)
 
 CHANNEL_PREFIXES = '&#!+'
 
@@ -115,7 +115,7 @@
 
     def sendLine(self, line):
         if self.encoding is not None:
-            if isinstance(line, unicode):
+            if isinstance(line, str):
                 line = line.encode(self.encoding)
         self.transport.write("%s%s%s" % (line, CR, LF))
 
@@ -129,16 +129,16 @@
         """
 
         if not command:
-            raise ValueError, "IRC message requires a command."
+            raise ValueError("IRC message requires a command.")
 
         if ' ' in command or command[0] == ':':
             # Not the ONLY way to screw up, but provides a little
             # sanity checking to catch likely dumb mistakes.
-            raise ValueError, "Somebody screwed up, 'cuz this doesn't" \
-                  " look like a command to me: %s" % command
+            raise ValueError("Somebody screwed up, 'cuz this doesn't" \
+                  " look like a command to me: %s" % command)
 
         line = string.join([command] + list(parameter_list))
-        if prefix.has_key('prefix'):
+        if 'prefix' in prefix:
             line = ":%s %s" % (prefix['prefix'], line)
         self.sendLine(line)
 
@@ -972,8 +972,8 @@
                 raise ValueError("Maximum length must exceed %d for message "
                                  "to %s" % (minimumLength, user))
             lines = split(message, length - minimumLength)
-            map(lambda line, self=self, fmt=fmt: self.sendLine(fmt % line),
-                lines)
+            list(map(lambda line, self=self, fmt=fmt: self.sendLine(fmt % line),
+                lines))
 
     def notice(self, user, message):
         """
@@ -1097,14 +1097,14 @@
 
         if len(self._pings) > self._MAX_PINGRING:
             # Remove some of the oldest entries.
-            byValue = [(v, k) for (k, v) in self._pings.items()]
+            byValue = [(v, k) for (k, v) in list(self._pings.items())]
             byValue.sort()
             excess = self._MAX_PINGRING - len(self._pings)
-            for i in xrange(excess):
+            for i in range(excess):
                 del self._pings[byValue[i][1]]
 
     def dccSend(self, user, file):
-        if type(file) == types.StringType:
+        if type(file) == bytes:
             file = open(file, 'r')
 
         size = fileSize(file)
@@ -1114,7 +1114,7 @@
         factory = DccSendFactory(file)
         port = reactor.listenTCP(0, factory, 1)
 
-        raise NotImplementedError,(
+        raise NotImplementedError(
             "XXX!!! Help!  I need to bind a socket, have it listen, and tell me its address.  "
             "(and stop accepting once we've made a single connection.)")
 
@@ -1405,7 +1405,7 @@
         if not self.fingerReply:
             return
 
-        if callable(self.fingerReply):
+        if hasattr(self.fingerReply, '__call__'):
             reply = self.fingerReply()
         else:
             reply = str(self.fingerReply)
@@ -1517,7 +1517,7 @@
         # Use splitQuoted for those who send files with spaces in the names.
         data = text.splitQuoted(data)
         if len(data) < 3:
-            raise IRCBadMessage, "malformed DCC SEND request: %r" % (data,)
+            raise IRCBadMessage("malformed DCC SEND request: %r" % (data,))
 
         (filename, address, port) = data[:3]
 
@@ -1525,7 +1525,7 @@
         try:
             port = int(port)
         except ValueError:
-            raise IRCBadMessage, "Indecipherable port %r" % (port,)
+            raise IRCBadMessage("Indecipherable port %r" % (port,))
 
         size = -1
         if len(data) >= 4:
@@ -1540,7 +1540,7 @@
     def dcc_ACCEPT(self, user, channel, data):
         data = text.splitQuoted(data)
         if len(data) < 3:
-            raise IRCBadMessage, "malformed DCC SEND ACCEPT request: %r" % (data,)
+            raise IRCBadMessage("malformed DCC SEND ACCEPT request: %r" % (data,))
         (filename, port, resumePos) = data[:3]
         try:
             port = int(port)
@@ -1553,7 +1553,7 @@
     def dcc_RESUME(self, user, channel, data):
         data = text.splitQuoted(data)
         if len(data) < 3:
-            raise IRCBadMessage, "malformed DCC SEND RESUME request: %r" % (data,)
+            raise IRCBadMessage("malformed DCC SEND RESUME request: %r" % (data,))
         (filename, port, resumePos) = data[:3]
         try:
             port = int(port)
@@ -1565,7 +1565,7 @@
     def dcc_CHAT(self, user, channel, data):
         data = text.splitQuoted(data)
         if len(data) < 3:
-            raise IRCBadMessage, "malformed DCC CHAT request: %r" % (data,)
+            raise IRCBadMessage("malformed DCC CHAT request: %r" % (data,))
 
         (filename, address, port) = data[:3]
 
@@ -1573,7 +1573,7 @@
         try:
             port = int(port)
         except ValueError:
-            raise IRCBadMessage, "Indecipherable port %r" % (port,)
+            raise IRCBadMessage("Indecipherable port %r" % (port,))
 
         self.dccDoChat(user, channel, address, port, data)
 
@@ -1660,9 +1660,8 @@
 
     def ctcpReply_PING(self, user, channel, data):
         nick = user.split('!', 1)[0]
-        if (not self._pings) or (not self._pings.has_key((nick, data))):
-            raise IRCBadMessage,\
-                  "Bogus PING response from %s: %s" % (user, data)
+        if (not self._pings) or ((nick, data) not in self._pings):
+            raise IRCBadMessage("Bogus PING response from %s: %s" % (user, data))
 
         t0 = self._pings[(nick, data)]
         self.pong(user, time.time() - t0)
@@ -1708,7 +1707,7 @@
         line = lowDequote(line)
         try:
             prefix, command, params = parsemsg(line)
-            if numeric_to_symbolic.has_key(command):
+            if command in numeric_to_symbolic:
                 command = numeric_to_symbolic[command]
             self.handleCommand(command, prefix, params)
         except IRCBadMessage:
@@ -1741,10 +1740,9 @@
         pass
     else:
         try:
-            address = long(address)
+            address = int(address)
         except ValueError:
-            raise IRCBadMessage,\
-                  "Indecipherable address %r" % (address,)
+            raise IRCBadMessage("Indecipherable address %r" % (address,))
         else:
             address = (
                 (address >> 24) & 0xFF,
@@ -1791,7 +1789,7 @@
     connected = 0
 
     def __init__(self, file):
-        if type(file) is types.StringType:
+        if type(file) is bytes:
             self.file = open(file, 'r')
 
     def connectionMade(self):
@@ -1967,7 +1965,7 @@
         pass
     else:
         try:
-            address = long(address)
+            address = int(address)
         except ValueError:
             pass
         else:
@@ -1979,7 +1977,7 @@
                 )
             # The mapping to 'int' is to get rid of those accursed
             # "L"s which python 1.5.2 puts on the end of longs.
-            address = string.join(map(str,map(int,address)), ".")
+            address = string.join(list(map(str,list(map(int,address)))), ".")
 
     if dcctype == 'SEND':
         filename = arg
@@ -2135,7 +2133,7 @@
 
 # CTCP constants and helper functions
 
-X_DELIM = chr(001)
+X_DELIM = chr(0o01)
 
 def ctcpExtract(message):
     """Extract CTCP data from a string.
@@ -2162,11 +2160,11 @@
             normal_messages.append(messages.pop(0))
         odd = not odd
 
-    extended_messages[:] = filter(None, extended_messages)
-    normal_messages[:] = filter(None, normal_messages)
-
-    extended_messages[:] = map(ctcpDequote, extended_messages)
-    for i in xrange(len(extended_messages)):
+    extended_messages[:] = [_f for _f in extended_messages if _f]
+    normal_messages[:] = [_f for _f in normal_messages if _f]
+
+    extended_messages[:] = list(map(ctcpDequote, extended_messages))
+    for i in range(len(extended_messages)):
         m = string.split(extended_messages[i], SPC, 1)
         tag = m[0]
         if len(m) > 1:
@@ -2180,7 +2178,7 @@
 
 # CTCP escaping
 
-M_QUOTE= chr(020)
+M_QUOTE= chr(0o20)
 
 mQuoteTable = {
     NUL: M_QUOTE + '0',
@@ -2190,7 +2188,7 @@
     }
 
 mDequoteTable = {}
-for k, v in mQuoteTable.items():
+for k, v in list(mQuoteTable.items()):
     mDequoteTable[v[-1]] = k
 del k, v
 
@@ -2221,7 +2219,7 @@
 
 xDequoteTable = {}
 
-for k, v in xQuoteTable.items():
+for k, v in list(xQuoteTable.items()):
     xDequoteTable[v[-1]] = k
 
 xEscape_re = re.compile('%s.' % (re.escape(X_QUOTE),), re.DOTALL)
@@ -2253,7 +2251,7 @@
     coded_messages = []
     for (tag, data) in messages:
         if data:
-            if not isinstance(data, types.StringType):
+            if not isinstance(data, bytes):
                 try:
                     # data as list-of-strings
                     data = " ".join(map(str, data))
@@ -2554,5 +2552,5 @@
 }
 
 numeric_to_symbolic = {}
-for k, v in symbolic_to_numeric.items():
+for k, v in list(symbolic_to_numeric.items()):
     numeric_to_symbolic[v] = k
--- twisted/words/protocols/msn.py (original)
+++ twisted/words/protocols/msn.py (refactored)
@@ -73,7 +73,7 @@
 
 import types, operator, os
 from random import randint
-from urllib import quote, unquote
+from urllib.parse import quote, unquote
 
 from twisted.python import failure, log
 from twisted.python.hashlib import md5
@@ -129,7 +129,7 @@
     if error == None:
         error = "Invalid Number of Parameters for %s" % cmd
     if num != expected:
-        raise MSNProtocolError, error
+        raise MSNProtocolError(error)
 
 def _parseHeader(h, v):
     """
@@ -213,7 +213,7 @@
     def handleEndHeaders(self):
         if self.connected:
             self.transport.loseConnection()
-        if not self.headers.has_key('passporturls') or not self.headers['passporturls'].has_key('dalogin'):
+        if 'passporturls' not in self.headers or 'dalogin' not in self.headers['passporturls']:
             self.deferred.errback(failure.Failure(failure.DefaultException("Invalid Nexus Reply")))
         self.deferred.callback('https://' + self.headers['passporturls']['dalogin'])
 
@@ -256,7 +256,7 @@
             self.transport.loseConnection()
         authHeader = 'authentication-info'
         _interHeader = 'www-authenticate'
-        if self.headers.has_key(_interHeader):
+        if _interHeader in self.headers:
             authHeader = _interHeader
         try:
             info = self.headers[authHeader]
@@ -266,7 +266,7 @@
                 handler(info)
             else:
                 raise Exception()
-        except Exception, e:
+        except Exception as e:
             self.deferred.errback(failure.Failure(e))
 
     def handleResponse(self, r):
@@ -352,7 +352,7 @@
         used to calculte the number to send
         as the message length when sending a message.
         """
-        return reduce(operator.add, [len(x[0]) + len(x[1]) + 4  for x in self.headers.items()]) + len(self.message) + 2
+        return reduce(operator.add, [len(x[0]) + len(x[1]) + 4  for x in list(self.headers.items())]) + len(self.message) + 2
 
     def setHeader(self, header, value):
         """ set the desired header """
@@ -367,7 +367,7 @@
 
     def hasHeader(self, header):
         """ check to see if the desired header exists """
-        return self.headers.has_key(header)
+        return header in self.headers
 
     def getMessage(self):
         """ return the message - not including headers """
@@ -430,7 +430,7 @@
         elif t == HAS_PAGER:
             self.hasPager = value
         else:
-            raise ValueError, "Invalid Phone Type"
+            raise ValueError("Invalid Phone Type")
 
     def addToList(self, listType):
         """
@@ -476,7 +476,7 @@
         Obtain all contacts which belong
         to the given list type.
         """
-        return dict([(uH,obj) for uH,obj in self.contacts.items() if obj.lists & listType])
+        return dict([(uH,obj) for uH,obj in list(self.contacts.items()) if obj.lists & listType])
 
     def addContact(self, contact):
         """
@@ -583,7 +583,7 @@
         Fire the callback for the given id
         if one exists and return 1, else return false
         """
-        if self.ids.has_key(id):
+        if id in self.ids:
             self.ids[id][0].callback(args)
             del self.ids[id]
             return 1
@@ -624,16 +624,16 @@
             try:
                 header, value = line.split(':')
             except ValueError:
-                raise MSNProtocolError, "Invalid Message Header"
+                raise MSNProtocolError("Invalid Message Header")
             self.currentMessage.setHeader(header, unquote(value).lstrip())
             return
         try:
             cmd, params = line.split(' ', 1)
         except ValueError:
-            raise MSNProtocolError, "Invalid Message, %s" % repr(line)
+            raise MSNProtocolError("Invalid Message, %s" % repr(line))
 
         if len(cmd) != 3:
-            raise MSNProtocolError, "Invalid Command, %s" % repr(cmd)
+            raise MSNProtocolError("Invalid Command, %s" % repr(cmd))
         if cmd.isdigit():
             errorCode = int(cmd)
             id = int(params.split()[0])
@@ -649,7 +649,7 @@
         if handler:
             try:
                 handler(params.split())
-            except MSNProtocolError, why:
+            except MSNProtocolError as why:
                 self.gotBadLine(line, why)
         else:
             self.handle_UNKNOWN(cmd, params.split())
@@ -681,7 +681,7 @@
         try:
             messageLen = int(params[2])
         except ValueError:
-            raise MSNProtocolError, "Invalid Parameter for MSG length argument"
+            raise MSNProtocolError("Invalid Parameter for MSG length argument")
         self.currentMessage = MSNMessage(length=messageLen, userHandle=params[0], screenName=unquote(params[1]))
 
     def handle_UNKNOWN(self, cmd, params):
@@ -735,7 +735,7 @@
 
     def handle_XFR(self, params):
         if len(params) < 4:
-            raise MSNProtocolError, "Invalid number of parameters for XFR"
+            raise MSNProtocolError("Invalid number of parameters for XFR")
         id, refType, addr = params[:3]
         # was addr a host:port pair?
         try:
@@ -816,7 +816,7 @@
 
     def handle_USR(self, params):
         if len(params) != 4 and len(params) != 6:
-            raise MSNProtocolError, "Invalid Number of Parameters for USR"
+            raise MSNProtocolError("Invalid Number of Parameters for USR")
 
         mechanism = params[1]
         if mechanism == "OK":
@@ -876,7 +876,7 @@
         contact = MSNContact(userHandle=params[0], screenName=unquote(params[1]),
                              lists=int(params[2]))
         if contact.lists & FORWARD_LIST:
-            contact.groups.extend(map(int, params[3].split(',')))
+            contact.groups.extend(list(map(int, params[3].split(','))))
         self._getStateData('list').addContact(contact)
         self._setStateData('last_contact', contact)
         sofar = self._getStateData('lst_sofar') + 1
@@ -914,7 +914,7 @@
             elif params[0].lower() == "n":
                 self._getStateData('list').autoAdd = 1
             else:
-                raise MSNProtocolError, "Invalid Paramater for GTC" # debug
+                raise MSNProtocolError("Invalid Paramater for GTC") # debug
         else:
             id = int(params[0])
             if params[1].lower() == "a":
@@ -922,7 +922,7 @@
             elif params[1].lower() == "n":
                 self._fireCallback(id, 1)
             else:
-                raise MSNProtocolError, "Invalid Paramater for GTC" # debug
+                raise MSNProtocolError("Invalid Paramater for GTC") # debug
 
     def handle_SYN(self, params):
         id = int(params[0])
@@ -968,24 +968,24 @@
         checkParamLen(len(params), 5, 'ADG')
         id = int(params[0])
         if not self._fireCallback(id, int(params[1]), unquote(params[2]), int(params[3])):
-            raise MSNProtocolError, "ADG response does not match up to a request" # debug
+            raise MSNProtocolError("ADG response does not match up to a request") # debug
 
     def handle_RMG(self, params):
         checkParamLen(len(params), 3, 'RMG')
         id = int(params[0])
         if not self._fireCallback(id, int(params[1]), int(params[2])):
-            raise MSNProtocolError, "RMG response does not match up to a request" # debug
+            raise MSNProtocolError("RMG response does not match up to a request") # debug
 
     def handle_REG(self, params):
         checkParamLen(len(params), 5, 'REG')
         id = int(params[0])
         if not self._fireCallback(id, int(params[1]), int(params[2]), unquote(params[3])):
-            raise MSNProtocolError, "REG response does not match up to a request" # debug
+            raise MSNProtocolError("REG response does not match up to a request") # debug
 
     def handle_ADD(self, params):
         numParams = len(params)
         if numParams < 5 or params[1].upper() not in ('AL','BL','RL','FL'):
-            raise MSNProtocolError, "Invalid Paramaters for ADD" # debug
+            raise MSNProtocolError("Invalid Paramaters for ADD") # debug
         id = int(params[0])
         listType = params[1].lower()
         listVer = int(params[2])
@@ -993,7 +993,7 @@
         groupID = None
         if numParams == 6: # they sent a group id
             if params[1].upper() != "FL":
-                raise MSNProtocolError, "Only forward list can contain groups" # debug
+                raise MSNProtocolError("Only forward list can contain groups") # debug
             groupID = int(params[5])
         if not self._fireCallback(id, listCodeToID[listType], userHandle, listVer, groupID):
             self.userAddedMe(userHandle, unquote(params[4]), listVer)
@@ -1001,7 +1001,7 @@
     def handle_REM(self, params):
         numParams = len(params)
         if numParams < 4 or params[1].upper() not in ('AL','BL','FL','RL'):
-            raise MSNProtocolError, "Invalid Paramaters for REM" # debug
+            raise MSNProtocolError("Invalid Paramaters for REM") # debug
         id = int(params[0])
         listType = params[1].lower()
         listVer = int(params[2])
@@ -1009,7 +1009,7 @@
         groupID = None
         if numParams == 5:
             if params[1] != "FL":
-                raise MSNProtocolError, "Only forward list can contain groups" # debug
+                raise MSNProtocolError("Only forward list can contain groups") # debug
             groupID = int(params[4])
         if not self._fireCallback(id, listCodeToID[listType], userHandle, listVer, groupID):
             if listType.upper() == "RL":
@@ -1031,7 +1031,7 @@
             port = MSN_PORT
 
         if not self._fireCallback(id, host, int(port), params[4]):
-            raise MSNProtocolError, "Got XFR (referral) that I didn't ask for .. should this happen?" # debug
+            raise MSNProtocolError("Got XFR (referral) that I didn't ask for .. should this happen?") # debug
 
     def handle_RNG(self, params):
         checkParamLen(len(params), 6, 'RNG')
@@ -1052,7 +1052,7 @@
         elif params[0] == "SSD":
             self.serverGoingDown()
         else:
-            raise MSNProtocolError, "Invalid Parameters received for OUT" # debug
+            raise MSNProtocolError("Invalid Parameters received for OUT") # debug
 
     # callbacks
 
@@ -1701,7 +1701,7 @@
 
     def connectionMade(self):
         MSNEventBase.connectionMade(self)
-        print 'sending initial stuff'
+        print('sending initial stuff')
         self._sendInit()
 
     def connectionLost(self, reason):
@@ -1968,7 +1968,7 @@
         self.sendLine('MIME-Version: %s' % message.getHeader('MIME-Version'))
         self.sendLine('Content-Type: %s' % message.getHeader('Content-Type'))
         # send the rest of the headers
-        for header in [h for h in message.headers.items() if h[0].lower() not in ('mime-version','content-type')]:
+        for header in [h for h in list(message.headers.items()) if h[0].lower() not in ('mime-version','content-type')]:
             self.sendLine("%s: %s" % (header[0], header[1]))
         self.transport.write(CR+LF)
         self.transport.write(message.message)
@@ -2117,11 +2117,11 @@
         self.segmentLength = 0
         self.buffer = ''
 
-        if isinstance(file, types.StringType):
+        if isinstance(file, bytes):
             path = os.path.join(directory, file)
             if os.path.exists(path) and not self.overwrite:
                 log.msg('File already exists...')
-                raise IOError, "File Exists" # is this all we should do here?
+                raise IOError("File Exists") # is this all we should do here?
             self.file = open(os.path.join(directory, file), 'wb')
         else:
             self.file = file
@@ -2242,7 +2242,7 @@
         @param file: A string or file object represnting the file to send.
         """
 
-        if isinstance(file, types.StringType):
+        if isinstance(file, bytes):
             self.file = open(file, 'rb')
         else:
             self.file = file
@@ -2433,7 +2433,7 @@
 
 # mapping of list codes to list ids
 listCodeToID = {}
-for id,code in listIDToCode.items():
+for id,code in list(listIDToCode.items()):
     listCodeToID[code] = id
 
 del id, code
@@ -2445,5 +2445,5 @@
 
 # Reverse of the above
 classNameToGUID = {}
-for guid, name in guidToClassName.iteritems():
+for guid, name in guidToClassName.items():
     classNameToGUID[name] = guid
--- twisted/words/protocols/oscar.py (original)
+++ twisted/words/protocols/oscar.py (refactored)
@@ -25,8 +25,8 @@
     if lines*16 != len(data): lines=lines+1
     for i in range(lines):
         d = tuple(data[16*i:16*i+16])
-        hex = map(lambda x: "%02X"%ord(x),d)
-        text = map(lambda x: (len(repr(x))>3 and '.') or x, d)
+        hex = ["%02X"%ord(x) for x in d]
+        text = [(len(repr(x))>3 and '.') or x for x in d]
         log.msg(' '.join(hex)+ ' '*3*(16-len(d)) +''.join(text))
     log.msg('')
 
@@ -67,7 +67,7 @@
 
 def encryptPasswordICQ(password):
     key=[0xF3,0x26,0x81,0xC4,0x39,0x86,0xDB,0x92,0x71,0xA3,0xB9,0xE6,0x53,0x7A,0x95,0x7C]
-    bytes=map(ord,password)
+    bytes=list(map(ord,password))
     r=""
     for i in range(len(bytes)):
         r=r+chr(bytes[i]^key[i%len(key)])
@@ -100,7 +100,7 @@
         self.warning = warn
         self.flags = []
         self.caps = []
-        for k,v in tlvs.items():
+        for k,v in list(tlvs.items()):
             if k == 1: # user flags
                 v=struct.unpack('!H',v)[0]
                 for o, f in [(1,'trial'),
@@ -208,7 +208,7 @@
     def __init__(self, name, tlvs = {}):
         self.name = name
         self.tlvs = tlvs
-        for k,v in tlvs.items():
+        for k,v in list(tlvs.items()):
             if k == 0x013c: # buddy comment
                 self.buddyComment = v
             elif k == 0x013d: # buddy alerts
@@ -230,7 +230,7 @@
                 self.alertSound = v
  
     def oscarRep(self, groupID, buddyID):
-        tlvData = reduce(lambda x,y: x+y, map(lambda (k,v):TLV(k,v), self.tlvs.items()), '\000\000')
+        tlvData = reduce(lambda x,y: x+y, [TLV(k_v[0],k_v[1]) for k_v in list(self.tlvs.items())], '\000\000')
         return struct.pack('!H', len(self.name)) + self.name + \
                struct.pack('!HH', groupID, buddyID) + '\000\000' + tlvData
 
@@ -349,7 +349,7 @@
 
     def oscar_Data(self,data):
         snac=readSNAC(data[1])
-        if self.requestCallbacks.has_key(snac[4]):
+        if snac[4] in self.requestCallbacks:
             d = self.requestCallbacks[snac[4]]
             del self.requestCallbacks[snac[4]]
             if snac[1]!=1:
@@ -374,7 +374,7 @@
         self.supportedFamilies = struct.unpack("!"+str(numFamilies)+'H', snac[3])
         d = ''
         for fam in self.supportedFamilies:
-            if self.snacFamilies.has_key(fam):
+            if fam in self.snacFamilies:
                 d=d+struct.pack('!2H',fam,self.snacFamilies[fam][0])
         self.sendSNACnr(0x01,0x17, d)
 
@@ -397,7 +397,7 @@
         """
         d = ''
         for fam in self.supportedFamilies:
-            if self.snacFamilies.has_key(fam):
+            if fam in self.snacFamilies:
                 version, toolID, toolVersion = self.snacFamilies[fam]
                 d = d + struct.pack('!4H',fam,version,toolID,toolVersion)
         self.sendSNACnr(0x01,0x02,d)
@@ -539,7 +539,7 @@
         if channel == 1: # message
             flags = []
             multiparts = []
-            for k, v in tlvs.items():
+            for k, v in list(tlvs.items()):
                 if k == 2:
                     while v:
                         v = v[2:] # skip bad data
@@ -592,14 +592,14 @@
                 exchange = struct.unpack('!H',moreTLVs[10001][:2])[0]
                 name = moreTLVs[10001][3:-2]
                 instance = struct.unpack('!H',moreTLVs[10001][-2:])[0]
-                if not self.services.has_key(SERVICE_CHATNAV):
+                if SERVICE_CHATNAV not in self.services:
                     self.connectService(SERVICE_CHATNAV,1).addCallback(lambda x: self.services[SERVICE_CHATNAV].getChatInfo(exchange, name, instance).\
                         addCallback(self._cbGetChatInfoForInvite, user, moreTLVs[12]))
                 else:
                     self.services[SERVICE_CHATNAV].getChatInfo(exchange, name, instance).\
                         addCallback(self._cbGetChatInfoForInvite, user, moreTLVs[12])
             elif requestClass == CAP_SEND_FILE:
-                if moreTLVs.has_key(11): # cancel
+                if 11 in moreTLVs: # cancel
                     log.msg('cancelled file request')
                     log.msg(status)
                     return # handle this later
@@ -615,7 +615,7 @@
             log.msg(tlvs)
 
     def _cbGetChatInfoForInvite(self, info, user, message):
-        apply(self.receiveChatInvite, (user,message)+info)
+        self.receiveChatInvite(*(user,message)+info)
 
     def oscar_09_03(self, snac):
         """
@@ -692,14 +692,14 @@
                 groups[groupID].addUser(buddyID, SSIBuddy(name, tlvs))
             elif itemType == 1: # group
                 g = SSIGroup(name, tlvs)
-                if groups.has_key(0): groups[0].addUser(groupID, g)
+                if 0 in groups: groups[0].addUser(groupID, g)
                 groups[groupID] = g
             elif itemType == 2: # permit
                 permit.append(name)
             elif itemType == 3: # deny
                 deny.append(name)
             elif itemType == 4: # permit deny info
-                if not tlvs.has_key(0xcb):
+                if 0xcb not in tlvs:
                     continue # this happens with ICQ
                 permitMode = {1:'permitall',2:'denyall',3:'permitsome',4:'denysome',5:'permitbuddies'}[ord(tlvs[0xca])]
                 visibility = {'\xff\xff\xff\xff':'all','\x00\x00\x00\x04':'notaim'}[tlvs[0xcb]]
@@ -805,9 +805,9 @@
         """
         data = ''.join([chr(random.randrange(0, 127)) for i in range(8)]) # cookie
         data = data + '\x00\x01' + chr(len(user)) + user
-        if not type(message) in (types.TupleType, types.ListType):
+        if not type(message) in (tuple, list):
             message = [[message,]]
-            if type(message[0][0]) == types.UnicodeType:
+            if type(message[0][0]) == str:
                 message[0].append('unicode')
         messageData = ''
         for part in message:
@@ -861,7 +861,7 @@
         """
         create a chat room
         """
-        if self.services.has_key(SERVICE_CHATNAV):
+        if SERVICE_CHATNAV in self.services:
             return self.services[SERVICE_CHATNAV].createChat(shortName)
         else:
             return self.connectService(SERVICE_CHATNAV,1).addCallback(lambda s: s.createChat(shortName))
@@ -978,7 +978,7 @@
         self.d = d
 
     def connectionLost(self, reason):
-        for k,v in self.bos.services.items():
+        for k,v in list(self.bos.services.items()):
             if v == self:
                 del self.bos.services[k]
                 return
@@ -1168,7 +1168,7 @@
             i=snac[5].find("\000")
             snac[5]=snac[5][i:]
         tlvs=readTLVs(snac[5])
-        if tlvs.has_key(6):
+        if 6 in tlvs:
             self.cookie=tlvs[6]
             server,port=string.split(tlvs[5],":")
             d = self.connectToBOS(server, int(port))
@@ -1176,7 +1176,7 @@
             if self.deferred:
                 d.chainDeferred(self.deferred)
             self.disconnect()
-        elif tlvs.has_key(8):
+        elif 8 in tlvs:
             errorcode=tlvs[8]
             errorurl=tlvs[4]
             if errorcode=='\000\030':
--- twisted/words/protocols/toc.py (original)
+++ twisted/words/protocols/toc.py (refactored)
@@ -26,10 +26,10 @@
 import time
 import base64
 import os
-import StringIO
-
-SIGNON,DATA,ERROR,SIGNOFF,KEEP_ALIVE=range(1,6)
-PERMITALL,DENYALL,PERMITSOME,DENYSOME=range(1,5)
+import io
+
+SIGNON,DATA,ERROR,SIGNOFF,KEEP_ALIVE=list(range(1,6))
+PERMITALL,DENYALL,PERMITSOME,DENYSOME=list(range(1,5))
 
 DUMMY_CHECKSUM = -559038737 # 0xdeadbeef
 
@@ -80,7 +80,7 @@
     key="Tic/Toc"
     ro="0x"
     i=0
-    ascii=map(ord,pw)
+    ascii=list(map(ord,pw))
     for c in ascii:
         ro=ro+'%02x'%(c^ord(key[i%len(key)]))
         i=i+1
@@ -168,8 +168,8 @@
     def connectionMade(self):
         # initialization of protocol
         self._buf=""
-        self._ourseqnum=0L
-        self._theirseqnum=0L
+        self._ourseqnum=0
+        self._theirseqnum=0
         self._mode="Flapon"
         self._onlyflaps=0
         self._laststatus={} # the last status for a user
@@ -194,7 +194,7 @@
             del self.factory.users[self.username]
         except:
             pass
-        for k in self.factory.chatroom.keys():
+        for k in list(self.factory.chatroom.keys()):
             try:
                 self.factory.chatroom[k].leave(self)
             except TOCParseError:
@@ -215,7 +215,7 @@
         send=send+struct.pack("!BHH",type,self._ourseqnum,length)
         send=send+data
         self._ourseqnum=self._ourseqnum+1
-        if self._ourseqnum>(256L**4):
+        if self._ourseqnum>(256**4):
             self._ourseqnum=0
         self.transport.write(send)
 
@@ -236,7 +236,7 @@
         if self._buf[0]!="*": return 0
         if len(self._buf)<6: return 0
         foo,type,seqnum,length=struct.unpack("!BBHH",self._buf[:6])
-        if type not in range(1,6): return 0
+        if type not in list(range(1,6)): return 0
         if len(self._buf)<6+length: return 0
         return 1
 
@@ -293,7 +293,7 @@
         if version!=1 or tlv!=1 or unlength+8!=len(flap[1]):
             raise TOCParseError
         self.username=normalize(flap[1][8:])
-        if self.username in self.factory.savedusers.keys():
+        if self.username in list(self.factory.savedusers.keys()):
             self.saved=self.factory.savedusers[self.username]
         else:
             self.saved=SavedUser()
@@ -370,7 +370,7 @@
             self.permitmode=PERMITSOME
             self.denylist=[]
             users=string.split(data," ")
-            map(self.permitlist.append,users)
+            list(map(self.permitlist.append,users))
         self.updateUsers()
 
     def toc_add_deny(self,data):
@@ -385,7 +385,7 @@
             self.permitmode=DENYSOME
             self.permitlist=[]
             users=string.split(data," ")
-            map(self.denylist.append,users)
+            list(map(self.denylist.append,users))
         self.updateUsers()
 
     def toc_evil(self,data):
@@ -399,7 +399,7 @@
             user=""
         else:
             user=self.saved.nick
-        if not(self.factory.users.has_key(username)):
+        if not(username in self.factory.users):
             self.sendError(CANT_WARN,username)
             return
         if self.factory.users[username].saved.evilness>=100:
@@ -413,7 +413,7 @@
 
         toc_add_buddy <buddyname1> [<buddyname2>] [<buddyname3>]...
         """
-        buddies=map(normalize,string.split(data," "))
+        buddies=list(map(normalize,string.split(data," ")))
         for b in buddies:
             if b not in self.buddylist:
                 self.buddylist.append(b)
@@ -449,7 +449,7 @@
             auto=1
             data=data[:-5]
         data=unquote(data)
-        if not(self.factory.users.has_key(username)):
+        if not(username in self.factory.users):
             self.sendError(NOT_AVAILABLE,username)
             return
         user=self.factory.users[username]
@@ -569,7 +569,7 @@
 
         toc_get_info <username>
         """
-        if not self.factory.users.has_key(data):
+        if data not in self.factory.users:
             self.sendError(901,data)
             return
         self.sendFlap(2,"GOTO_URL:TIC:info/%s"%data)
@@ -611,13 +611,13 @@
         Update the users who have us on their buddylist.
         Called when the user changes anything (idle,away) so people can get updates.
         """
-        for user in self.factory.users.values():
+        for user in list(self.factory.users.values()):
             if self.username in user.buddylist and self.canContact(user):
                 user.buddyUpdate(self)
 
     def getStatus(self,user):
         if self.canContact(user):
-            if self in self.factory.users.values():ol='T'
+            if self in list(self.factory.users.values()):ol='T'
             else: ol='F'
             idle=0
             if self.idletime:
@@ -644,7 +644,7 @@
         """
         if not self.canContact(user): return
         status=user.getStatus(self)
-        if not self._laststatus.has_key(user):
+        if user not in self._laststatus:
             self._laststatus[user]=()
         if self._laststatus[user]!=status:
             send="UPDATE_BUDDY:%s:%s:%s:%s:%s:%s"%status
@@ -752,7 +752,7 @@
         return p
 
     def getChatroom(self,exchange,name):
-        for i in self.chatroom.values():
+        for i in list(self.chatroom.values()):
             if normalize(i.name)==normalize(name):
                 return i
         self.chatroom[self.chatroomid]=Chatroom(self,exchange,name,self.chatroomid)
@@ -823,7 +823,7 @@
         if self._buf[0]!="*": return 0
         if len(self._buf)<6: return 0
         foo,type,seqnum,length=struct.unpack("!BBHH",self._buf[:6])
-        if type not in range(1,6): return 0
+        if type not in list(range(1,6)): return 0
         if len(self._buf)<6+length: return 0
         return 1
 
@@ -871,7 +871,7 @@
             self._debug("bad SNAC:%s"%(flap[1]))
             return
         command,rest=string.split(flap[1],":",1)
-        if MAXARGS.has_key(command):
+        if command in MAXARGS:
             maxsplit=MAXARGS[command]
         else:
             maxsplit=-1
@@ -1071,7 +1071,7 @@
         func(user,cookie,seq,pip,vip,port,tlvs)
 
     def tocSEND_FILE(self,user,cookie,seq,pip,vip,port,tlvs):
-        if tlvs.has_key('12'):
+        if '12' in tlvs:
             description=tlvs['12']
         else:
             description=""
@@ -1233,7 +1233,7 @@
         deny := deny list
         """
         s="m %s\n"%mode
-        for g in buddylist.keys():
+        for g in list(buddylist.keys()):
             s=s+"g %s\n"%g
             for u in buddylist[g]:
                 s=s+"b %s\n"%u
@@ -1442,7 +1442,7 @@
             self.hdr[3]=self.cookie
             self.hdr[4]=0
             self.hdr[5]=0
-            self.transport.write(apply(struct.pack,[self.header_fmt]+self.hdr))
+            self.transport.write(struct.pack(*[self.header_fmt]+self.hdr))
             data=data[256:]
             if self.hdr[6]==1:
                 self.name=self.filename
@@ -1460,7 +1460,7 @@
             self.hdr[19]=DUMMY_CHECKSUM # XXX really calculate this
             self.hdr[18]=self.hdr[18]+1
             self.hdr[21]="\000"
-            self.transport.write(apply(struct.pack,[self.header_fmt]+self.hdr))
+            self.transport.write(struct.pack(*[self.header_fmt]+self.hdr))
             self.sofar=0
             if self.hdr[7]==0:
                 self.transport.loseConnection()
@@ -1493,7 +1493,7 @@
              len(self.listing),os.path.getmtime(self.dir),
              checksum(self.listing),0,0,0,0,0,0,"OFT_Windows ICBMFT V1.1 32",
              "\002",chr(0x1a),chr(0x10),"","",0,0,""]
-        self.transport.write(apply(struct.pack,[self.header_fmt]+hdr))
+        self.transport.write(struct.pack(*[self.header_fmt]+hdr))
 
     def dataReceived(self,data):
         self.buf=self.buf+data
@@ -1501,7 +1501,7 @@
             hdr=list(struct.unpack(self.header_fmt,self.buf[:256]))
             self.buf=self.buf[256:]
             if hdr[2]==0x1209:
-                self.file=StringIO.StringIO(self.listing)
+                self.file=io.StringIO(self.listing)
                 self.transport.registerProducer(self,0)
             elif hdr[2]==0x120b: pass
             elif hdr[2]==0x120c: # file request
@@ -1518,7 +1518,7 @@
                 self.file.seek(0)
                 hdr[18]=hdr[19]=0
                 hdr[21]=chr(0x20)
-                self.transport.write(apply(struct.pack,[self.header_fmt]+hdr))
+                self.transport.write(struct.pack(*[self.header_fmt]+hdr))
                 log.msg("got file request for %s"%file,hex(hdr[13]))
             elif hdr[2]==0x0202:
                 log.msg("sending file")
@@ -1535,7 +1535,7 @@
                 log.msg("restarting at %s"%already)
                 hdr[2]=0x0106
                 hdr[19]=checksum(data)
-                self.transport.write(apply(struct.pack,[self.header_fmt]+hdr))
+                self.transport.write(struct.pack(*[self.header_fmt]+hdr))
             elif hdr[2]==0x0207:
                 self.transport.registerProducer(self,0)
             else:
--- twisted/words/protocols/jabber/client.py (original)
+++ twisted/words/protocols/jabber/client.py (refactored)
@@ -259,7 +259,7 @@
 
     def onBind(self, iq):
         if iq.bind:
-            self.xmlstream.authenticator.jid = JID(unicode(iq.bind.jid))
+            self.xmlstream.authenticator.jid = JID(str(iq.bind.jid))
 
 
 
--- twisted/words/protocols/jabber/component.py (original)
+++ twisted/words/protocols/jabber/component.py (refactored)
@@ -167,7 +167,7 @@
         L{onHandshake}.
         """
         if (element.uri, element.name) == (self.namespace, 'handshake'):
-            self.onHandshake(unicode(element))
+            self.onHandshake(str(element))
         else:
             exc = error.StreamError('not-authorized')
             self.xmlstream.sendStreamError(exc)
--- twisted/words/protocols/jabber/error.py (original)
+++ twisted/words/protocols/jabber/error.py (refactored)
@@ -231,8 +231,8 @@
 
 def _getText(element):
     for child in element.children:
-        if isinstance(child, basestring):
-            return unicode(child)
+        if isinstance(child, str):
+            return str(child)
 
     return None
 
--- twisted/words/protocols/jabber/jid.py (original)
+++ twisted/words/protocols/jabber/jid.py (refactored)
@@ -80,25 +80,25 @@
 
     if user:
         try:
-            user = nodeprep.prepare(unicode(user))
+            user = nodeprep.prepare(str(user))
         except UnicodeError:
-            raise InvalidFormat, "Invalid character in username"
+            raise InvalidFormat("Invalid character in username")
     else:
         user = None
 
     if not host:
-        raise InvalidFormat, "Server address required."
+        raise InvalidFormat("Server address required.")
     else:
         try:
-            host = nameprep.prepare(unicode(host))
+            host = nameprep.prepare(str(host))
         except UnicodeError:
-            raise InvalidFormat, "Invalid character in hostname"
+            raise InvalidFormat("Invalid character in hostname")
 
     if resource:
         try:
-            resource = resourceprep.prepare(unicode(resource))
+            resource = resourceprep.prepare(str(resource))
         except UnicodeError:
-            raise InvalidFormat, "Invalid character in resource"
+            raise InvalidFormat("Invalid character in resource")
     else:
         resource = None
 
@@ -152,7 +152,7 @@
         @rtype: C{unicode}
         """
         if self.user:
-            return u"%s@%s" % (self.user, self.host)
+            return "%s@%s" % (self.user, self.host)
         else:
             return self.host
 
@@ -182,12 +182,12 @@
         """
         if self.user:
             if self.resource:
-                return u"%s@%s/%s" % (self.user, self.host, self.resource)
+                return "%s@%s/%s" % (self.user, self.host, self.resource)
             else:
-                return u"%s@%s" % (self.user, self.host)
+                return "%s@%s" % (self.user, self.host)
         else:
             if self.resource:
-                return u"%s/%s" % (self.host, self.resource)
+                return "%s/%s" % (self.host, self.resource)
             else:
                 return self.host
 
--- twisted/words/protocols/jabber/sasl.py (original)
+++ twisted/words/protocols/jabber/sasl.py (refactored)
@@ -99,7 +99,7 @@
 
     try:
         return b64decode(s)
-    except Exception, e:
+    except Exception as e:
         raise SASLIncorrectEncodingError(str(e))
 
 class SASLInitiatingInitializer(xmlstream.BaseFeatureInitiatingInitializer):
--- twisted/words/protocols/jabber/sasl_mechanisms.py (original)
+++ twisted/words/protocols/jabber/sasl_mechanisms.py (refactored)
@@ -158,7 +158,7 @@
         """
 
         directive_list = []
-        for name, value in directives.iteritems():
+        for name, value in directives.items():
             if name in ('username', 'realm', 'cnonce',
                         'nonce', 'digest-uri', 'authzid', 'cipher'):
                 directive = '%s="%s"' % (name, value)
--- twisted/words/protocols/jabber/xmlstream.py (original)
+++ twisted/words/protocols/jabber/xmlstream.py (refactored)
@@ -30,8 +30,8 @@
 if ssl and not ssl.supported:
     ssl = None
 
-STREAM_AUTHD_EVENT = intern("//event/stream/authd")
-INIT_FAILED_EVENT = intern("//event/xmpp/initfailed")
+STREAM_AUTHD_EVENT = sys.intern("//event/stream/authd")
+INIT_FAILED_EVENT = sys.intern("//event/xmpp/initfailed")
 
 NS_STREAMS = 'http://etherx.jabber.org/streams'
 NS_XMPP_TLS = 'urn:ietf:params:xml:ns:xmpp-tls'
@@ -266,7 +266,7 @@
             self.xmlstream.thisEntity = jid.internJID(rootElement["to"])
 
         self.xmlstream.prefixes = {}
-        for prefix, uri in rootElement.localPrefixes.iteritems():
+        for prefix, uri in rootElement.localPrefixes.items():
             self.xmlstream.prefixes[uri] = prefix
 
         self.xmlstream.sid = randbytes.secureRandom(8).encode('hex')
@@ -527,7 +527,7 @@
         """
         # set up optional extra namespaces
         localPrefixes = {}
-        for uri, prefix in self.prefixes.iteritems():
+        for uri, prefix in self.prefixes.items():
             if uri != NS_STREAMS:
                 localPrefixes[prefix] = uri
 
@@ -592,7 +592,7 @@
         if domish.IElement.providedBy(obj):
             obj = obj.toXml(prefixes=self.prefixes,
                             defaultUri=self.namespace,
-                            prefixesInScope=self.prefixes.values())
+                            prefixesInScope=list(self.prefixes.values()))
 
         xmlstream.XmlStream.send(self, obj)
 
@@ -735,7 +735,7 @@
         """
         iqDeferreds = xs.iqDeferreds
         xs.iqDeferreds = {}
-        for d in iqDeferreds.itervalues():
+        for d in iqDeferreds.values():
             d.errback(ConnectionLost())
 
     xs.iqDeferreds = {}
--- twisted/words/protocols/jabber/xmpp_stringprep.py (original)
+++ twisted/words/protocols/jabber/xmpp_stringprep.py (refactored)
@@ -10,7 +10,7 @@
     import re
 
     class IDNA:
-        dots = re.compile(u"[\u002E\u3002\uFF0E\uFF61]")
+        dots = re.compile("[\u002E\u3002\uFF0E\uFF61]")
         def nameprep(self, label):
             return label.lower()
 
@@ -116,18 +116,18 @@
             if result_c is not None:
                 result.append(result_c)
 
-        return u"".join(result)
+        return "".join(result)
 
     def check_prohibiteds(self, string):
         for c in string:
             for table in self.prohibiteds:
                 if table.lookup(c):
-                    raise UnicodeError, "Invalid character %s" % repr(c)
+                    raise UnicodeError("Invalid character %s" % repr(c))
 
     def check_unassigneds(self, string):
         for c in string:
             if stringprep.in_table_a1(c):
-                raise UnicodeError, "Unassigned code point %s" % repr(c)
+                raise UnicodeError("Unassigned code point %s" % repr(c))
     
     def check_bidirectionals(self, string):
         found_LCat = False
@@ -140,11 +140,11 @@
                 found_LCat = True
 
         if found_LCat and found_RandALCat:
-            raise UnicodeError, "Violation of BIDI Requirement 2"
+            raise UnicodeError("Violation of BIDI Requirement 2")
 
         if found_RandALCat and not (stringprep.in_table_d1(string[0]) and
                                     stringprep.in_table_d1(string[-1])):
-            raise UnicodeError, "Violation of BIDI Requirement 3"
+            raise UnicodeError("Violation of BIDI Requirement 3")
 
 
 class NamePrep:
@@ -170,11 +170,11 @@
     """
 
     # Prohibited characters.
-    prohibiteds = [unichr(n) for n in range(0x00, 0x2c + 1) +
-                                       range(0x2e, 0x2f + 1) +
-                                       range(0x3a, 0x40 + 1) +
-                                       range(0x5b, 0x60 + 1) +
-                                       range(0x7b, 0x7f + 1) ]
+    prohibiteds = [chr(n) for n in list(range(0x00, 0x2c + 1)) +
+                                       list(range(0x2e, 0x2f + 1)) +
+                                       list(range(0x3a, 0x40 + 1)) +
+                                       list(range(0x5b, 0x60 + 1)) +
+                                       list(range(0x7b, 0x7f + 1)) ]
 
     def prepare(self, string):
         result = []
@@ -195,23 +195,23 @@
     def check_prohibiteds(self, string):
         for c in string:
            if c in self.prohibiteds:
-               raise UnicodeError, "Invalid character %s" % repr(c)
+               raise UnicodeError("Invalid character %s" % repr(c))
 
     def nameprep(self, label):
         label = idna.nameprep(label)
         self.check_prohibiteds(label)
         if label[0] == '-':
-            raise UnicodeError, "Invalid leading hyphen-minus"
+            raise UnicodeError("Invalid leading hyphen-minus")
         if label[-1] == '-':
-            raise UnicodeError, "Invalid trailing hyphen-minus"
+            raise UnicodeError("Invalid trailing hyphen-minus")
         return label
 
 if crippled:
     case_map = MappingTableFromFunction(lambda c: c.lower())
     nodeprep = Profile(mappings=[case_map],
                        normalize=False,
-                       prohibiteds=[LookupTable([u' ', u'"', u'&', u"'", u'/',
-                                                 u':', u'<', u'>', u'@'])],
+                       prohibiteds=[LookupTable([' ', '"', '&', "'", '/',
+                                                 ':', '<', '>', '@'])],
                        check_unassigneds=False,
                        check_bidi=False)
 
@@ -238,8 +238,8 @@
     nodeprep = Profile(mappings=[B_1, B_2],
                        prohibiteds=[C_11, C_12, C_21, C_22,
                                     C_3, C_4, C_5, C_6, C_7, C_8, C_9,
-                                    LookupTable([u'"', u'&', u"'", u'/',
-                                                 u':', u'<', u'>', u'@'])])
+                                    LookupTable(['"', '&', "'", '/',
+                                                 ':', '<', '>', '@'])])
 
     resourceprep = Profile(mappings=[B_1,],
                            prohibiteds=[C_12, C_21, C_22,
--- twisted/words/test/test_domish.py (original)
+++ twisted/words/test/test_domish.py (refactored)
@@ -82,11 +82,11 @@
         Calling C{elements} without arguments on a L{domish.Element} returns
         all child elements, whatever the qualfied name.
         """
-        e = domish.Element((u"testns", u"foo"))
-        c1 = e.addElement(u"name")
-        c2 = e.addElement((u"testns2", u"baz"))
-        c3 = e.addElement(u"quux")
-        c4 = e.addElement((u"testns", u"name"))
+        e = domish.Element(("testns", "foo"))
+        c1 = e.addElement("name")
+        c2 = e.addElement(("testns2", "baz"))
+        c3 = e.addElement("quux")
+        c4 = e.addElement(("testns", "name"))
 
         elts = list(e.elements())
 
@@ -101,13 +101,13 @@
         Calling C{elements} with a namespace and local name on a
         L{domish.Element} returns all child elements with that qualified name.
         """
-        e = domish.Element((u"testns", u"foo"))
-        c1 = e.addElement(u"name")
-        c2 = e.addElement((u"testns2", u"baz"))
-        c3 = e.addElement(u"quux")
-        c4 = e.addElement((u"testns", u"name"))
-
-        elts = list(e.elements(u"testns", u"name"))
+        e = domish.Element(("testns", "foo"))
+        c1 = e.addElement("name")
+        c2 = e.addElement(("testns2", "baz"))
+        c3 = e.addElement("quux")
+        c4 = e.addElement(("testns", "name"))
+
+        elts = list(e.elements("testns", "name"))
 
         self.assertIn(c1, elts)
         self.assertNotIn(c2, elts)
@@ -167,7 +167,7 @@
         self.assertEquals(self.elements[0].uri, 'jabber')
         self.assertEquals(self.elements[0]['to'], 'bar')
         self.assertEquals(self.elements[0].x.uri, 'xdelay')
-        self.assertEquals(unicode(self.elements[0].x), 'some&data>')
+        self.assertEquals(str(self.elements[0].x), 'some&data>')
 
     def testNoRootNS(self):
         xml = "<stream><error xmlns='etherx'/></stream>"
@@ -410,12 +410,12 @@
 
     def testRawXMLWithUnicodeSerialization(self):
         e = domish.Element((None, "foo"))
-        e.addRawXml(u"<degree>\u00B0</degree>")
-        self.assertEquals(e.toXml(), u"<foo><degree>\u00B0</degree></foo>")
+        e.addRawXml("<degree>\u00B0</degree>")
+        self.assertEquals(e.toXml(), "<foo><degree>\u00B0</degree></foo>")
 
     def testUnicodeSerialization(self):
         e = domish.Element((None, "foo"))
-        e["test"] = u"my value\u0221e"
-        e.addContent(u"A degree symbol...\u00B0")
+        e["test"] = "my value\u0221e"
+        e.addContent("A degree symbol...\u00B0")
         self.assertEquals(e.toXml(),
-                          u"<foo test='my value\u0221e'>A degree symbol...\u00B0</foo>")
+                          "<foo test='my value\u0221e'>A degree symbol...\u00B0</foo>")
--- twisted/words/test/test_irc.py (original)
+++ twisted/words/test/test_irc.py (refactored)
@@ -5,7 +5,7 @@
 Tests for L{twisted.words.protocols.irc}.
 """
 
-from StringIO import StringIO
+from io import StringIO
 import time
 
 from twisted.trial import unittest
--- twisted/words/test/test_jabberclient.py (original)
+++ twisted/words/test/test_jabberclient.py (refactored)
@@ -82,9 +82,9 @@
         self.assertEquals('set', iq['type'])
         self.assertEquals(('jabber:iq:auth', 'query'),
                           (iq.children[0].uri, iq.children[0].name))
-        self.assertEquals('user', unicode(iq.query.username))
-        self.assertEquals('secret', unicode(iq.query.password))
-        self.assertEquals('resource', unicode(iq.query.resource))
+        self.assertEquals('user', str(iq.query.username))
+        self.assertEquals('secret', str(iq.query.password))
+        self.assertEquals('resource', str(iq.query.resource))
 
         # Send server response
         self.xmlstream.dataReceived("<iq type='result' id='%s'/>" % iq['id'])
@@ -116,10 +116,10 @@
         self.assertEquals('set', iq['type'])
         self.assertEquals(('jabber:iq:auth', 'query'),
                           (iq.children[0].uri, iq.children[0].name))
-        self.assertEquals('user', unicode(iq.query.username))
+        self.assertEquals('user', str(iq.query.username))
         self.assertEquals(sha1('12345secret').hexdigest(),
-                          unicode(iq.query.digest))
-        self.assertEquals('resource', unicode(iq.query.resource))
+                          str(iq.query.digest))
+        self.assertEquals('resource', str(iq.query.resource))
 
         # Send server response
         self.xmlstream.dataReceived("<iq type='result' id='%s'/>" % iq['id'])
--- twisted/words/test/test_jabbercomponent.py (original)
+++ twisted/words/test/test_jabbercomponent.py (refactored)
@@ -50,7 +50,7 @@
         self.assertEquals('handshake', handshake.name)
         self.assertEquals('test:component', handshake.uri)
         self.assertEquals(sha1("%s%s" % ('12345', 'secret')).hexdigest(),
-                          unicode(handshake))
+                          str(handshake))
 
         # successful authentication
 
--- twisted/words/test/test_jabbererror.py (original)
+++ twisted/words/test/test_jabbererror.py (refactored)
@@ -33,7 +33,7 @@
         e = error.BaseError('feature-not-implemented', 'text')
         element = e.getElement()
         self.assertEquals(len(element.children), 2)
-        self.assertEquals(unicode(element.text), 'text')
+        self.assertEquals(str(element.text), 'text')
         self.assertEquals(element.text.getAttribute((NS_XML, 'lang')), None)
 
     def test_getElementTextLang(self):
@@ -43,7 +43,7 @@
         e = error.BaseError('feature-not-implemented', 'text', 'en_US')
         element = e.getElement()
         self.assertEquals(len(element.children), 2)
-        self.assertEquals(unicode(element.text), 'text')
+        self.assertEquals(str(element.text), 'text')
         self.assertEquals(element.text[(NS_XML, 'lang')], 'en_US')
 
     def test_getElementAppCondition(self):
--- twisted/words/test/test_jabberjid.py (original)
+++ twisted/words/test/test_jabberjid.py (refactored)
@@ -206,7 +206,7 @@
         Test unicode representation of JIDs.
         """
         j = jid.JID(tuple=('user', 'host', 'resource'))
-        self.assertEquals("user@host/resource", unicode(j))
+        self.assertEquals("user@host/resource", str(j))
 
     def test_repr(self):
         """
--- twisted/words/test/test_jabberxmppstringprep.py (original)
+++ twisted/words/test/test_jabberxmppstringprep.py (refactored)
@@ -23,62 +23,62 @@
     """
 
     def testResourcePrep(self):
-        self.assertEquals(resourceprep.prepare(u'resource'), u'resource')
-        self.assertNotEquals(resourceprep.prepare(u'Resource'), u'resource')
-        self.assertEquals(resourceprep.prepare(u' '), u' ')
+        self.assertEquals(resourceprep.prepare('resource'), 'resource')
+        self.assertNotEquals(resourceprep.prepare('Resource'), 'resource')
+        self.assertEquals(resourceprep.prepare(' '), ' ')
 
         if crippled:
             return
 
-        self.assertEquals(resourceprep.prepare(u'Henry \u2163'), u'Henry IV')
-        self.assertEquals(resourceprep.prepare(u'foo\xad\u034f\u1806\u180b'
-                                               u'bar\u200b\u2060'
-                                               u'baz\ufe00\ufe08\ufe0f\ufeff'),
-                          u'foobarbaz')
-        self.assertEquals(resourceprep.prepare(u'\u00a0'), u' ')
-        self.assertRaises(UnicodeError, resourceprep.prepare, u'\u1680')
-        self.assertEquals(resourceprep.prepare(u'\u2000'), u' ')
-        self.assertEquals(resourceprep.prepare(u'\u200b'), u'')
-        self.assertRaises(UnicodeError, resourceprep.prepare, u'\u0010\u007f')
-        self.assertRaises(UnicodeError, resourceprep.prepare, u'\u0085')
-        self.assertRaises(UnicodeError, resourceprep.prepare, u'\u180e')
-        self.assertEquals(resourceprep.prepare(u'\ufeff'), u'')
-        self.assertRaises(UnicodeError, resourceprep.prepare, u'\uf123')
-        self.assertRaises(UnicodeError, resourceprep.prepare, u'\U000f1234')
-        self.assertRaises(UnicodeError, resourceprep.prepare, u'\U0010f234')
-        self.assertRaises(UnicodeError, resourceprep.prepare, u'\U0008fffe')
-        self.assertRaises(UnicodeError, resourceprep.prepare, u'\U0010ffff')
-        self.assertRaises(UnicodeError, resourceprep.prepare, u'\udf42')
-        self.assertRaises(UnicodeError, resourceprep.prepare, u'\ufffd')
-        self.assertRaises(UnicodeError, resourceprep.prepare, u'\u2ff5')
-        self.assertEquals(resourceprep.prepare(u'\u0341'), u'\u0301')
-        self.assertRaises(UnicodeError, resourceprep.prepare, u'\u200e')
-        self.assertRaises(UnicodeError, resourceprep.prepare, u'\u202a')
-        self.assertRaises(UnicodeError, resourceprep.prepare, u'\U000e0001')
-        self.assertRaises(UnicodeError, resourceprep.prepare, u'\U000e0042')
-        self.assertRaises(UnicodeError, resourceprep.prepare, u'foo\u05bebar')
-        self.assertRaises(UnicodeError, resourceprep.prepare, u'foo\ufd50bar')
+        self.assertEquals(resourceprep.prepare('Henry \u2163'), 'Henry IV')
+        self.assertEquals(resourceprep.prepare('foo\xad\u034f\u1806\u180b'
+                                               'bar\u200b\u2060'
+                                               'baz\ufe00\ufe08\ufe0f\ufeff'),
+                          'foobarbaz')
+        self.assertEquals(resourceprep.prepare('\u00a0'), ' ')
+        self.assertRaises(UnicodeError, resourceprep.prepare, '\u1680')
+        self.assertEquals(resourceprep.prepare('\u2000'), ' ')
+        self.assertEquals(resourceprep.prepare('\u200b'), '')
+        self.assertRaises(UnicodeError, resourceprep.prepare, '\u0010\u007f')
+        self.assertRaises(UnicodeError, resourceprep.prepare, '\u0085')
+        self.assertRaises(UnicodeError, resourceprep.prepare, '\u180e')
+        self.assertEquals(resourceprep.prepare('\ufeff'), '')
+        self.assertRaises(UnicodeError, resourceprep.prepare, '\uf123')
+        self.assertRaises(UnicodeError, resourceprep.prepare, '\U000f1234')
+        self.assertRaises(UnicodeError, resourceprep.prepare, '\U0010f234')
+        self.assertRaises(UnicodeError, resourceprep.prepare, '\U0008fffe')
+        self.assertRaises(UnicodeError, resourceprep.prepare, '\U0010ffff')
+        self.assertRaises(UnicodeError, resourceprep.prepare, '\udf42')
+        self.assertRaises(UnicodeError, resourceprep.prepare, '\ufffd')
+        self.assertRaises(UnicodeError, resourceprep.prepare, '\u2ff5')
+        self.assertEquals(resourceprep.prepare('\u0341'), '\u0301')
+        self.assertRaises(UnicodeError, resourceprep.prepare, '\u200e')
+        self.assertRaises(UnicodeError, resourceprep.prepare, '\u202a')
+        self.assertRaises(UnicodeError, resourceprep.prepare, '\U000e0001')
+        self.assertRaises(UnicodeError, resourceprep.prepare, '\U000e0042')
+        self.assertRaises(UnicodeError, resourceprep.prepare, 'foo\u05bebar')
+        self.assertRaises(UnicodeError, resourceprep.prepare, 'foo\ufd50bar')
         #self.assertEquals(resourceprep.prepare(u'foo\ufb38bar'),
         #                  u'foo\u064ebar')
-        self.assertRaises(UnicodeError, resourceprep.prepare, u'\u06271')
-        self.assertEquals(resourceprep.prepare(u'\u06271\u0628'),
-                          u'\u06271\u0628')
-        self.assertRaises(UnicodeError, resourceprep.prepare, u'\U000e0002')
+        self.assertRaises(UnicodeError, resourceprep.prepare, '\u06271')
+        self.assertEquals(resourceprep.prepare('\u06271\u0628'),
+                          '\u06271\u0628')
+        self.assertRaises(UnicodeError, resourceprep.prepare, '\U000e0002')
 
     def testNodePrep(self):
-        self.assertEquals(nodeprep.prepare(u'user'), u'user')
-        self.assertEquals(nodeprep.prepare(u'User'), u'user')
-        self.assertRaises(UnicodeError, nodeprep.prepare, u'us&er')
+        self.assertEquals(nodeprep.prepare('user'), 'user')
+        self.assertEquals(nodeprep.prepare('User'), 'user')
+        self.assertRaises(UnicodeError, nodeprep.prepare, 'us&er')
 
     def testNamePrep(self):
-        self.assertEquals(nameprep.prepare(u'example.com'), u'example.com')
-        self.assertEquals(nameprep.prepare(u'Example.com'), u'example.com')
-        self.assertRaises(UnicodeError, nameprep.prepare, u'ex@mple.com')
-        self.assertRaises(UnicodeError, nameprep.prepare, u'-example.com')
-        self.assertRaises(UnicodeError, nameprep.prepare, u'example-.com')
+        self.assertEquals(nameprep.prepare('example.com'), 'example.com')
+        self.assertEquals(nameprep.prepare('Example.com'), 'example.com')
+        self.assertRaises(UnicodeError, nameprep.prepare, 'ex@mple.com')
+        self.assertRaises(UnicodeError, nameprep.prepare, '-example.com')
+        self.assertRaises(UnicodeError, nameprep.prepare, 'example-.com')
 
         if crippled:
             return
 
-        self.assertEquals(nameprep.prepare(u'stra\u00dfe.example.com'),
-                          u'strasse.example.com')
+        self.assertEquals(nameprep.prepare('stra\u00dfe.example.com'),
+                          'strasse.example.com')
--- twisted/words/test/test_msn.py (original)
+++ twisted/words/test/test_msn.py (refactored)
@@ -6,7 +6,7 @@
 """
 
 # System imports
-import StringIO
+import io
 
 # Twisted imports
 
@@ -30,9 +30,9 @@
 from twisted.trial import unittest
 
 def printError(f):
-    print f
-
-class StringIOWithoutClosing(StringIO.StringIO):
+    print(f)
+
+class StringIOWithoutClosing(io.StringIO):
     disconnecting = 0
     def close(self): pass
     def loseConnection(self): pass
@@ -55,7 +55,7 @@
         transport = StringIOWithoutClosing()
         protocol.makeConnection(transport)
         protocol.dataReceived('HTTP/1.0 200 OK\r\n')
-        for (h,v) in headers.items(): protocol.dataReceived('%s: %s\r\n' % (h,v))
+        for (h,v) in list(headers.items()): protocol.dataReceived('%s: %s\r\n' % (h,v))
         protocol.dataReceived('\r\n')
         self.failUnless(self.result[0] == "https://login.myserver.com/")
 
@@ -63,7 +63,7 @@
         protocol = msn.PassportLogin(self.deferred,'foo@foo.com','testpass','https://foo.com/', 'a')
         protocol.makeConnection(StringIOWithoutClosing())
         protocol.dataReceived(response)
-        for (h,v) in headers.items(): protocol.dataReceived('%s: %s\r\n' % (h,v))
+        for (h,v) in list(headers.items()): protocol.dataReceived('%s: %s\r\n' % (h,v))
         protocol.dataReceived('\r\n')
 
     def testPassportLoginSuccess(self):
@@ -290,7 +290,7 @@
         m += 'LoginTime: 1016941010\r\nEmailEnabled: 1\r\nMemberIdHigh: 40000\r\nMemberIdLow: -600000000\r\nlang_preference: 1033\r\n'
         m += 'preferredEmail: foo@bar.com\r\ncountry: AU\r\nPostalCode: 90210\r\nGender: M\r\nKid: 0\r\nAge:\r\nsid: 400\r\n'
         m += 'kv: 2\r\nMSPAuth: 2CACCBCCADMoV8ORoz64BVwmjtksIg!kmR!Rj5tBBqEaW9hc4YnPHSOQ$$\r\n\r\n'
-        map(self.client.lineReceived, m.split('\r\n')[:-1])
+        list(map(self.client.lineReceived, m.split('\r\n')[:-1]))
         self.failUnless((self.client.state == 'PROFILE'), msg='Failed to detect initial profile')
 
     def testStatus(self):
@@ -316,7 +316,7 @@
             "LSG 0 Other%20Contacts 0",
             "LST userHandle@email.com Some%20Name 11 0"
         ]
-        map(self.client.lineReceived, lines)
+        list(map(self.client.lineReceived, lines))
         contacts = self.client.factory.contacts
         contact = contacts.getContact('userHandle@email.com')
         self.failUnless(contacts.version == 100, "Invalid contact list version")
@@ -352,7 +352,7 @@
             "LST userHandle@email.com Some%20Name 11 0",
             "BPR PHH 123%20456"
         ]
-        map(self.client.lineReceived, lines)
+        list(map(self.client.lineReceived, lines))
         contact = self.client.factory.contacts.getContact('userHandle@email.com')
         self.failUnless(contact.homePhone == '123 456', "Did not update contact's phone number")
 
@@ -449,10 +449,12 @@
         self.client.checkMessage(m)
         self.failUnless((self.client.state == 'INFO'), msg='Failed to detect file transfer info')
 
-    def fileResponse(self, (accept, cookie, info)):
+    def fileResponse(self, xxx_todo_changeme):
+        (accept, cookie, info) = xxx_todo_changeme
         if accept and cookie == 1234: self.client.state = 'RESPONSE'
 
-    def fileInfo(self, (accept, ip, port, aCookie, info)):
+    def fileInfo(self, xxx_todo_changeme1):
+        (accept, ip, port, aCookie, info) = xxx_todo_changeme1
         if accept and ip == '192.168.0.1' and port == 6891 and aCookie == 4321: self.client.state = 'INFO'
 
 
--- twisted/words/test/test_service.py (original)
+++ twisted/words/test/test_service.py (refactored)
@@ -23,7 +23,7 @@
         # Kind is "user" or "group"
         realm = service.InMemoryWordsRealm("realmname")
 
-        name = u'test' + kind.lower()
+        name = 'test' + kind.lower()
         create = getattr(realm, 'create' + kind.title())
         get = getattr(realm, 'get' + kind.title())
         flag = 'create' + kind.title() + 'OnRequest'
@@ -43,20 +43,20 @@
 
         # Getting a non-existent user should succeed if createUserOnRequest is True
         setattr(realm, flag, True)
-        d = wFD(get(u"new" + kind.lower()))
+        d = wFD(get("new" + kind.lower()))
         yield d
         p = d.getResult()
         self.assertEquals(p.name, "new" + kind.lower())
 
         # Getting that user again should return the same object
-        d = wFD(get(u"new" + kind.lower()))
+        d = wFD(get("new" + kind.lower()))
         yield d
         newp = d.getResult()
         self.assertIdentical(p, newp)
 
         # Getting a non-existent user should fail if createUserOnRequest is False
         setattr(realm, flag, False)
-        d = wFD(get(u"another" + kind.lower()))
+        d = wFD(get("another" + kind.lower()))
         yield d
         self.assertRaises(noSuchExc, d.getResult)
     _entityCreationTest = dG(_entityCreationTest)
@@ -74,24 +74,24 @@
         realm = service.InMemoryWordsRealm("realmname")
 
         # Make a user to play around with
-        d = wFD(realm.createUser(u"testuser"))
+        d = wFD(realm.createUser("testuser"))
         yield d
         user = d.getResult()
 
         # Make sure getting the user returns the same object
-        d = wFD(realm.getUser(u"testuser"))
+        d = wFD(realm.getUser("testuser"))
         yield d
         retrieved = d.getResult()
         self.assertIdentical(user, retrieved)
 
         # Make sure looking up the user also returns the same object
-        d = wFD(realm.lookupUser(u"testuser"))
+        d = wFD(realm.lookupUser("testuser"))
         yield d
         lookedUp = d.getResult()
         self.assertIdentical(retrieved, lookedUp)
 
         # Make sure looking up a user who does not exist fails
-        d = wFD(realm.lookupUser(u"nosuchuser"))
+        d = wFD(realm.lookupUser("nosuchuser"))
         yield d
         self.assertRaises(ewords.NoSuchUser, d.getResult)
     testUserRetrieval = dG(testUserRetrieval)
@@ -108,13 +108,13 @@
         self.assertIdentical(p, user)
 
         # Make sure getting that user returns the same object
-        d = wFD(realm.getUser(u"testuser"))
+        d = wFD(realm.getUser("testuser"))
         yield d
         retrieved = d.getResult()
         self.assertIdentical(user, retrieved)
 
         # Make sure looking up that user returns the same object
-        d = wFD(realm.lookupUser(u"testuser"))
+        d = wFD(realm.lookupUser("testuser"))
         yield d
         lookedUp = d.getResult()
         self.assertIdentical(retrieved, lookedUp)
@@ -124,17 +124,17 @@
     def testGroupRetrieval(self):
         realm = service.InMemoryWordsRealm("realmname")
 
-        d = wFD(realm.createGroup(u"testgroup"))
+        d = wFD(realm.createGroup("testgroup"))
         yield d
         group = d.getResult()
 
-        d = wFD(realm.getGroup(u"testgroup"))
+        d = wFD(realm.getGroup("testgroup"))
         yield d
         retrieved = d.getResult()
 
         self.assertIdentical(group, retrieved)
 
-        d = wFD(realm.getGroup(u"nosuchgroup"))
+        d = wFD(realm.getGroup("nosuchgroup"))
         yield d
         self.assertRaises(ewords.NoSuchGroup, d.getResult)
     testGroupRetrieval = dG(testGroupRetrieval)
@@ -148,7 +148,7 @@
         yield d
         d.getResult()
 
-        d = wFD(realm.getGroup(u"testGroup"))
+        d = wFD(realm.getGroup("testGroup"))
         yield d
         group = d.getResult()
 
@@ -164,11 +164,11 @@
         """
         realm = service.InMemoryWordsRealm("realmname")
 
-        d = wFD(realm.createUser(u"test"))
+        d = wFD(realm.createUser("test"))
         yield d
         user = d.getResult()
 
-        d = wFD(realm.createGroup(u"test"))
+        d = wFD(realm.createGroup("test"))
         yield d
         group = d.getResult()
     testGroupUsernameCollision = dG(testGroupUsernameCollision)
@@ -176,11 +176,11 @@
 
     def testEnumeration(self):
         realm = service.InMemoryWordsRealm("realmname")
-        d = wFD(realm.createGroup(u"groupone"))
+        d = wFD(realm.createGroup("groupone"))
         yield d
         d.getResult()
 
-        d = wFD(realm.createGroup(u"grouptwo"))
+        d = wFD(realm.createGroup("grouptwo"))
         yield d
         d.getResult()
 
@@ -229,15 +229,15 @@
         self.protocol.makeConnection(self.transport)
 
     def write(self, stuff):
-        if isinstance(stuff, unicode):
+        if isinstance(stuff, str):
             stuff = stuff.encode('utf-8')
         self.protocol.dataReceived(stuff)
 
 
 class IRCProtocolTestCase(unittest.TestCase):
     STATIC_USERS = [
-        u'useruser', u'otheruser', u'someguy', u'firstuser', u'username',
-        u'userone', u'usertwo', u'userthree', u'someuser']
+        'useruser', 'otheruser', 'someguy', 'firstuser', 'username',
+        'userone', 'usertwo', 'userthree', 'someuser']
 
     def setUp(self):
         self.realm = service.InMemoryWordsRealm("realmname")
@@ -255,7 +255,7 @@
     def _assertGreeting(self, user):
         # Make sure we get 1-4 at least
         response = self._response(user)
-        expected = range(1, 5)
+        expected = list(range(1, 5))
         for (prefix, command, args) in response:
             try:
                 expected.remove(int(command))
@@ -284,11 +284,11 @@
     def _response(self, user):
         response = user.transport.value().splitlines()
         user.transport.clear()
-        return map(irc.parsemsg, response)
+        return list(map(irc.parsemsg, response))
 
 
     def testPASSLogin(self):
-        user = wFD(self._loggedInUser(u'firstuser'))
+        user = wFD(self._loggedInUser('firstuser'))
         yield user
         user = user.getResult()
         self._assertGreeting(user)
@@ -296,7 +296,7 @@
 
 
     def testNickServLogin(self):
-        firstuser = wFD(self.realm.lookupUser(u'firstuser'))
+        firstuser = wFD(self.realm.lookupUser('firstuser'))
         yield firstuser
         firstuser = firstuser.getResult()
 
@@ -315,7 +315,7 @@
 
 
     def testFailedLogin(self):
-        firstuser = wFD(self.realm.lookupUser(u'firstuser'))
+        firstuser = wFD(self.realm.lookupUser('firstuser'))
         yield firstuser
         firstuser = firstuser.getResult()
 
@@ -329,7 +329,7 @@
 
     def testLogout(self):
         logout = []
-        firstuser = wFD(self.realm.lookupUser(u'firstuser'))
+        firstuser = wFD(self.realm.lookupUser('firstuser'))
         yield firstuser
         firstuser = firstuser.getResult()
 
@@ -342,11 +342,11 @@
 
 
     def testJoin(self):
-        firstuser = wFD(self.realm.lookupUser(u'firstuser'))
+        firstuser = wFD(self.realm.lookupUser('firstuser'))
         yield firstuser
         firstuser = firstuser.getResult()
 
-        somechannel = wFD(self.realm.createGroup(u"somechannel"))
+        somechannel = wFD(self.realm.createGroup("somechannel"))
         yield somechannel
         somechannel = somechannel.getResult()
 
@@ -376,7 +376,7 @@
 
 
         # Hook up another client!  It is a CHAT SYSTEM!!!!!!!
-        other = wFD(self._loggedInUser(u'otheruser'))
+        other = wFD(self._loggedInUser('otheruser'))
         yield other
         other = other.getResult()
 
@@ -404,11 +404,11 @@
         When a user joins a group without a topic, no topic information is
         sent to that user.
         """
-        firstuser = wFD(self.realm.lookupUser(u'firstuser'))
+        firstuser = wFD(self.realm.lookupUser('firstuser'))
         yield firstuser
         firstuser = firstuser.getResult()
 
-        somechannel = wFD(self.realm.createGroup(u"somechannel"))
+        somechannel = wFD(self.realm.createGroup("somechannel"))
         yield somechannel
         somechannel = somechannel.getResult()
 
@@ -426,18 +426,18 @@
 
 
     def testLeave(self):
-        user = wFD(self._loggedInUser(u'useruser'))
-        yield user
-        user = user.getResult()
-
-        somechannel = wFD(self.realm.createGroup(u"somechannel"))
+        user = wFD(self._loggedInUser('useruser'))
+        yield user
+        user = user.getResult()
+
+        somechannel = wFD(self.realm.createGroup("somechannel"))
         yield somechannel
         somechannel = somechannel.getResult()
 
         user.write('JOIN #somechannel\r\n')
         user.transport.clear()
 
-        other = wFD(self._loggedInUser(u'otheruser'))
+        other = wFD(self._loggedInUser('otheruser'))
         yield other
         other = other.getResult()
 
@@ -477,7 +477,7 @@
 
 
     def testGetTopic(self):
-        user = wFD(self._loggedInUser(u'useruser'))
+        user = wFD(self._loggedInUser('useruser'))
         yield user
         user = user.getResult()
 
@@ -517,17 +517,17 @@
 
 
     def testSetTopic(self):
-        user = wFD(self._loggedInUser(u'useruser'))
-        yield user
-        user = user.getResult()
-
-        add = wFD(self.realm.createGroup(u"somechannel"))
+        user = wFD(self._loggedInUser('useruser'))
+        yield user
+        user = user.getResult()
+
+        add = wFD(self.realm.createGroup("somechannel"))
         yield add
         somechannel = add.getResult()
 
         user.write("JOIN #somechannel\r\n")
 
-        other = wFD(self._loggedInUser(u'otheruser'))
+        other = wFD(self._loggedInUser('otheruser'))
         yield other
         other = other.getResult()
 
@@ -567,17 +567,17 @@
 
 
     def testGroupMessage(self):
-        user = wFD(self._loggedInUser(u'useruser'))
-        yield user
-        user = user.getResult()
-
-        add = wFD(self.realm.createGroup(u"somechannel"))
+        user = wFD(self._loggedInUser('useruser'))
+        yield user
+        user = user.getResult()
+
+        add = wFD(self.realm.createGroup("somechannel"))
         yield add
         somechannel = add.getResult()
 
         user.write("JOIN #somechannel\r\n")
 
-        other = wFD(self._loggedInUser(u'otheruser'))
+        other = wFD(self._loggedInUser('otheruser'))
         yield other
         other = other.getResult()
 
@@ -600,11 +600,11 @@
 
 
     def testPrivateMessage(self):
-        user = wFD(self._loggedInUser(u'useruser'))
-        yield user
-        user = user.getResult()
-
-        other = wFD(self._loggedInUser(u'otheruser'))
+        user = wFD(self._loggedInUser('useruser'))
+        yield user
+        user = user.getResult()
+
+        other = wFD(self._loggedInUser('otheruser'))
         yield other
         other = other.getResult()
 
@@ -634,7 +634,7 @@
 
 
     def testOper(self):
-        user = wFD(self._loggedInUser(u'useruser'))
+        user = wFD(self._loggedInUser('useruser'))
         yield user
         user = user.getResult()
 
@@ -648,7 +648,7 @@
 
 
     def testGetUserMode(self):
-        user = wFD(self._loggedInUser(u'useruser'))
+        user = wFD(self._loggedInUser('useruser'))
         yield user
         user = user.getResult()
 
@@ -664,7 +664,7 @@
 
 
     def testSetUserMode(self):
-        user = wFD(self._loggedInUser(u'useruser'))
+        user = wFD(self._loggedInUser('useruser'))
         yield user
         user = user.getResult()
 
@@ -678,11 +678,11 @@
 
 
     def testGetGroupMode(self):
-        user = wFD(self._loggedInUser(u'useruser'))
-        yield user
-        user = user.getResult()
-
-        add = wFD(self.realm.createGroup(u"somechannel"))
+        user = wFD(self._loggedInUser('useruser'))
+        yield user
+        user = user.getResult()
+
+        add = wFD(self.realm.createGroup("somechannel"))
         yield add
         somechannel = add.getResult()
 
@@ -698,11 +698,11 @@
 
 
     def testSetGroupMode(self):
-        user = wFD(self._loggedInUser(u'useruser'))
-        yield user
-        user = user.getResult()
-
-        group = wFD(self.realm.createGroup(u"groupname"))
+        user = wFD(self._loggedInUser('useruser'))
+        yield user
+        user = user.getResult()
+
+        group = wFD(self.realm.createGroup("groupname"))
         yield group
         group = group.getResult()
 
@@ -724,7 +724,7 @@
         add.getResult()
 
         users = []
-        for nick in u'userone', u'usertwo', u'userthree':
+        for nick in 'userone', 'usertwo', 'userthree':
             u = wFD(self._loggedInUser(nick))
             yield u
             u = u.getResult()
@@ -766,12 +766,12 @@
 
 
     def testList(self):
-        user = wFD(self._loggedInUser(u"someuser"))
-        yield user
-        user = user.getResult()
-        user.transport.clear()
-
-        somegroup = wFD(self.realm.createGroup(u"somegroup"))
+        user = wFD(self._loggedInUser("someuser"))
+        yield user
+        user = user.getResult()
+        user.transport.clear()
+
+        somegroup = wFD(self.realm.createGroup("somegroup"))
         yield somegroup
         somegroup = somegroup.getResult()
         somegroup.size = lambda: succeed(17)
@@ -815,7 +815,7 @@
 
 
     def testWhois(self):
-        user = wFD(self._loggedInUser(u'someguy'))
+        user = wFD(self._loggedInUser('someguy'))
         yield user
         user = user.getResult()
 
@@ -933,24 +933,24 @@
 
     def testGroups(self):
         mindone = TestMind()
-        one = wFD(self._loggedInAvatar(u"one", "p1", mindone))
+        one = wFD(self._loggedInAvatar("one", "p1", mindone))
         yield one
         one = one.getResult()
 
         mindtwo = TestMind()
-        two = wFD(self._loggedInAvatar(u"two", "p2", mindtwo))
+        two = wFD(self._loggedInAvatar("two", "p2", mindtwo))
         yield two
         two = two.getResult()
 
-        add = wFD(self.realm.createGroup(u"foobar"))
+        add = wFD(self.realm.createGroup("foobar"))
         yield add
         add.getResult()
 
-        groupone = wFD(one.join(u"foobar"))
+        groupone = wFD(one.join("foobar"))
         yield groupone
         groupone = groupone.getResult()
 
-        grouptwo = wFD(two.join(u"foobar"))
+        grouptwo = wFD(two.join("foobar"))
         yield grouptwo
         grouptwo = grouptwo.getResult()
 
--- twisted/words/test/test_toc.py (original)
+++ twisted/words/test/test_toc.py (refactored)
@@ -8,10 +8,10 @@
 from twisted.internet import protocol, main
 from twisted.python import failure
 
-import StringIO
+import io
 from struct import pack,unpack
 
-class StringIOWithoutClosing(StringIO.StringIO):
+class StringIOWithoutClosing(io.StringIO):
     def close(self):
         pass
         
@@ -43,7 +43,7 @@
         self.runTest()
     def runTest(self):
         USERS=2
-        data=range(USERS)
+        data=list(range(USERS))
         data[0]=("FLAPON\r\n\r\n",\
         flap(1,"\000\000\000\001\000\001\000\004test"),\
         flap(2,"toc_signon localhost 9999 test 0x100000 english \"penguin 0.1\"\000"),\
@@ -87,16 +87,16 @@
         flap(2,"toc_chat_send 0 \"hi test\"\000"),\
         flap(5,"\000"),\
         flap(2,"toc_chat_leave 0\000"))
-        strings=range(USERS)
+        strings=list(range(USERS))
         for i in strings:
             strings[i]=StringIOWithoutClosing()
         fac=toc.TOCFactory()
-        dummy=range(USERS)
+        dummy=list(range(USERS))
         for i in dummy:
             dummy[i]=DummyTOC()
             dummy[i].factory=fac
             dummy[i].makeConnection(protocol.FileWrapper(strings[i]))
-        while reduce(lambda x,y:x+y,map(lambda x:x==(),data))!=USERS:
+        while reduce(lambda x,y:x+y,[x==() for x in data])!=USERS:
             for i in range(USERS):
                 d=data[i]
                 if len(d)>0:
@@ -105,20 +105,20 @@
                         dummy[i].dataReceived(j) # test by doing a character at a time
                 else:
                     dummy[i].connectionLost(failure.Failure(main.CONNECTION_DONE))
-        values=range(USERS)
+        values=list(range(USERS))
         for i in values:
             values[i]=strings[i].getvalue()
-        flaps=map(lambda x:[],range(USERS))
+        flaps=[[] for x in list(range(USERS))]
         for value in values:
             i=values.index(value)
             f,value=readFlap(value)
             while f:
                 flaps[i].append(f)
                 f,value=readFlap(value)
-        ts=range(USERS)
+        ts=list(range(USERS))
         for t in ts:
             ts[t]=dummy[t].signontime
-        shouldequal=range(USERS)
+        shouldequal=list(range(USERS))
         shouldequal[0]=[ \
         [1,"\000\000\000\001"],\
         [2,"SIGN_ON:TOC1.0\000"],\
--- twisted/words/xish/domish.py (original)
+++ twisted/words/xish/domish.py (refactored)
@@ -37,14 +37,14 @@
         if prefixes:
             self.prefixes.update(prefixes)
         self.prefixes.update(G_PREFIXES)
-        self.prefixStack = [G_PREFIXES.values()] + (prefixesInScope or [])
+        self.prefixStack = [list(G_PREFIXES.values())] + (prefixesInScope or [])
         self.prefixCounter = 0
 
     def getValue(self):
-        return u"".join(self.writelist)
+        return "".join(self.writelist)
 
     def getPrefix(self, uri):
-        if not self.prefixes.has_key(uri):
+        if uri not in self.prefixes:
             self.prefixes[uri] = "xn%d" % (self.prefixCounter)
             self.prefixCounter = self.prefixCounter + 1
         return self.prefixes[uri]
@@ -66,7 +66,7 @@
             return
 
         # Shortcut, check to see if elem is actually a string (aka Cdata)
-        if isinstance(elem, types.StringTypes):
+        if isinstance(elem, str):
             write(escapeToXml(elem))
             return
 
@@ -76,9 +76,9 @@
         uri = elem.uri
         defaultUri, currentDefaultUri = elem.defaultUri, defaultUri
 
-        for p, u in elem.localPrefixes.iteritems():
+        for p, u in elem.localPrefixes.items():
             self.prefixes[u] = p
-        self.prefixStack.append(elem.localPrefixes.keys())
+        self.prefixStack.append(list(elem.localPrefixes.keys()))
 
         # Inherit the default namespace
         if defaultUri is None:
@@ -108,13 +108,13 @@
            (uri != defaultUri or not prefix or not inScope):
             write(" xmlns='%s'" % (defaultUri))
 
-        for p, u in elem.localPrefixes.iteritems():
+        for p, u in elem.localPrefixes.items():
             write(" xmlns:%s='%s'" % (p, u))
 
         # Serialize attributes
-        for k,v in elem.attributes.items():
+        for k,v in list(elem.attributes.items()):
             # If the attribute name is a tuple, it's a qualified attribute
-            if isinstance(k, types.TupleType):
+            if isinstance(k, tuple):
                 attr_uri, attr_name = k
                 attr_prefix = self.getPrefix(attr_uri)
 
@@ -198,7 +198,7 @@
             yield n
 
 
-class SerializedXML(unicode):
+class SerializedXML(str):
     """ Marker class for pre-serialized XML in the DOM. """
     pass
 
@@ -403,7 +403,7 @@
         self.localPrefixes = localPrefixes or {}
         self.uri, self.name = qname
         if defaultUri is None and \
-           self.uri not in self.localPrefixes.itervalues():
+           self.uri not in iter(self.localPrefixes.values()):
             self.defaultUri = self.uri
         else:
             self.defaultUri = defaultUri
@@ -437,12 +437,12 @@
         """ Retrieve the first CData (content) node
         """
         for n in self.children:
-            if isinstance(n, types.StringTypes): return n
+            if isinstance(n, str): return n
         return ""
 
     def _dqa(self, attr):
         """ Dequalify an attribute key as needed """
-        if isinstance(attr, types.TupleType) and not attr[0]:
+        if isinstance(attr, tuple) and not attr[0]:
             return attr[1]
         else:
             return attr
@@ -453,7 +453,7 @@
 
     def hasAttribute(self, attrib):
         """ Determine if the specified attribute exists """
-        return self.attributes.has_key(self._dqa(attrib))
+        return self._dqa(attrib) in self.attributes
 
     def compareAttribute(self, attrib, value):
         """ Safely compare the value of an attribute against a provided value.
@@ -479,7 +479,7 @@
     def addContent(self, text):
         """ Add some text data to this Element. """
         c = self.children
-        if len(c) > 0 and isinstance(c[-1], types.StringTypes):
+        if len(c) > 0 and isinstance(c[-1], str):
             c[-1] = c[-1] + text
         else:
             c.append(text)
@@ -588,8 +588,8 @@
         def parse(self, buffer):
             try:
                 self.dataReceived(buffer)
-            except sux.ParseError, e:
-                raise ParserError, str(e)
+            except sux.ParseError as e:
+                raise ParserError(str(e))
 
 
         def findUri(self, prefix):
@@ -608,7 +608,7 @@
             uri = None
 
             # Pass 1 - Identify namespace decls
-            for k, v in attributes.items():
+            for k, v in list(attributes.items()):
                 if k.startswith("xmlns"):
                     x, p = _splitPrefix(k)
                     if (x is None): # I.e.  default declaration
@@ -637,7 +637,7 @@
                 uri = self.findUri(prefix)
 
             # Pass 2 - Fix up and escape attributes
-            for k, v in attributes.items():
+            for k, v in list(attributes.items()):
                 p, n = _splitPrefix(k)
                 if p is None:
                     attribs[n] = v
@@ -692,7 +692,7 @@
             # Ensure the document hasn't already ended
             if self.rootElem is None:
                 # XXX: Write more legible explanation
-                raise ParserError, "Element closed after end of document."
+                raise ParserError("Element closed after end of document.")
 
             # Fix up name
             prefix, name = _splitPrefix(name)
@@ -705,7 +705,7 @@
             if self.currElem is None:
                 # Ensure element name and uri matches
                 if self.rootElem.name != name or self.rootElem.uri != uri:
-                    raise ParserError, "Mismatched root elements"
+                    raise ParserError("Mismatched root elements")
                 self.DocumentEndEvent()
                 self.rootElem = None
 
@@ -715,7 +715,7 @@
                 # element
                 if self.currElem.name != name or self.currElem.uri != uri:
                     # XXX: Write more legible explanation
-                    raise ParserError, "Malformed element close"
+                    raise ParserError("Malformed element close")
 
                 # Pop prefix and default NS stack
                 self.prefixStack.pop()
@@ -754,8 +754,8 @@
     def parse(self, buffer):
         try:
             self.parser.Parse(buffer)
-        except self.error, e:
-            raise ParserError, str(e)
+        except self.error as e:
+            raise ParserError(str(e))
 
     def _onStartElement(self, name, attrs):
         # Generate a qname tuple from the provided name
@@ -764,7 +764,7 @@
             qname = ('', name)
 
         # Process attributes
-        for k, v in attrs.items():
+        for k, v in list(attrs.items()):
             if k.find(" ") != -1:
                 aqname = k.split(" ")
                 attrs[(aqname[0], aqname[1])] = v
--- twisted/words/xish/utility.py (original)
+++ twisted/words/xish/utility.py (refactored)
@@ -102,7 +102,7 @@
         @type kwargs: C{dict}
         """
 
-        for key, (methodwrapper, onetime) in self.callbacks.items():
+        for key, (methodwrapper, onetime) in list(self.callbacks.items()):
             try:
                 methodwrapper(*args, **kwargs)
             except:
@@ -267,8 +267,8 @@
         event, observers = self._getEventAndObservers(event)
 
         emptyLists = []
-        for priority, priorityObservers in observers.iteritems():
-            for query, callbacklist in priorityObservers.iteritems():
+        for priority, priorityObservers in observers.items():
+            for query, callbacklist in priorityObservers.items():
                 if event == query:
                     callbacklist.removeCallback(observerfn)
                     if callbacklist.isEmpty():
@@ -306,13 +306,13 @@
             observers = self._xpathObservers
             match = lambda query, obj: query.matches(obj)
 
-        priorities = observers.keys()
+        priorities = list(observers.keys())
         priorities.sort()
         priorities.reverse()
 
         emptyLists = []
         for priority in priorities:
-            for query, callbacklist in observers[priority].iteritems():
+            for query, callbacklist in observers[priority].items():
                 if match(query, obj):
                     callbacklist.callback(obj)
                     foundTarget = True
--- twisted/words/xish/xmlstream.py (original)
+++ twisted/words/xish/xmlstream.py (refactored)
@@ -20,10 +20,10 @@
 from twisted.internet import protocol
 from twisted.words.xish import domish, utility
 
-STREAM_CONNECTED_EVENT = intern("//event/stream/connected")
-STREAM_START_EVENT = intern("//event/stream/start")
-STREAM_END_EVENT = intern("//event/stream/end")
-STREAM_ERROR_EVENT = intern("//event/stream/error")
+STREAM_CONNECTED_EVENT = sys.intern("//event/stream/connected")
+STREAM_START_EVENT = sys.intern("//event/stream/start")
+STREAM_END_EVENT = sys.intern("//event/stream/end")
+STREAM_ERROR_EVENT = sys.intern("//event/stream/error")
 
 class XmlStream(protocol.Protocol, utility.EventDispatcher):
     """ Generic Streaming XML protocol handler.
@@ -140,7 +140,7 @@
         if domish.IElement.providedBy(obj):
             obj = obj.toXml()
 
-        if isinstance(obj, unicode):
+        if isinstance(obj, str):
             obj = obj.encode('utf-8')
 
         if self.rawDataOutFn:
--- twisted/words/xish/xpath.py (original)
+++ twisted/words/xish/xpath.py (refactored)
@@ -12,9 +12,9 @@
 """
 
 try:
-    import cStringIO as StringIO
+    import io as StringIO
 except ImportError:
-    import StringIO
+    import io
 
 class LiteralValue(str):
     def value(self, elem):
@@ -182,7 +182,7 @@
                 self.childLocation.queryForStringList(c, resultlist)
         else:
             for c in elem.children:
-                if isinstance(c, (str, unicode)):
+                if isinstance(c, (str, str)):
                     resultlist.append(c)
 
 
@@ -269,7 +269,7 @@
     def queryForStringList(self, elem, resultlist):
         if self.isRootMatch(elem):
             for c in elem.children:
-                if isinstance(c, (str, unicode)):
+                if isinstance(c, (str, str)):
                     resultlist.append(c)
         for c in elem.elements():
             self.queryForStringList(c, resultlist)
@@ -288,7 +288,7 @@
         return self.baseLocation.matches(elem)
 
     def queryForString(self, elem):
-        result = StringIO.StringIO()
+        result = io.StringIO()
         self.baseLocation.queryForString(elem, result)
         return result.getvalue()
 
--- twisted/words/xish/xpathparser.py (original)
+++ twisted/words/xish/xpathparser.py (refactored)
@@ -285,8 +285,8 @@
         p = p - 7
 
     # Now print the string, along with an indicator
-    print >>sys.stderr, '> ',text
-    print >>sys.stderr, '> ',' '*p + '^'
+    print('> ',text, file=sys.stderr)
+    print('> ',' '*p + '^', file=sys.stderr)
 
 def print_error(input, err, scanner):
     """Print error messages, the parser stack, and the input text -- for human-readable error messages."""
@@ -294,7 +294,7 @@
     # Figure out the line number
     line_number = scanner.get_line_number()
     column_number = scanner.get_column_number()
-    print >>sys.stderr, '%d:%d: %s' % (line_number, column_number, err.msg)
+    print('%d:%d: %s' % (line_number, column_number, err.msg), file=sys.stderr)
 
     context = err.context
     if not context:
@@ -302,19 +302,19 @@
 
     while context:
         # TODO: add line number
-        print >>sys.stderr, 'while parsing %s%s:' % (context.rule, tuple(context.args))
+        print('while parsing %s%s:' % (context.rule, tuple(context.args)), file=sys.stderr)
         print_line_with_pointer(input, context.scanner.get_prev_char_pos(context.tokenpos))
         context = context.parent
 
 def wrap_error_reporter(parser, rule):
     try:
         return getattr(parser, rule)()
-    except SyntaxError, e:
+    except SyntaxError as e:
         input = parser._scanner.input
         print_error(input, e, parser._scanner)
     except NoMoreTokens:
-        print >>sys.stderr, 'Could not complete parsing; stopped around here:'
-        print >>sys.stderr, parser._scanner
+        print('Could not complete parsing; stopped around here:', file=sys.stderr)
+        print(parser._scanner, file=sys.stderr)
 
 
 from twisted.words.xish.xpath import AttribValue, BooleanValue, CompareValue
@@ -503,6 +503,6 @@
             f = open(argv[2],'r')
         else:
             f = stdin
-        print parse(argv[1], f.read())
-    else: print >>sys.stderr, 'Args:  <rule> [<filename>]'
+        print(parse(argv[1], f.read()))
+    else: print('Args:  <rule> [<filename>]', file=sys.stderr)
 # End -- grammar generated by Yapps
