--- 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,)) @@ -683,9 +683,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/conch/client/connect.py (original) +++ twisted/conch/client/connect.py (refactored) @@ -2,7 +2,7 @@ # See LICENSE for details. # -import direct +from . import direct connectTypes = {"direct" : direct.connect} --- 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 @@ -156,7 +156,7 @@ sys.stdout,sys.stdin=oldout,oldin return p except (KeyboardInterrupt, IOError): - print + print() raise ConchError('PEBKAC') def getPassword(self, prompt = None): @@ -233,7 +233,7 @@ return defer.fail(ConchError('bad password')) raise except KeyboardInterrupt: - print + print() reactor.stop() @@ -243,12 +243,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--- 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) @@ -144,7 +144,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: @@ -186,7 +186,7 @@ self.successfulCredentials = {} def get_credentialInterfaces(self): - return self.checkers.keys() + return list(self.checkers.keys()) credentialInterfaces = property(get_credentialInterfaces) --- 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/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('--- 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/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/client/direct.py (original) +++ twisted/conch/client/direct.py (refactored) @@ -79,7 +79,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): --- 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/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 'Pass--- 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/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/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/telnet.py (original) +++ twisted/conch/telnet.py (refactored) @@ -522,7 +522,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 @@ -912,7 +912,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/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 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])phrases 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]))) --- 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/factory.py (original) +++ twisted/conch/ssh/factory.py (refactored) @@ -19,7 +19,7 @@ from twisted.conch import error from twisted.conch.ssh import keys -import transport, userauth, connection +from . import transport, userauth, connection import random import warnings @@ -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'): sel: if echo: - responses.append(raw_input(prompt)) + responses.append(input(prompt)) else: responses.append(getpass.getpass(prompt)) finally: --- twisted/conch/client/options.py (original) +++ twisted/conch/client/options.py (refactored) @@ -34,9 +34,9 @@ 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), #"user-authentications":"_values -s , 'user authentication types to choose from' %s" % @@ -59,7 +59,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 @@ -68,7 +68,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 --- 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/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/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, tkinter.filedialog, tkinter.font, tkinter.messagebox, 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) @@ -89,20 +89,20 @@ def getIdentityFile(self): - r = tkFileDialog.askopenfilename() + r = tkinter.filedialog.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() @@ -122,14 +122,14 @@ if cipher in SSHClientTransport.supportedCiphers: SSHClientTransport.supportedCiphers = [cipher] else: - tkMessageBox.showerror('TkConch', 'Bad cipher.') + tkinter.messagebox.showerror('TkConch', 'Bad cipher.') finished = 0 if mac: if mac in SSHClientTransport.supportedMACs: SSHClientTransport.supportedMACs = [mac] elif finished: - tkMessageBox.showerror('TkConch', 'Bad MAC.') + tkinter.messagebox.showerror('TkConch', 'Bad MAC.') finished = 0 if escape: @@ -140,13 +140,13 @@ elif len(escape) == 1: options['escape'] = escape elif finished: - tkMessageBox.showerror('TkConch', "Bad escape character '%s'." % escape) + tkinter.messagebox.showerror('TkConch', "Bad escape character '%s'." % escape) finished = 0 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: @@ -156,7 +156,7 @@ options['user'], options['host'] = options['host'].split('@',1) if (not options['host'] or not options['user']) and finished: - tkMessageBox.showerror('TkConch', 'Missing host or username.') + tkinter.messagebox.showerror('TkConch', 'Missing host or username.') finished = 0 if finished: self.master.quit() @@ -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']: @@ -342,7 +342,7 @@ return SSHClientTransport() def clientConnectionFailed(self, connector, reason): - tkMessageBox.showwarning('TkConch','Connection Failed, Reason:\n %s: %s' % (reason.type, reason.value)) + tkinter.messagebox.showwarning('TkConch','Connection Failed, Reason:\n %s: %s' % (reason.type, reason.value)) class SSHClientTransport(transport.SSHClientTransport): @@ -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/keys.py (original) +++ twisted/conch/ssh/keys.py (refactored) @@ -82,7 +82,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) @@ -221,19 +221,19 @@ keyData = base64.decodestring(b64Data) try: decodedKey = berDecoder.decode(keyData)[0] - 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] if len(decodedKey) < 6: raise BadKeyError('RSA key failed to decode properly') - n, e, d, p, q = [long(value) for value in decodedKey[1:6]] + n, e, d, p, q = [int(value) for value in decodedKey[1:6]] if p > q: # make p smaller than q p, q = q, p return Class(RSA.construct((n, e, d, p, q))) elif kind == 'DSA': - p, q, g, y, x = [long(value) for value in decodedKey[1: 6]] + p, q, g, y, x = [int(value) for value in decodedKey[1: 6]] if len(decodedKey) < 6: raise BadKeyError('DSA key failed to decode properly') return Class(DSA.construct((y, g, p, q, x))) @@ -402,7 +402,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: @@ -575,7 +575,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() @@ -607,7 +607,7 @@ objData = (0, data['p'], data['q'], data['g'], data['y'], data['x']) asn1Sequence = univ.Sequence() - for index, value in itertools.izip(itertools.count(), objData): + for index, value in zip(itertools.count(), objData): asn1Sequence.setComponentByPosition(index, univ.Integer(value)) asn1Data = berEncoder.encode(asn1Sequence) if extra: @@ -724,8 +724,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/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' '472053920406973753286383105093071943149833883541551517388 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/ssh/asn1.py (original) +++ twisted/conch/ssh/asn1.py (refactored) @@ -23,7 +23,7 @@ def pack(data): asn1Sequence = univ.Sequence() - for index, value in itertools.izip(itertools.count(), data): + for index, value in zip(itertools.count(), data): try: valueAsInteger = univ.Integer(value) except TypeError: --- 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/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): + df.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/forwarding.py (original) +++ twisted/conch/ssh/forwarding.py (refactored) @@ -15,7 +15,7 @@ from twisted.internet import protocol, reactor from twisted.python import log -import common, channel +from . import common, channel class SSHListenForwardingFactory(protocol.Factory): def __init__(self, connection, hostport, klass): @@ -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/session.py (original) +++ twisted/conch/ssh/session.py (refactored) @@ -219,7 +219,7 @@ sigvalue = getattr(signal, signame, None) if sigvalue is not None: self._signalValuesToNames[sigvalue] = signame - for k, v in signal.__dict__.items(): + for k, v in list(signal.__dict__.items()): # Check for platform specific signals, ignoring Python specific # SIG_DFL and SIG_IGN if k.startswith('SIG') and not k.startswith('SIG_'): @@ -284,11 +284,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 @@ -302,9 +303,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/userauth.py (original) +++ twisted/conch/ssh/userauth.py (refactored) @@ -188,12 +188,13 @@ return d - def _@@ 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/ssh/agent.py (original) +++ twisted/conch/ssh/agent.py (refactored) @@ -181,7 +181,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)) @@ -288,7 +288,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/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/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/test/test_conch.py (original) +++ twisted/conch/test/test_conch.py (refactored) @@ -303,7 +303,7 @@ remoteHP, origHP = forwarding.unpackOpen_forwarded_tcpip(data) log.msg(self.remoteForwards) log.msg(remoteHP) - if self.remoteForwards.has_key(re7L')} 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_checkers.py (original) +++ twisted/conch/test/test_checkers.py (refactored) @@ -99,11 +99,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_keys.py (original) +++ twisted/conch/test/test_keys.py (refactored) @@ -177,7 +177,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 @@ -485,8 +485,8 @@ skip = "cannot run w/o/ PyASN1" 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' @@ -550,14 +550,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): @@ -656,7 +656,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) @@ -666,7 +666,7 @@ """ rsa1 = keys.Key(self.rsaObj) rsa2 = keys.KeycbFinishedAuth(self, (interface, avatar, logout)): + def _cbFinishedAuth(self, xxx_todo_changeme): """ The callback when user has successfully been authenticated. For a description of the arguments, see L{twisted.cred.portal.Portal.login}. We start the service requested by the user. """ + (interface, avatar, logout) = xxx_todo_changeme self.transport.avatar = avatar self.transport.logoutFunction = logout service = self.transport.factory.getService(self.transport, @@ -510,7 +511,7 @@ if result: return try: - method = iterator.next() + method = next(iterator) except StopIteration: self.transport.sendDisconnect( transport.DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE, @@ -815,7 +816,7 @@ MSG_USERAUTH_PK_OK = 60 messages = {} -for k, v in locals().items(): +for k, v in list(locals().items()): if k[:4]=='MSG_': messages[v] = k # doesn't handle doubles --- 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_ckeygen.py (original) +++ twisted/conch/test/test_ckeygen.py (refactored) @@ -6,7 +6,7 @@ """ import sys -from StringIO import StringIO +from io import StringIO try: import Crypto --- twisted/conch/test/test_openssh_compat.py (original) +++ twisted/conch/test/test_openssh_compat.py (refactored) @@ -62,7 +62,7 @@ """ keys = self.factory.getPublicKeys() self.assertEquals(len(keys), 1) - keyTypes = keys.keys() + keyTypes = list(keys.keys()) self.assertEqual(keyTypes, ['ssh-rsa']) @@ -73,7 +73,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, []) @@ -87,16 +87,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_ssh.py (original) +++ twisted/conch/test/test_ssh.py (refactored) @@ -24,7 +24,7 @@ from twisted.python import failure, log from twisted.trial import unittest -from test_recvline import LoopbackRelay +from .test_recvline import LoopbackRelay @@ -79,7 +79,7 @@ def logout(self): self.loggedOut = True - for listener in self.listeners.values(): + for listener in list(self.listeners.values()): log.msg('stopListening %s' % listener) listener.stopListening() @@ -242,10 +242,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))) @@ -282,7 +282,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/ui/tkvt100.py (original) +++ twisted/conch/ui/tkvt100.py (refactored) @@ -8,8 +8,8 @@ Maintainer: Paul Swartz """ -import Tkinter, tkFont -import ansi +import tkinter, tkinter.font +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']) + ttyFont = tkinter.font.Font(family = 'Courier', size = 10) + 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('', self.keyPressed) self.canvas.bind('<1>', lambda x: 'break') self.canvas.bind('', 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(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) @@ -680,7 +680,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) @@ -712,9 +712,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) @@ -732,9 +732,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/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/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/_threadedselect.py (origef __next__(self): if self.filesCache: return self.filesCache.pop(0) d = self.read() @@ -884,7 +884,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 @@ -920,7 +920,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/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/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/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/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 . """ - return self.checkers.keys() + return list(self.checkers.keys()) def registerChecker(self, checker, *credentialInterfaces): if not credentialInterfaces: --- 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/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/_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/default.py (original) +++ twisted/internet/default.py (refactored) @@ -15,7 +15,7 @@ warnings.warn("twisted.internet.default is deprecated. Use posixbase or selectinal) +++ 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/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 @@ moteHP[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_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_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_transport.py (original) +++ twisted/conch/test/test_transport.py (refactored) @@ -276,7 +276,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 @@ -294,7 +294,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 @@ -1641,7 +1641,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) @@ -1655,7 +1655,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) @@ -1673,7 +1673,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') @@ -1698,7 +1698,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/internet/base.py (original) +++ twisted/internet/base.py (refactored) @@ -30,6 +30,7 @@ # This import is for side-effects! Even if you don't see any code using it # in this module, don't delete it. from twisted.python import threadable +from functools import reduce class DelayedCall(styles.Ephemeral): @@ -160,9 +161,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: @@ -179,7 +180,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: @@ -348,7 +349,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'): @@ -614,7 +615,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( @@ -671,8 +672,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, @@ -840,7 +841,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: @@ -869,7 +870,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") @@ -896,7 +897,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. @@ -923,7 +924,7 @@ called by a shutdown trigger created in L{_initThreadPool}. """ triggers = [self._threadpoolStartupID, self.threadpoolShutdownID] - for trigger in filter(None, triggers): + for trigger in [_f for _f in triggers if _f]: try: self.removeSystemEventTrigger(trigger) except ValueError: @@ -957,7 +958,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_ 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/fdesc.py (original) +++ twisted/internet/fdesc.py (refactored) @@ -84,7 +84,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: @@ -109,7 +109,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) @@ -123,11 +123,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/kqreactor.py (original) +++ twisted/internet/kqreactor.py (refactored) @@ -176,7 +176,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/posixbase.py (original) +++ twisted/internet/posixbase.py (refactored) @@ -42,7 +42,7 @@ processEnabled = False if platformType == 'posix': from twisted.internet import fdesc - import process + from . import process processEnabled = True if platform.isWindows(): @@ -84,7 +84,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 @@ -135,7 +136,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 @@ -233,9 +234,9 @@ from twisted.internet._dumbwin32proc import Process _'), "%s is not callable" % (f,) # See comment in the other callFromThread implementation. self.threadCallQueue.append((f, args, kw)) @@ -992,7 +993,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: @@ -1006,7 +1007,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()) @@ -1068,7 +1069,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/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/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 @@ -102,7 +102,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 @@ """ # systemreactor 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/epollreactor.py (original) +++ twisted/internet/epollreactor.py (refactored) @@ -113,7 +113,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: @@ -175,7 +175,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/gtkreactor.py (original) +++ twisted/internet/gtkreactor.py (refactored) @@ -19,7 +19,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 @@ -68,11 +68,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/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,30 +627,30 @@ # 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) fdesc._unsetCloseOnExec(child) 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 @@ -662,11 +662,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) @@ -682,12 +682,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() @@ -861,7 +861,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/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 == EMSGSI imports -import Tkinter, tkSimpleDialog, tkMessageBox +import tkinter, tkinter.simpledialog, tkinter.messagebox # twisted imports from twisted.python import log @@ -56,13 +56,13 @@ def getPassword(prompt = '', confirm = 0): while 1: - try1 = tkSimpleDialog.askstring('Password Dialog', prompt, show='*') + try1 = tkinter.simpledialog.askstring('Password Dialog', prompt, show='*') if not confirm: return try1 - try2 = tkSimpleDialog.askstring('Password Dialog', 'Confirm Password', show='*') + try2 = tkinter.simpledialog.askstring('Password Dialog', 'Confirm Password', show='*') if try1 == try2: return try1 else: - tkMessageBox.showerror('Password Mismatch', 'Passwords did not match, starting over') + tkinter.messagebox.showerror('Password Mismatch', 'Passwords did not match, starting over') __all__ = ["install", "uninstall"] --- twisted/internet/udp.py (original) +++ twisted/internet/udp.py (refactored) @@ -37,7 +37,7 @@ from twisted.python import log, reflect, failure # Sibling Imports -import abstract, error, interfaces +from . import abstract, error, interfaces class Port(base.BasePort): @@ -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 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 @@ -299,7 +300,7 @@ category=DeprecationWarning, stacklevel=3) else: - mode = 0666 + mode = 0o666 return mode --- twisted/internet/task.py (original) +++ twisted/internet/task.py (refactored) @@ -74,7 +74,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() @@ -142,9 +142,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) @@ -376,7 +376,7 @@ pausing if the result was a L{defer.Deferred}. """ try: - result = self._iterator.next() + result = next(self._iterator) except StopIteration: self._completeWith(TaskDone(), self._iterator) except: --- 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] 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/defer.py (original) +++ twisted/internet/defer.py (refactored) @@ -171,8 +171,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) @@ -597,7 +597,7 @@ while 1: try: - result = g.next() + result = next(g) except StopIteration: deferred.callback(result) return deferred @@ -748,7 +748,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/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) @@ -94,7 +94,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: @@ -149,7 +149,7 @@ try: l = self._poller.poll(timeout) - except SelectError, e: + except SelectError as e: if e[0] == errno.EINTR: return else: --- twisted/internet/tcp.py (original) +++ twisted/internet/tcp.py (refactored) @@ -144,13 +144,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): @@ -188,14 +189,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 @@ -244,7 +245,7 @@ # shutdown) try: ZE: - 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/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/reactor.py (original) +++ twisted/internet/iocpreactor/reactor.py (refactored) @@ -38,7 +38,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/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") 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/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/test/test_base.py (original) +++ twisted/internet/test/test_base.py (refactored) @@ -6,7 +6,7 @@ """ import socket -from Queue import Queue +from queue import Queue from zope.interface import implements --- twisted/internet/test/test_fdset.py (original) +++ twisted/internet/test/test_fdset.py (refactored) @@ -38,7 +38,7 @@ client.setblocking(False) try: client.connect(('127.0.0.1', serverSocket.getsockname()[1])) - except socket.error, e: + except socket.error as e: self.assertIn(e.args[0], (EINPROGRESS, EWOULDBLOCK)) else: self.fail("Connect should have raised EINPROGRESS or EWOULDBLOCK") --- twisted/lore/default.py (original) +++ twisted/lore/default.py (refactored) @@ -24,9 +24,9 @@ try: fp = open(options['template']) templ = dom.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) @@ -40,7 +40,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 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 @@ -262,7 +263,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: @@ -450,7 +451,7 @@ """ try: data = self.socket.recv(self.bufferSize) - except socket.error, se: + except socket.error as se: if se.args[0] == EWOULDBLOCK: return else: @@ -472,7 +473,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): @@ -638,7 +639,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: @@ -692,13 +693,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) @@ -851,8 +852,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. @@ -872,7 +873,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) @@ -896,7 +898,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 @@ -1003,10 +1005,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/test/test_process.py (original) +++ twisted/internet/test/test_process.py (refactored) @@ -158,9 +158,10 @@ reactor.spawnProcess, Exiter(), sys.executable, [sys.executable, "-c", source], usePTY=self.usePTY) - def cbExited((failure,)): + def cbExited(xxx_todo_changeme): # Trapping implicitly 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/iocpreactor/tcp.py (original) +++ twisted/internet/iocpreactor/tcp.py (refactored) @@ -265,17 +265,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) @@ -489,8 +489,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/lore/lint.py (original) +++ twisted/lore/lint.py (refactored) @@ -6,7 +6,7 @@ """ from xml.dom import minidom as dom -import parser, urlparse, os.path +import parser, urllib.parse, os.path from twisted.lore import tree, process from twisted.web import domhelpers @@ -30,7 +30,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): @@ -124,18 +124,18 @@ # Fix < and > text = text.replace('>', '>').replace('<', '<') # 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)) @@ -151,7 +151,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, @@ -164,7 +164,7 @@ node.getAttribute('href')) lines = open(fn).readlines() lines = lines[int(node.getAttribute('skipLines', 0)):] - for line, num in zip(lines, range(len(lines))): + .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_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/htmlbook.py (original) +++ twisted/lore/htmlbook.py (refactored) @@ -24,7 +24,7 @@ Index = self.Index if filename: - execfile(filename) + exec(compile(open(filename).read(), filename, 'exec')) def getFiles(self): return [c[0] for c in self.chapters] --- twisted/lore/latex.py (original) +++ twisted/lore/latex.py (refactored) @@ -7,13 +7,13 @@ from xml.dom import minidom as dom import os.path, re, string -from cStringIO import StringIO -import urlparse +from io import StringIO +import urllib.parse from twisted.web import domhelpers from twisted.python import text, procutils -import tree +from . import tree escapingRE = re.compile(r'([\[\]#$%&_{}^~\\])') lowerUpperRE = re.compile(r'([a-z])([A-Z])') @@ -51,11 +51,11 @@ if hasattr(node, 'eref'): return writer(entities.get(node.eref, '')) if hasattr(node, 'data'): - if isinstance(node.data, unicode): + if isinstance(node.data, str): data = node.data.encode('utf-8') else: data = node.data - return writer(filter(data)) + return writer(list(filter(data))) for child in node.childNodes: getLatexText(child, writer, filter, entities) @@ -207,7 +207,7 @@ def visitNode_a_listing(self, node): fileName = os.path.join(self.currDir, node.getAttribute('href')) self.writer 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(): @@ -283,7 +284,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) @@ -330,7 +332,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/lore/tree.py (original) +++ twisted/lore/tree.py (refactored) @@ -3,7 +3,7 @@ from itertools import count -import re, os, cStringIO, time, cgi, string, urlparse +import re, os, io, time, cgi, string, urllib.parse from xml.dom import minidom as dom from xml.sax.handler import ErrorHandler, feature_validation from xml.dom.pulldom import SAX2DOM @@ -15,7 +15,7 @@ from twisted.python.deprecate import deprecated from twisted.python.versions import Version from twisted.web import domhelpers -import process, latex, indexer, numberer, htmlbook +from . import process, latex, indexer, numberer, htmlbook # relative links to html files def fixLinks(document, ext): @@ -42,7 +42,7 @@ supported_schemes=['http', 'https', 'ftp', 'mailto'] for node in domhelpers.findElementsWithAttribute(document, 'href'): href = node.getAttribute("href") - if urlparse.urlparse(href)[0] in supported_schemes: + if urllib.parse.urlparse(href)[0] in supported_schemes: continue if node.getAttribute("class") == "absolute": continue @@ -158,12 +158,12 @@ @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') + oldio = io.StringIO(oldio.getvalue().strip()+'\n') howManyLines = len(oldio.getvalue().splitlines()) - newio = cStringIO.StringIO() + newio = io.StringIO() htmlizer.filter(oldio, newio, writer=htmlizer.SmallerHTMLWriter) lineLabels = _makeLineNumbers(howManyLines) newel = dom.parseString(newio.getvalue()).documentElement @@ -198,15 +198,15 @@ 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())) skip = node.getAttribute('skipLines') or 0 lines = lines[int(skip):] howManyLines = len(lines) data = '\n'.join(lines) - data = cStringIO.StringIO(text.removeLeadingTrailingBlanks(data)) + data = io.StringIO(text.removeLeadingTrailingBlanks(data)) htmlizer.filter(data, outfile, writer=htmlizer.SmallerHTMLWriter) sourceNode = dom.parseString(outfile.getvalue()).documentElement sourceNode.insertBefore(_makeLineNumbers(howManyLines), sourceNode.firstChild) @@ -341,7 +341,7 @@ else: subHeaders.append(element) - auto = count().next + auto = count().__next__ def addItem(headerElement, parent): anchor = dom.Element('a') @@ -614,7 +614,7 @@ indexer.addEntry(filename, anchor, entry.getAttribute('value'), ref) # does nodeName even affect anything? entry.nodeName = entr 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/texi.py (original) +++ twisted/lore/texi.py (refactored) @@ -3,11 +3,11 @@ # -from cStringIO import StringIO +from io import StringIO import os, re from twisted.python import text from twisted.web import domhelpers -import latex, tree +from . import latex, tree spaceRe = re.compile('\s+') --- twisted/lore/scripts/lore.py (original) +++ twisted/lore/scripts/lore.py (refactored) @@ -73,12 +73,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): @@ -133,7 +133,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' @@ -141,14 +141,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_lint.py (original) +++ twisted/lore/test/test_lint.py (refactored) @@ -7,7 +7,7 @@ import sys from xml.dom import minidom -from StringIO import StringIO +from io import StringIO from twisted.trial.unittest import TestCase from twisted.lore.lint import getDefaultChecker --- 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 '' % (map(str, self.objs),) + return '' % (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/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() + y.tagName = entry.endTagName = 'a' - for attrName in entry.attributes.keys(): + for attrName in list(entry.attributes.keys()): entry.removeAttribute(attrName) entry.setAttribute('name', anchor) @@ -645,7 +645,7 @@ link.parentNode.removeChild(link) else: link.nodeName = link.tagName = link.endTagName = 'a' - for attrName in link.attributes.keys(): + for attrName in list(link.attributes.keys()): link.removeAttribute(attrName) link.setAttribute('href', indexFilename) @@ -1068,7 +1068,7 @@ try: try: parser.parse(fObj) - except IOError, e: + except IOError as e: raise process.ProcessingFailure( e.strerror + ", filename was '" + filename + "'") finally: --- 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 @@ -78,11 +78,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() @@ -188,7 +188,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. @@ -238,7 +238,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: @@ -259,7 +260,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 @@ -333,10 +334,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: @@ -388,7 +390,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): @@ -460,7 +462,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., spitter) --- 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/lmath.py (original) +++ twisted/lore/lmath.py (refactored) @@ -9,7 +9,7 @@ from xml.dom import minidom as dom from twisted.web import domhelpers -import latex, tree, lint, default +from . import latex, tree, lint, default class MathLatexSpitter(latex.LatexSpitter): --- 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) @@ -45,7 +45,7 @@ from xml.dom import minidom as dom import os.path, re -from cStringIO import StringIO +from io import StringIO from twisted.lore import default from twisted.web import domhelpers @@ -271,16 +271,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/test/test_lore.py (original) +++ twisted/lore/test/test_lore.py (refactored) @@ -31,7 +31,7 @@ # import os, shutil, errno, time -from StringIO import StringIO +from io import StringIO from xml.dom import minidom as dom from twisted.trial import unittest @@ -863,7 +863,7 @@ parent = dom.Element('body') header = dom.Element('h2') text = dom.Text() - text.data = u'header & special character' + text.data = 'header & special character' header.appendChild(text) parent.appendChild(header) subheader = dom.Element('h3') @@ -1090,7 +1090,7 @@ # appropriate unicode codepoint. self.assertEqual( domhelpers.gatherTextNodes(document.documentElement), - u"uses an xhtml entity: \N{COPYRIGHT SIGN}") + "uses an xhtml entity: \N{COPYRIGHT SIGN}") def test_withTransitionalDocType(self): @@ -1108,7 +1108,7 @@ # appropriate unicode codepoint. self.assertEqual( domhelpers.gatherTextNodes(document.documentElement), - u"uses an xhtml entity: \N{COPYRIGHT SIGN}") + "uses an xhtml entity: \N{COPYRIGHT SIGN}") def test_withStrictDocType(self): @@ -1126,7 +1126,7 @@ # appropriate unicode codepoint. self.assertEqual( domhelpers.gatherTextNodes(document.documentElement), - u"uses an xhtml entity: \N{COPYRIGHT SIGN}") + "uses an xhtml entity: \N{COPYRIGHT SIGN}") def test_withDisallowedDocType(self): @@ -1157,14 +1157,14 @@ document = dom.Document() parent = dom.Element('foo') text = dom.Text() - text.data = u'\N{SNOWMAN}' + text.data = '\N{SNOWMAN}' parent.appendChild(text) document.appendChild(parent) outFile = self.mktemp() tree._writeDocument(outFile, document) self.assertXMLEqual( FilePath(outFile).getContent(), - u'\N{SNOWMAN}'.encode('utf-8')) + '\N{SNOWMAN}'.encode('utf-8')) @@ -1181,7 +1181,7 @@ out = StringIO() spitter = LatexSpitter(out.write) spitter.visitNode(doc) - self.assertEqual(out.getvalue(), u'\\index{name}\n') + self.assertEqual(out.getvalue(), '\\index{name}\n') --- 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 re 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/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/test/pop3testserver.py (original) +++ twisted/mail/test/pop3testserver.py (refactored) @@ -227,7 +227,7 @@ """ def printMessage(msg): - print "Server Starting in %s mode" % msg + print("Server Starting in %s mode" % msg) def processArg(arg): @@ -288,11 +288,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 postmaster: return None name = 'postmaster' --- 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/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): @@ -313,7 +313,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 @@ -322,7 +322,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: @@ -380,12 +380,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 = [] @@ -393,7 +393,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:] @@ -403,15 +403,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]) @@ -432,7 +432,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] == '"': @@ -644,7 +644,7 @@ try: addr = Address(m.group('path'), self.host) - except AddressError, e: + except AddressError as e: self.sendCode(553, str(e)) return @@ -682,7 +682,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 @@ -737,7 +737,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) @@ -821,7 +821,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() @@ -843,10 +843,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 @@ -1107,7 +1108,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, '') @@ -1117,7 +1118,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') @@ -1222,7 +1223,7 @@ raise NotImplementedError def _disconnectFromServer(self): - self._expected = xrange(0, 1000) + self._expected = range(0, 1000) self._okresponse = self.smtpState_disconnect self.sendLine('QUIT') @@ -1405,7 +1406,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 @@ -1449,7 +1450,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 @@ -1462,7 +1463,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 @@ -1679,9 +1680,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) + + if isinstance(toEmail, str): toEmail = [toEmail] self.fromEmail = Address(fromEmail) self.nEmails = len(toEmail) @@ -1944,10 +1945,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/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('\\begin{verbatim}\n') - lines = map(string.rstrip, open(fileName).readlines()) + lines = list(map(string.rstrip, open(fileName).readlines())) skipLines = int(node.getAttribute('skipLines') or 0) lines = lines[skipLines:] self.writer(text.removeLeadingTrailingBlanks('\n'.join(lines))) @@ -225,7 +225,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: @@ -366,7 +366,7 @@ start_q = "``" end_q = "''" - writeNodeData = LatexSpitter.writeNodeData.im_func + writeNodeData = LatexSpitter.writeNodeData.__func__ class FootnoteLatexSpitter(LatexSpitter): --- twisted/lore/test/test_latex.py (original) +++ twisted/lore/test/test_latex.py (refactored) @@ -25,11 +25,11 @@ """ node = Element('foo') text = Text() - text.data = u"foo \N{SNOWMAN}" + text.data = "foo \N{SNOWMAN}" node.appendChild(text) result = [] getLatexText(node, result.append) - self.assertEqual(result, [u"foo \N{SNOWMAN}".encode('utf-8')]) + self.assertEqual(result, ["foo \N{SNOWMAN}".encode('utf-8')]) --- 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) @@ -359,7 +359,7 @@ N = len(names) if (N >= 1 and names[0] in self._1_RESPONSES or N >= 2 and names[1] in self._2_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(names) else: unuse.append(names) @@ -508,7 +508,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 @@ -573,7 +573,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() @@ -595,11 +595,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): @@ -622,7 +622,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, @@ -640,7 +640,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) @@ -783,7 +784,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): @@ -901,7 +902,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): @@ -954,7 +955,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] @@ -980,7 +981,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' @@ -1050,7 +1052,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,)) @@ -1082,7 +1085,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') @@ -1156,7 +1159,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") @@ -1177,7 +1180,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") @@ -1189,7 +1192,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 @@ -1197,7 +1200,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") @@ -1212,7 +1215,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") @@ -1227,7 +1230,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") @@ -1250,7 +1253,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,)) @@ -1288,7 +1291,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') @@ -1418,7 +1421,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') @@ -1427,7 +1430,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())) @@ -1622,7 +1625,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. @@ -1828,7 +1831,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: @@ -1932,7 +1935,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) @@ -2072,7 +2075,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) @@ -2152,7 +2155,7 @@ if octets > self._memoryFileLimit: return tempfile.TemporaryFile() else: - return StringIO.StringIO() + return io.StringIO() def makeTag(self): tag = '%0.4X' % self.tagID @@ -2300,7 +2303,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: for cap in rest[1:]: @@ -2333,7 +2337,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 @@ -2352,9 +2357,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): @@ -2427,13 +2433,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) @@ -2462,7 +2468,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): @@ -2567,7 +2573,8 @@ d.addCallback(self.__cbNamespace) return d - def __cbNamespace(self, (lines, last)): + def __cbNamespace(self, xxx_todo_changeme6): + (lines, last) = xxx_todo_changeme6 for parts in lines: if len(parts) == 4 and parts[0] == 'NAMESPACE': return [e or [] for e in parts[1:]] @@ -2663,14 +2670,13 @@ raise IllegalServerResponse(phrase) - def __cbSelect(self, (lines, tagline), rw): + def __cbSelect(self, xxx_todo_changeme7, rw): """ Handle lines received in response to a SELECT or EXAMINE command. See RFC 3501, section 6.3.1. """ - # In the absense of specification, we are free to assume: - # READ-WRITE access + (lines, tagline) = xxx_todo_changeme7 datum = {'READ-WRITE': rw} lines.append(parseNestedParens(tagline)) for split in lines: @@ -2834,7 +2840,8 @@ 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 parts in lines: if len(parts) == 4 and parts[0] == command: @@ -2870,19 +2877,20 @@ d.addCallback(self.__cbStatus) return d - def __cbStatus(self, (lines, last)): + def __cbStatus(self, xxx_todo_changeme9): + (lines, last) = xxx_todo_changeme9 status = {} for parts in lines: if parts[0] == 'STATUS': 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 @@ -2982,7 +2990,8 @@ return d - def __cbExpunge(self, (lines, last)): + def __cbExpunge(self, xxx_todo_changeme10): + (lines, last) = xxx_todo_changeme10 ids = [] for parts in lines: if len(parts) == 2 and parts[1] == 'EXPUNGE': @@ -3017,7 +3026,8 @@ return d - def __cbSearch(self, (lines, end)): + def __cbSearch(self, xxx_todo_changeme11): + (lines, end) = xxx_todo_changeme11 ids = [] for parts in lines: if len(parts) > 0 and parts[0] == 'SEARCH': @@ -3354,12 +3364,12 @@ responseParts = iter(fetchResponseList) while True: try: - key = responseParts.next() + key = next(responseParts) except StopIteration: break try: - value = responseParts.next() + value = next(responseParts) except StopIteration: raise IllegalServerResponse( "Not enough arguments", fetchResponseList) @@ -3386,7 +3396,7 @@ else: key = (key, (value[0], tuple(value[1]))) try: - value = responseParts.next() + value = next(responseParts) except StopIteration: raise IllegalServerResponse( "Not enough arguments", fetchResponseList) @@ -3395,7 +3405,7 @@ if value.startswith('<') and value.endswith('>'): key = key + (value,) try: - value = responseParts.next() + value = next(responseParts) except StopIteration: raise IllegalServerResponse( "Not enough arguments", fetchResponseList) @@ -3404,7 +3414,8 @@ return values - def _cbFetch(self, (lines, last), requestedParts, structured): + def _cbFetch(self, xxx_todo_changeme12, requestedParts, structured): + (lines, last) = xxx_todo_changeme12 info = {} for parts in lines: if len(parts) == 3 and parts[1] == 'FETCH': @@ -3415,14 +3426,14 @@ info[id][0].extend(parts[2]) results = {} - for (messageId, values) in info.iteritems(): + for (messageId, values) in info.items(): mapping = self._parseFetchPairs(values[0]) results.setdefault(messageId, {}).update(mapping) flagChanges = {} - for messageId in results.keys(): + for messageId in list(results.keys()): values = results[messageId] - for part in values.keys(): + for part in list(values.keys()): if part not in requestedParts and part == 'FLAGS': flagChanges[messageId] = values['FLAGS'] # Find flags in the result and get rid of them. @@ -3534,9 +3545,9 @@ 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',))) - d.addCallback(self._cbFetch, map(str.upper, terms.keys()), True) + d.addCallback(self._cbFetch, list(map(str.upper, list(terms.keys()))), True) return d def setFlags(self, messages, flags, silent=1, uid=0): @@ -3683,11 +3694,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) @@ -3696,7 +3707,7 @@ if p == '*': p = None else: - p = long(p) + p = int(p) except ValueError: raise IllegalIdentifierError(p) else: @@ -3824,7 +3835,7 @@ @return: The formatted query string """ cmd = [] - keys = kwarg.keys() + keys = list(kwarg.keys()) if sorted: keys.sort() for k in keys: @@ -3846,7 +3857,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: @@ -3957,14 +3968,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)) @@ -4014,7 +4025,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 @@ -4092,9 +4103,9 @@ for i in items: if i is None: pieces.extend([' ', 'NIL']) - elif isinstance(i, (DontQuoteMe, int, long)): + elif isinstance(i, (DontQuoteMe, 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: @@ -4391,15 +4402,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])) @@ -4428,9 +4439,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 @@ -4441,15 +4452,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] @@ -4457,7 +4468,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 @@ -4473,7 +4484,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): @@ -4571,7 +4582,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 @@ -4619,7 +4630,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') @@ -4964,7 +4975,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 @@ -4992,7 +5003,7 @@ d = defer.Deferred() def go(last): try: - r = i.next() + r = next(i) except StopIteration: d.callback(last) except: @@ -5365,7 +5376,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): @@ -5380,7 +5391,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 @@ -5443,14 +5454,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, -actor reactor.callLater(30, setWaiting, self.queue, self.managed[factory]) del self.managed[factory] --- 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)"' % (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/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) @@ -472,7 +472,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) @@ -628,10 +628,10 @@ smtp.Address(''), ['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') @@ -640,7 +640,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') @@ -681,7 +681,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() @@ -763,7 +763,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() @@ -834,7 +834,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[:] @@ -1404,7 +1404,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) @@ -1514,7 +1514,7 @@ return done -aliasFile = StringIO.StringIO("""\ +aliasFile = io.StringIO("""\ # Here's a comment # woop another one testuser: address1,address2, address3, @@ -1763,7 +1763,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() @@ -1872,34 +1872,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( 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 __inialiases) - 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) @@ -1927,11 +1927,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) @@ -1963,6 +1963,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) and issubclass(o, unittest.TestCase): o.skip = "twisted.mail only works on posix" --- 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 = '' 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/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 factort__(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/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(dy = 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/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(compile(open(filename).read(), filename, 'exec'), 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 ct.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/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) @@ -234,7 +234,7 @@ self, 'key_%s' % ksym, lambda *a, **kw: None)(entry, event) if self.__debug: - print ksym + print(ksym) return rvalue def getText(self): @@ -251,7 +251,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. @@ -259,7 +259,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: @@ -350,7 +350,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/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] = 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 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 @@ -50,19 +50,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 ] @@ -72,7 +72,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')) @@ -94,7 +94,7 @@ reader class. """ reader = codecs.getreader('imap4-utf-7')(StringIO('Hello&AP8-world')) - self.assertEquals(reader.read(), u'Hello\xffworld') + self.assertEquals(reader.read(), 'Hello\xffworld') def test_getwriter(self): @@ -104,7 +104,7 @@ """ output = StringIO() writer = codecs.getwriter('imap4-utf-7')(output) - writer.write(u'Hello\xffworld') + writer.write('Hello\xffworld') self.assertEquals(output.getvalue(), 'Hello&AP8-world') @@ -132,7 +132,7 @@ characters which are in ASCII using the corresponding ASCII byte. """ # 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'), '&-') @@ -1152,7 +1152,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() @@ -1171,7 +1171,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): @@ -1250,7 +1250,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 @@ -1289,7 +1289,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]) @@ -1769,7 +1769,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) @@ -3050,11 +3050,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): @@ -3527,7 +3527,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) @@ -3607,7 +3607,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 = [] @@ -3635,10 +3635,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) @@ -3674,7 +3674,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) @@ -3805,7 +3805,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/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 Exceptio1) @@ -5481,7 +5492,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/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): @@ -497,7 +497,7 @@ data = transport.value() transport.clear() 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] == '.': @@ -510,7 +510,7 @@ transport.clear() 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] @@ -645,7 +645,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/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) @@ -120,7 +120,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 @@ -152,7 +152,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/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/test/tesupported" % 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/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 sgetattr(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/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/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/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.liveMn 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: @@ -97,7 +97,7 @@ def makeService(config): - import client, cache, hosts + from . import client, cache, hosts ca, cl = [], [] if config['cache']: --- 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 @@ -23,6 +23,7 @@ from twisted.names.client import Resolver from twisted.names.test.test_client import StubPort +from functools import reduce def justPayload(results): return [r.payload for r in results[0]] @@ -197,9 +198,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(list(map(str, results))), list(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(list(map(str, r)))) d.addBoth(setDone) d.addCallback(checkResults) @@ -386,7 +387,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(list(test_domain_com.records.values())))] for r in results: if r.ttl is None: r.ttl = default_ttl --- 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/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/test/test_ethernet.py (original) +++ twisted/pair/test/test_ethernet.py (refactored) @@ -182,7 +182,7 @@ except components.CannotAdapt: pass else: - raise Aself.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/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 whsertionError, '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_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 protocessages.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/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/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_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' + raist_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/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 = ise 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/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} ofo.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/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) @@ -139,7 +139,7 @@ def doUpgrade(): global versionedsToUpgrade, upgraded - for versioned in versionedsToUpgrade.values(): + for versioned in list(versionedsToUpgrade.values()): requireUpgrade(versioned) versionedsToUpgrade = {} upgraded = {} @@ -197,11 +197,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 @@ -214,7 +214,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 @@ -229,7 +229,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 @@ -239,7 +239,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/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).isfilat 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/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 follo 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/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/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 = "ol 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/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/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() @@ -164,7 +164,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) @@ -205,9 +205,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/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/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/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/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) @@ -17,6 +17,7 @@ from twisted.internet.protocol import ServerFactory, Protocol, ClientFactory from twisted.internet import error from twisted.python import log +from functools import reduce class ProtocolWrapper(Protocol): @@ -135,7 +136,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(list(map(len, seq))))) ProtocolWrapper.writeSequence(self, seq) def dataReceived(self, data): @@ -176,7 +177,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 @@ -242,7 +243,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() @@ -252,7 +253,7 @@ """ self.unthrottleReadsID = None log.msg("Stopped throttling reads on %s" % self) - for p in self.protococommand" - 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/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/loopback.py (original) +++ twisted/protocols/loopback.py (refactored) @@ -39,7 +39,7 @@ d.callback(None) - def __nonzero__(self): + def __bool__(self): return bool(self._queue) --- twisted/protocols/pcp.py (original) +++ twisted/protocols/pcp.py (refactored) @@ -13,6 +13,7 @@ from zope.interface import implements from twisted.internet import interfaces +from functools import reduce class BasicProducerConsumerProxy: --- twisted/protocols/shoutcast.py (original) +++ twisted/protocols/shoutcast.py (refactored) @@ -104,8 +104,8 @@ 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") --- 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:ws::") - 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/protocols/ftp.py (original) +++ twisted/protocols/ftp.py (refactored) @@ -19,6 +19,7 @@ import errno import fnmatch import warnings +from functools import reduce try: import pwd, grp @@ -649,7 +650,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 @@ -661,7 +662,7 @@ dtpInstance = None binary = True - passivePortRange = xrange(0, 1) + passivePortRange = range(0, 1) listenFactory = reactor.listenTCP @@ -813,7 +814,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 @@ -858,7 +860,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] @@ -913,7 +915,7 @@ try: segments = toSegments(self.workingDirectory, path) - except InvalidPath, e: + except InvalidPath as e: return defer.fail(FileNotFoundError(path)) d = self.shell.list( @@ -931,7 +933,7 @@ try: segments = toSegments(self.workingDirectory, path) - except InvalidPath, e: + except InvalidPath as e: return defer.fail(FileNotFoundError(path)) def cbList(results): @@ -965,7 +967,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)) @@ -1113,7 +1115,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) @@ -1125,7 +1128,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) @@ -1269,7 +1273,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 @@ -1582,7 +1586,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() @@ -1607,7 +1611,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() @@ -1620,7 +1624,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() @@ -1658,7 +1662,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() @@ -1738,7 +1742,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() @@ -1755,7 +1759,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() @@ -1772,7 +1776,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() @@ -1785,7 +1789,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) exe(): 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 @@ -525,7 +525,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 @@ -648,7 +648,7 @@ _failAllReason = None _outstandingRequests = None - _counter = 0L + _counter = 0 boxSender = None def __init__(self, locator): @@ -681,7 +681,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) @@ -1448,10 +1448,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 @@ -1479,7 +1479,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) @@ -2329,7 +2329,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/postfix.py (original) +++ twisted/protocols/postfix.py (refactored) @@ -8,7 +8,7 @@ import sys import UserDict -import urllib +import urllib.request, urllib.parse, urllib.error from twisted.protocols import basic from twisted.protocols import policies @@ -18,10 +18,10 @@ # 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/sip.py (original) +++ twisted/protocols/sip.py (refactored) @@ -48,7 +48,7 @@ } longHeaders = {} -for k, v in shortHeaders.items(): +for k, v in list(shortHeaders.items()): longHeaders[v] = k del k, v @@ -316,7 +316,7 @@ elif self.rportValue is not None: s += ";rport=%s" % (self.rport,) - etc = self.otherParams.items() + etc = list(self.otherParams.items()) etc.sort() for k, v in etc: if v is None: @@ -340,7 +340,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(":") @@ -415,7 +415,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): @@ -556,12 +556,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" @@ -654,7 +654,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: @@ -774,8 +774,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 @@ -813,7 +814,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)) @@ -906,7 +907,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() @@ -917,7 +918,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 @@ -926,6 +927,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) @@ -1102,12 +1104,12 @@ 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() @@ -1152,32 +1154,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. cept: return defer.fail() @@ -1801,7 +1805,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() @@ -2638,7 +2642,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/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) @@ -264,7 +264,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)) @@ -287,7 +287,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) @@ -312,7 +312,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/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. - 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/tls.py (original) +++ twisted/protocols/tls.py (refactored) @@ -42,7 +42,7 @@ try: Connection(Context(TLSv1_METHOD), None) -except TypeError, e: +except TypeError as e: if str(e) != "argument must be an int, or have a fileno() method.": raise raise ImportError("twisted.protocols.tls requires pyOpenSSL 0.10 or newer.") @@ -204,7 +204,7 @@ # Failure's are fat. Drop the reference. self._reason = None ProtocolWrapper.connectionLost(self, failure) - except Error, e: + except Error as e: # Something went pretty wrong. For example, this might be a # handshake failure (because there were no shared ciphers, because # a certificate failed to verify, etc). TLS can no longer proceed. @@ -295,7 +295,7 @@ self._writeBlockedOnRead = True self._appSendBuffer.append(leftToSend) break - except Error, e: + except Error as e: # Just drop the connection. This has two useful consequences. # First, for the application protocol's connectionLost method, # it will squash any error into connection lost. We *could* --- twisted/protocols/gps/rockwell.py (original) +++ twisted/protocols/gps/rockwell.py (refactored) @@ -24,6 +24,7 @@ import struct, operator, math from twisted.internet import protocol from twisted.python import log +from functools import reduce DEBUG = 1 @@ -189,7 +190,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(' 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/logfile.py (original) +++ twisted/python/logfile.py (refactored) @@ -65,7 +65,7 @@ else: if self.defaultMode is not None: # Set the lowest permissi 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/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: @@ -38,7 +38,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: @@ -68,7 +68,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 @@ -123,7 +123,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 @@ -132,13 +132,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 @@ -150,13 +150,13 @@ try: if kill is not None: 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/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 fromf.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/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/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) @@ -7,7 +7,7 @@ """ import tokenize, cgi, keyword -import reflect +from . import reflect class TokenPrinter: @@ -17,10 +17,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 @@ -85,7 +87,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/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: @@ -631,7 +631,7 @@ # Some more sibling imports, at the bottom and unqualified to avoid # unresolvable circularity -import threadable, failure +from . import threadable, failure threadable.synchronize(LogPublisher) --- 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: + 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/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/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: thons - 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/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/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) @@ -132,7 +132,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. @@ -153,7 +153,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/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: 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 Exception: 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/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/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, """ 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/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)) @@ -166,7 +166,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 @@ -196,14 +196,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): """ @@ -332,7 +332,7 @@ def __getstate__(self): d = self.__dict__.copy() - if d.has_key('statinfo'): + if 'statinfo' in d: del d['statinfo'] return d @@ -622,7 +622,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) @@ -771,7 +771,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/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/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()): 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/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) readmodule = None --- 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/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') @@ -370,20 +370,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 @@ -437,7 +437,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] @@ -491,11 +491,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] @@ -522,7 +522,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: @@ -565,7 +565,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] @@ -592,7 +592,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] @@ -639,7 +639,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: @@ -670,14 +670,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() @@ -730,7 +730,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 @@ -755,7 +755,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 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/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/test/test_htmlizer.py (original) +++ twisted/python/test/test_htmlizer.py (refactored) @@ -5,7 +5,7 @@ Tests for L{twisted.python.htmlizer}. """ -from StringIO import StringIO +from io import StringIO from twisted.trial.unittest import TestCase from twisted.python.htmlizer import filter @@ -22,7 +22,7 @@ """ input = StringIO("") output = StringIO() - filter(input, output) + list(filter(input, output)) self.assertEqual(output.getvalue(), '
\n') @@ -34,7 +34,7 @@ """ input = StringIO("foo\n") output = StringIO() - filter(input, output) + list(filter(input, output)) self.assertEqualfunc, args, kwargs): try: - result = apply(func, args, kwargs) + result = func(*args, **kwargs) except: errback(sys.exc_info()[1]) 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/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): @@ -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,10 +462,10 @@ 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): @@ -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') @@ -525,14 +525,14 @@ 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): @@ -540,10 +540,10 @@ 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 + return int def getDescription(self, long): """ @@ -551,15 +551,15 @@ @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.optPa( output.getvalue(), '
foo\n'
--- 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/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 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
@@ -564,18 +564,18 @@
         if opt.get('long', None):
             long = opt['long']
             if opt.get("optType", None) == "parameter":
-                long = long + '='
-
-            long = "%-*s" % (maxOptLen, long)
+                long = int + '='
+
+            long = "%-*s" % (maxOptLen, int)
             if short:
                 comma = ","
         else:
             long = " " * (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/test/test_zipstream.py (original)
+++ twisted/python/test/test_zipstream.py (refactored)
@@ -63,9 +63,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):
@@ -82,7 +82,7 @@
         """
         fileEntry = self.getFileEntry('')
         self.assertIdentical(iter(fileEnrams_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
+        return int # we really ought to have a good description to use
 
     def getShortOption(self, long):
         """
         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():
+        for methodName, methodObj in list(methodsDict.items()):
             long = 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_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):
@@ -146,7 +146,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)
@@ -234,12 +235,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))
@@ -264,8 +265,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']
@@ -275,8 +276,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']
@@ -324,7 +325,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)
 
@@ -362,82 +364,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          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)
@@ -109,7 +109,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'] = {}
@@ -118,7 +118,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)
@@ -162,7 +162,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)
@@ -170,25 +170,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]\n")
-        print synopsis
+        print(synopsis)
         for p in plugin.getPlugins(itrial.IReporter):
-            print '   ', p.longOpt, '\t', p.description
-        print
+       ), (10, None))
         self.assertRaises(ValueError, d.removeInterval, 10)
 
 
@@ -758,7 +760,7 @@
         util.setIDFunction(fakeId)
 
         self.assertEquals(util.unsignedID(foo), 17)
-        self.assertEquals(util.unsignedID(bar), (sys.maxint + 1) * 2 - 73)
+        self.assertEquals(util.unsignedID(bar), (sys.maxsize + 1) * 2 - 73)
 
 
     def test_defaultIDFunction(self):
@@ -768,6 +770,6 @@
         obj = object()
         idValue = id(obj)
         if idValue < 0:
-            idValue += (sys.maxint + 1) * 2
+            idValue += (sys.maxsize + 1) * 2
 
         self.assertEquals(util.unsignedID(obj), idValue)
--- 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/mktap.py (original)
+++ twisted/scripts/mktap.py (refactored)
@@ -112,7 +112,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))
@@ -128,14 +128,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:
@@ -157,7 +157,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))
 
@@ -166,8 +166,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/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/test/test_mktap.py (original)
+++ twisted/scripts/test/test_mktap.py (refactored)
@@ -115,7 +115,7 @@
         plugins = loadPlugins()
         self.assertTrue(plugins, "There should be at least one plugin.")
         # Make sure the mapping is set up properly.
-        for k, v in plugins.iteritems():
+        for k, v in plugins.items():
             self.assertEqual(k, v.tapname)
 
         # Make sure one of the always-available builtin plugins is there. 
--- 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 @@
             el     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/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/ui/gtk2util.py (originalif 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):
             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/refpath.py (original)
+++ twisted/spread/refpath.py (refactored)
@@ -51,7 +51,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"):
@@ -60,8 +60,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"):
@@ -70,8 +69,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"):
@@ -80,8 +78,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
 
@@ -91,5 +88,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/tktree.py (original)
+++ twisted/spread/ui/tktree.py (refactored)
@@ -16,7 +16,7 @@
 """
 
 import    run_gtk2(config)
--- 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/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/spread/jelly.py (original)
+++ twisted/spread/jelly.py (refactored)
@@ -84,6 +84,7 @@
 
 import datetime
 from types import BooleanType
+from functools import reduce
 
 try:
     import decimal
@@ -161,7 +162,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 +264,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 +452,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 +481,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 +532,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(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 +634,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 +692,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 +724,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 +775,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 +787,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 +802,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 +849,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):
@@ -865,7 +866,7 @@
             raise InsecureJelly("module %s not allowed" % modName)
         klaus = namedObject(restof 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/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
 from xml.dom import minidom as dom
 
@@ -438,7 +438,7 @@
         replaceProjectVersion("test_project",
                               Version("twisted.test_project", 0, 82, 7))
         ns = {'__name___': 'twisted.test_project'}
-        execfile("test_project", ns)
+        exec(compile(open("test_project").read(), "test_project", 'exec'), 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(compile(open("test_project").read(), "test_project", 'exec'), ns)
         self.assertEquals(ns["version"].base(), "0.82.7pre8")
 
 
@@ -1203,7 +1203,7 @@
 
 
     def _setupTeXFiles(self):
-        sections = range(3)
+        sections = list(range(3))
         self._setupTeXSections(sections)
         return self._setupTeXBook(sections)
 
@@ -1353,7 +1353,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))
@@ -1370,7 +1370,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/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
-        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("",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/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)
+++ 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):
             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):
             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):
+            text = str(text)
         return self._statusBar.push(self._statusContext, text)
--- twisted/spread/ui/tkutil.py (original)
+++ twisted/spread/ui/tkutil.py (refactored)
@@ -4,9 +4,9 @@
 
 """Utilities for building L{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__ 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/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/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((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/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/proto_helpers.py (original)
+++ twisted/test/proto_helpers.py (refactored)
@@ -6,7 +6,7 @@
 Assorted functionality which is commonly useful when writing unit tests.
 """
 
-from StringIO import StringIO
+from io import StringIO
 
 from zope.interface import implements
 
@@ -25,11 +25,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)
 
@@ -128,7 +128,7 @@
 
     # ITransport
     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_application.py (original)
+++ twisted/test/test_application.py (refactored)
@@ -7,7 +7,7 @@
 """
 
 import sys, copy, os, pickle
-from StringIO import StringIO
+from io import StringIO
 
 from twisted.trial import unittest, util
 from twisted.application import service, internet, app
@@ -422,7 +422,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()
@@ -453,7 +453,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)
@@ -478,7 +478,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)
@@ -870,7 +870,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_defgen.py (original)
+++ twisted/test/test_defgen.py (refactored)
@@ -1,4 +1,4 @@
-from __future__ import generators, nested_scopes
+
 
 import sys
 
@@ -107,7 +107[0])
         objType = type(klaus)
-        if objType not in (types.ClassType, types.TypeType):
+        if objType not in (type, type):
             raise InsecureJelly(
                 "class %r unjellied to something that isn't a class: %r" % (
                     rest[0], klaus))
@@ -894,7 +895,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, {})
@@ -919,7 +920,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/test/iosim.py (original)
+++ twisted/test/iosim.py (refactored)
@@ -48,7 +48,7 @@
     implements(interfaces.ITransport,
                interfaces.ITLSTransport) # ha ha not really
 
-    _nextserial = itertools.count().next
+    _nextserial = itertools.count().__next__
     closed = 0
     disconnecting = 0
     disconnected = 0
@@ -216,18 +216,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:
@@ -237,14 +237,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/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_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')
     ,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 @@
     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_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.failUnlessEq()
+        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/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/test_amp.py (original)
+++ twisted/test/test_amp.py (refactored)
@@ -573,7 +573,7 @@
                                                    'print': "ignored",
                                                    '_answer': "1"}))
         self.assertEquals(answers, [dict(hello="yay",
-                                         Print=u"ignored")])
+                                         Print="ignored")])
 
 
 class SimpleGreeting(amp.Command):
@@ -1457,8 +1457,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_jelly.py (original)
+++ twisted/test/test_jelly.py (refactored)
@@ -130,7 +130,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):
@@ -387,7 +387,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(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)
@@ -182,7 +182,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):
@@ -207,7 +207,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_digestauth.py (original)
+++ twisted/test/test_digestauth.py (refactored)
@@ -271,7 +271,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])
 
 
--- 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_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_logfile.py (original)
+++ twisted/test/test_logfile.py (refactored)
@@ -27,9 +27,9 @@
         Restore back write rights on created paths: if tesual(arg_2_default, list(range(4)))
 
         self.failUnlessEqual(signature.get_name(3), 'kw')
         self.failUnless(signature.is_keyword(3))
--- 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_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)
@@ -860,9 +860,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)
@@ -909,7 +909,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)
@@ -988,7 +988,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()
 
@@ -1028,11 +1028,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
@@ -1157,9 +1157,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_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 @@
             ts 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_memcache.py (original)
+++ twisted/test/test_memcache.py (refactored)
@@ -415,12 +415,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])
 
 
@@ -428,7 +428,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_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 u        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_factories.py (original)
+++ twisted/test/test_factories.py (refactored)
@@ -42,7 +42,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_ftp.py (original)
+++ twisted/test/test_ftp.py (refactored)
@@ -293,7 +293,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
@@ -355,11 +355,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())
@@ -371,7 +371,7 @@
         their C{passivePortRange} attribute set to the same object the
         factory's C{passivePortRange} attribute is set to.
         """
-        portRange = xrange(2017, 2031)
+        portRange = range(2017, 2031)
         self.factory.passivePortRange = portRange
         protocol = self.factory.buildProtocol(None)
         self.assertEqual(portRange, protocol.wrappedProtocol.passivePortRange)
@@ -422,7 +422,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)
 
@@ -716,7 +717,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')
@@ -733,7 +735,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['finittest
 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_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
@@ -566,7 +566,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)
@@ -680,7 +680,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")
@@ -1366,12 +1366,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_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
@@ -184,10 +184,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)
@@ -204,10 +204,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):
@@ -222,10 +222,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)
         selcatcher), 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_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_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_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_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_protocols.py (original)
+++ twisted/test/test_protocols.py (refactored)
@@ -777,4 +777,4 @@
         Test that L{proto_helpers.StringTransport} doesn't accept unicode data.
         """
         s = proto_helpers.StringTransport()
- letype'] == 'd', 'misparsed fileitem')
@@ -758,7 +761,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))
@@ -1779,7 +1783,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_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
@@ -178,7 +178,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)
@@ -200,7 +200,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)
 
@@ -210,7 +210,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):
@@ -251,8 +251,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)
@@ -271,7 +271,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_policies.py (original)
+++ twisted/test/test_policies.py (refactored)
@@ -7,7 +7,7 @@
 
 from zope.interface import Interface, implements, implementedBy
 
-from StringIO import StringIO
+from io import StringIO
 
 from twisted.trial import unittest
 from twisted.test.proto_helpers import StringTransport
@@ -201,9 +201,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_reflect.py (original)
+++ twisted/test/test_reflect.py (refactored)
@@ -376,9 +376,9 @@
         o = Dummy()
         m = o.dummy
 
-        self.assertIn(".im_self", reflect.objgrep(m, m.im_self, reflect.isSame))
-        self.assert        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_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_paths.py (original)
+++ twisted/test/test_paths.py (refactored)
@@ -147,9 +147,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)
@@ -251,9 +251,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)
@@ -292,7 +292,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_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
@@ -205,7 +205,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)
@@ -438,11 +438,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
 
@@ -541,7 +541,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)
@@ -615,7 +615,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:
@@ -647,7 +647,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={}):
@@ -758,18 +758,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)
@@ -791,29 +791,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)
@@ -940,8 +940,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)
@@ -1252,7 +1252,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
 
 
@@ -2131,10 +2131,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_stdio.py (original)
+++ twisted/test/test_stdio.py (refactored)
@@ -154,7 +154,7 @@
             self._spawnProcess(
                 p, 'stdio_test_lastwrite.py', UNIQUE_LAST_WRITE_STRING,
                 usePTY=True)
-        except ValueError, e:
f.assertIdentical(type(inst), self.m.ListSubclass)
@@ -240,13 +240,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_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_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_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}))
+  In(".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):
         """
@@ -475,8 +475,7 @@
 
 
 
-class BTBase(Breakable):
-    __metaclass__ = BrokenType
+class BTBase(Breakable, metaclass=BrokenType):
     breakRepr = True
     breakStr = True
 
--- 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_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_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.app       self.assertRaises(TypeError, s.write, u'foo')
+        self.assertRaises(TypeError, s.write, 'foo')
--- 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)
@@ -489,7 +489,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
 
@@ -648,7 +648,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)
@@ -761,7 +761,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
 
@@ -789,7 +789,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_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_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_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 allConn+        except ValueError as e:
             # Some platforms don't work with usePTY=True
             raise unittest.SkipTest(str(e))
 
@@ -227,7 +227,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
@@ -242,7 +242,7 @@
         d = p.onCompletion
 
         written = []
-        toWrite = range(100)
+        toWrite = list(range(100))
 
         def connectionMade(ign):
             if toWrite:
--- 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),
                               "" % (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 und           {'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_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, io
 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)
 
 
 
@@ -735,7 +735,7 @@
 
 
     def _testStats(self, statsClass, profile):
-        out = StringIO.StringIO()
+        out = io.StringIO()
 
         # Patch before creating the pstats, because pstats binds self.stream to
         # sys.stdout early in 2.5 and newer.
--- 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/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/runner.py (original)
+++ twisted/trial/runner.py (refactored)
@@ -486,7 +486,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,))
@@ -510,7 +510,7 @@
         """
         if not isinstance(method,end(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_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_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/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/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_output.py (original)
+++ twisted/trial/test/test_output.py (refactored)
@@ -5,7 +5,7 @@
 Teserlying 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/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(
@@ -264,8 +264,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:
@@ -317,7 +317,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/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 waected((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/trial/unittest.py (original)
+++ twisted/trial/unittest.py (refactored)
@@ -181,7 +181,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
@@ -261,7 +261,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'
@@ -1002,7 +1002,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 = {}
 
@@ -1091,7 +1091,7 @@
 
                     if filename != os.path.normcase(aWarning.filename):
                         continue
-                    lineStarts = list(_findlinestarts(aFunction.func_code))
+                    lineStarts = list(_findlinestarts(aFunction.__code__))
                     first = lineStarts[0][1]
                     last = lineStarts[-1][1]
                     if not (first <= aWarning.lineno <= last):
@@ -1101,7 +1101,7 @@
                     toFlush.append(aWarning)
                     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/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,
 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)
@@ -600,7 +600,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)
@@ -683,7 +683,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):
@@ -699,16 +699,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/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_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_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 argumenrnings, 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_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 = runnerts 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_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_vts
         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_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/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:
+        ex.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_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/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"])
-erboseReporter(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/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                               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_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/web/domhelpers.py (original)
+++ twisted/web/domhelpers.py (refactored)
@@ -6,7 +6,7 @@
 A library for performing interesting tasks with DOM objects.
 """
 
-import StringIO
+import io
 
 from twisted.web import microdom
 from twisted.web.microdom import getElementsByTagName, escape, unescape
@@ -53,7 +53,7 @@
     """
     result = _get(node, nodeId)
     if result: return result
-    raise NodeLookupError, nodeId
+    raise NodeLookupError(nodeId)
 
 def getIfExists(node, nodeId):
     """
@@ -249,7 +249,7 @@
 
 
 def getNodeText(node):
-    oldio = StringIO.StringIO()
+    oldio = io 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/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/error.py (original)
+++ twisted/web/error.py (refactored)
@@ -86,7 +86,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)
 
 
 from twisted.web import resource as _resource
--- twisted/web/google.py (original)
+++ twisted/web/google.py (refactored)
@@ -4,7 +4,7 @@
 #
 """\"I'm Feeling Lucky\" with U{Google}.
 """
-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/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
@@ -137,7 +137,7 @@
     def __init__(self, rawHeaders=None):
         self._rawHeaders = {}
         if rawHeaders is not None:
-            for name, values in rawHeaders.iteritems():
+            for name, values in rawHeaders.items():
                 self.setRawHeaders(name, values)
 
 
@@ -239,7 +239,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/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
+fromcept ivfs.VFSError as e:
             return vfsToFtpError(e)
         except:
             return defer.fail()
--- 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/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.python import log
 from twisted.web import http
@@ -44,13 +44,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))
@@ -294,7 +294,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]
@@ -333,7 +333,7 @@
                  timeout=0, cookies=None, followRedirect=1,
                  redirectLimit=20):
         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):
@@ -379,7 +379,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:
             try:
                 if not self.file:
--- twisted/web/resource.py (original)
+++ twisted/web/resource.py (refactored)
@@ -88,10 +88,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()
@@ -109,7 +109,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
--- twisted/web/script.py (original)
+++ twisted/web/sc.StringIO()
     writeNodeData(node, oldio)
     return oldio.getvalue()
 
--- 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 
 tags around some text and HTML-escape it."
--- 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)
@@ -580,7 +580,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:
@@ -625,10 +625,10 @@
             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()
@@ -639,7 +639,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)
@@ -685,7 +685,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 += " >..." % self.nodeName
@@ -695,13 +695,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
 
@@ -746,7 +746,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
@@ -812,7 +812,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:
@@ -823,11 +823,11 @@
         if newspaces:
             namespaces = namespaces.copy()
             namespaces.update(newspaces)
-        for k, v         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/web/distrib.py (original)
+++ twisted/web/distrib.py (refactored)
@@ -10,7 +10,7 @@
 """
 
 # System Imports
-import types, os, copy, cStringIO
+import types, os, copy, io
 try:
     import pwd
 except ImportError:
@@ -54,7 +54,7 @@
         state['requestHeaders'] = Headers(dict(state['requestHeaders']))
         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')
@@ -83,7 +83,7 @@
 
     def finished(self, result):
         if result != server.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/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')
@@ -323,7 +323,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):
@@ -342,7 +342,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:]
 
 
@@ -353,9 +353,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:
@@ -556,14 +556,14 @@
         if name == 'received_headers':
             # A property would be nice, ript.py (refactored)
@@ -9,9 +9,9 @@
 import os, traceback
 
 try:
-    import cStringIO as StringIO
+    import io as StringIO
 except ImportError:
-    import StringIO
+    import io
 
 from twisted import copyright
 from twisted.web import http, server, static, resource, html
@@ -61,8 +61,8 @@
             'cache': cs.cache,
             'recache': cs.recache}
     try:
-        execfile(path, glob, glob)
-    except AlreadyCached, ac:
+        exec(compile(open(path).read(), path, 'exec'), glob, glob)
+    except AlreadyCached as ac:
         return ac.args[0]
     rsrc = glob['resource']
     if cs.doCache and rsrc is not noRsrc:
@@ -78,7 +78,7 @@
             'registry': registry}
 
     e = ptl_compile.compile_template(open(path), path)
-    exec e in glob
+    exec(e, glob)
     return glob['resource']
 
 
@@ -156,13 +156,13 @@
                      '__file__': self.filename,
                      'registry': self.registry}
         try:
-            execfile(self.filename, namespace, namespace)
-        except IOError, e:
+            exec(compile(open(self.filename).read(), self.filename, 'exec'), namespace, namespace)
+        except IOError as e:
             if e.errno == 2: #file not found
                 request.setResponseCode(http.NOT_FOUND)
                 request.write(resource.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/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
 import time
@@ -136,7 +136,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:
@@ -336,7 +336,7 @@
         kind = kind.strip()
         if kind != 'bytes':
             raise ValueError("Unsupported Bytes-Unit: %r" % (kind,))
-        unparsedRanges = filter(None, map(str.strip, value.split(',')))
+        unparsedRanges = [_f for _f in list(map(str.strip, value.split(','))) if _f]
         parsedRanges = []
         for byteRange in unparsedRanges:
             try:
@@ -429,7 +429,7 @@
             offset, offset + size - 1, self.getFileSize())
 
 
-    def _doSingleRangeRequest(self, request, (start, end)):
+    def _doSingleRangeRequest(self, request, xxx_todo_changeme):
         """
         Set up the response for Range headers that specify a single range.
 
@@ -444,6 +444,7 @@
         @return: A 2-tuple of the offset and size of the range to return.
             offset == size == 0 indicates that the request is not satisfiable.
         """
+        (start, end) = xxx_todo_changeme
         offset, size  = self._rangeToOffsetAndSize(start, end)
         if offset == size == 0:
             # This range doesn't overlap with any of this resource, so the
@@ -604,7 +605,7 @@
 
         try:
             fileForReading = self.openForReading()
-        exc urllib.parse import quote as urlquote
 
 from twisted.internet import reactor
 from twisted.internet.protocol import ClientFactory
@@ -52,7 +52,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)
@@ -133,14 +133,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]
@@ -282,7 +282,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/server.py (original)
+++ twisted/web/server.py (refactored)
@@ -15,14 +15,14 @@
 import types
 import copy
 import os
-from urllib import quote
+from urllib.parse import quote
 
 from zope.interface import implements
 
 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
@@ -120,7 +120,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)
@@ -131,7 +131,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
@@ -178,7 +178,7 @@
 
         if body == NOT_DONE_YET:
             return
-        if type(body) is not types.StringType:
+        if type(body) is not bytes:
             body = resource.ErrorPage(
                 http.INTERNAL_SERVER_ERROR,
                 "Request did not return a string",
@@ -547,5 +547,5 @@
         return resource.getChildForRequest(self.resource, request)
 
 
-import html
-
+from . import html
+
--- 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 @@
  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
@@ -596,7 +596,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
 
@@ -709,7 +709,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
@@ -741,7 +741,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
@@ -897,7 +897,7 @@
     def setResponseCode(self, code, message=None):
         """Set the HTTP response code.
         """
-        if not isinstance(code, (int, long)):
+        if not isinstance(code, int):
             raise TypeError("HTTP response code must be int or long")
         self.code = code
         if message:
@@ -950,7 +950,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
 
@@ -1553,7 +1553,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/twcgi.py (original)
+++ twisted/web/twcgi.py (refactored)
@@ -11,7 +11,7 @@
 import string
 import os
 import sys
-import urllib
+import urllib.request, urllib.parse, urllib.error
 
 # Twisted Imports
 from twisted.web import http
@@ -97,20 +97,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/xmlrpc.py (original)
+++ twisted/web/xmlrpc.py (refactored)
@@ -9,7 +9,7 @@
 """
 
 # System Imports
-import sys, xmlrpclib, urlparse
+import sys, xmlrpc.client, urllib.parse
 
 # Sibling Imports
 from twisted.web import resource, server, http
@@ -22,10 +22,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
 
 # On Python 2.4 and earlier, DateTime.decode returns unicode.
 if sys.version_info[:2] < (2, 5):
@@ -104,20 +104,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:
                 d = defer.maybeDeferred(function, *args)
@@ -133,12 +133,12 @@
             result = (result,)
         try:
             try:
-                content = xmlrpclib.dumps(
+                content = 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,))
-                content = xmlrpclib.dumps(f, methodresponse=True,
+                content = xmlrpc.client.dumps(f, methodresponse=True,
                                           allow_none=self.allowNone)
 
             request.setHeader("content-length", str(len(content)))
@@ -179,7 +179,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:
@@ -307,14 +307,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())
@@ -373,7 +373,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/test/test_http_headers.py (original)
+++ twisted/web/test/test_http_headers.py (refactored)
@@ -215,7 +215,7 @@
         them both.
         """
         h = Headers()
-        for k, v in kw.iteritems():
+        for k, v in kw.items():
             h.setRawHeaders(k,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,
@@ -903,7 +903,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
@@ -1021,7 +1021,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/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('
Dictionary instance @ %s' % hex(id(d))) w('') - 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 ('
' + 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))+ '
') -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('
Self') --- 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.python.failure import Failure @@ -275,7 +275,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 @@ -298,7 +298,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()): ept IOError, e: + except IOError as e: import errno if e[0] == errno.EACCES: return resource.ForbiddenResource().render(request) @@ -636,7 +637,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): warnings.warn( @@ -790,7 +791,7 @@ self.request.registerProducer(self, 0) def _nextRange(self): - self.partBoundary, partOffset, self._partSize = self.rangeIter.next() + self.partBoundary, partOffset, self._partSize = next(self.rangeIter) self._partBytesWritten = 0 self.fileObject.seek(partOffset) @@ -1013,7 +1014,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 + '/' @@ -1064,7 +1065,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/vhost.py (original) +++ twisted/web/vhost.py (refactored) @@ -22,7 +22,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/_auth/wrapper.py (original) +++ twisted/web/_auth/wrapper.py (refactored) @@ -38,7 +38,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_domhelpers.py (original) +++ twisted/web/test/test_domhelpers.py (refactored) @@ -297,10 +297,10 @@ """ node = self.dom.parseString("bar") text = domhelpers.getNodeText(node) - self.assertEqual(text, u"bar") - self.assertIsInstance(text, unicode) - - node = self.dom.parseString(u"\N{SNOWMAN}".encode('utf-8')) + self.assertEqual(text, "bar") + self.assertIsInstance(text, str) + + node = self.dom.parseString("\N{SNOWMAN}".encode('utf-8')) text = domhelpers.getNodeText(node) - self.assertEqual(text, u"\N{SNOWMAN}") - self.assertIsInstance(text, unicode) + self.assertEqual(text, "\N{SNOWMAN}") + self.assertIsInstance(text, str) --- twisted/web/test/test_webclient.py (original) +++ twisted/web/test/test_webclient.py (refactored) @@ -5,10 +5,10 @@ Tests for L{twisted.web.client}. """ -import StringIO, os +import io, os from errno import ENOSPC -from urlparse import urlparse +from urllib.parse import urlparse from twisted.trial import unittest from twisted.web import server, static, client, error, util, resource @@ -42,7 +42,7 @@ clas '''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 '' 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 = ''' --- 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 @@ -222,7 +222,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/test/test_httpauth.py (original) +++ twisted/web/test/test_httpauth.py (refactored) @@ -195,7 +195,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_static.py (original) +++ twisted/web/test/test_static.py (refactored) @@ -6,7 +6,7 @@ Tests for L{twisted.web.static}. """ -import os, re, StringIO +import os, re, io from twisted.internet import abstract from twisted.python.compat import set @@ -91,7 +91,7 @@ base = FilePath(self.mktemp()) base.setContent('') # Make sure we can delete the file later. - self.addCleanup(base.chmod, 0700) + self.addCleanup(base.chmod, 0o700) # Get rid of our own read permission. base.chmod(0) @@ -296,7 +296,7 @@ start with 'content-'. """ contentHeaders = {} - for k, v in request.outgoingHeaders.iteritems(): + for k, v in request.outgoingHeaders.items(): if k.startswith('content-'): contentHeaders[k] = v return contentHeaders @@ -572,7 +572,7 @@ request = DummyRequest([]) content = 'abcdef' producer = static.NoRangeStaticProducer( - request, StringIO.StringIO(content)) + request, io.StringIO(content)) # start calls registerProducer on the DummyRequest, which pulls all # output from the producer and so we just need this one call. producer.start() @@ -589,7 +589,7 @@ bufferSize = abstract.FileDescriptor.bufferSize content = 'a' * (2*bufferSize + 1) producer = static.NoRangeStaticProducer( - request, StringIO.StringIO(content)) + request, io.StringIO(content)) # start calls registerProducer on the DummyRequest, which pulls all # output from the producer and so we just need this one call. producer.start() @@ -611,7 +611,7 @@ callbackList = [] finishDeferred.addCallback(callbackList.append) producer = static.NoRangeStaticProducer( - request, StringIO.StringIO('abcdef')) + request, io.StringIO('abcdef')) # start calls registerProducer on the DummyRequest, which pulls all # output from the producer and so we just need this one call. producer.start() @@ -634,7 +634,7 @@ request = DummyRequest([]) content = 'abcdef' producer = static.SingleRangeStaticProducer( - request, StringIO.StringIO(content), 1, 3) + request, io.StringIO(content), 1, 3) # DummyRequest.registerProducer pulls all output from the producer, so # we just need to call start. producer.start() @@ -651,7 +651,7 @@ bufferSize = abstract.FileDescriptor.bufferSize content = 'abc' * bufferSize producer = static.SingleRangeStaticProducer( - request, StringIO.StringIO(content), 1, bufferSize+10) + request, io.StringIO(content), 1, bufferSize+10) # DummyRequest.registerProducer pulls all output from the producer, so # we just need to call start. producer.start() @@ -672,7 +672,7 @@ callbackList = [] finishDeferred.addCallback(callbackList.append) producer = static.SingleRangeStaticProducer( - request, StringIO.StringIO('abcdef'), 1, 1) + request, io.StringIO('abcdef'), 1, 1) # start calls registerProducer on the DummyRequest, which pulls all # output from the producer and so we just need this one call. producer.start() @@ -695,7 +695,7 @@ request = DummyRequest([]) content = 'abcdef' producer = static.MultipleRangeStaticProducer( - request, StringIO.StringIO(content), [('1', 1, 3), ('2', 5, 1)]) + request, io.StringIO(content), [('1', 1, 3), ('2', 5, 1)]) # DummyRequest.registerProducer pulls all output from the producer, so # we just need to call start. producer.start() @@ -719,7 +719,7 @@ request = DummyRequest([]) content = '0123456789' * 2 producer = static.MultipleRangeStaticProducer( - request, StringIO.StringIO(content), + request, io.StringIO(content), [('a', 0, 2), ('b', 5, 10), ('c', 0, 0)]) producer.bufferSize = 10 # DummyRequest.registerProducer pulls all output from the producer, so @@ -742,7 +742,7 @@ callbackList = [] finishDeferred.addCallback(callbackList.append) producer = static.MultipleRangeStaticProducer( - request, StringIO.StringIO('abcdef'), [('', 1, 2)]) + request, io.StringIO('abcdef'), [('', 1, 2)]) # start calls registerProducer on the DummyRequest, which pulls all # output from the producer and so we just need this one call. producer.start() @@ -1251,7 +1251,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) @@ -1383,7 +1383,7 @@ """ Instantiation of L{FileTransfer} produces a deprecation warning. """ - static.FileTransfer(StringIO.StringIO(), 0, DummyRequest([])) + static.FileTransfer(io.StringIO(), 0, DummyRequest([])) warnings = self.flushWarnings([self.test_deprecation]) self.assertEqual(len(warnings), 1) self.assertEqual(warnings[0]['category'], DeprecationWarning) --- 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) tr self.assertEquals(req.responseHeaders.getRawHeaders(header, None), resultHeaders[header]) @@ -887,16 +887,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"), @@ -968,7 +968,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): @@ -1141,7 +1141,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_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 @@ -201,7 +201,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 @@ -212,7 +213,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 @@ -436,7 +438,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) @@ -533,7 +536,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/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 im v) return h, _DictHeaders(h) @@ -427,8 +427,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_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 from zope.interface.verify import verifyObject @@ -198,7 +198,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_xmlrpc.py (original) +++ twisted/web/test/test_xmlrpc.py (refactored) @@ -6,7 +6,7 @@ Tests for XML-RPC support in L{twisted.web.xmlrpc}. """ -import xmlrpclib +import xmlrpc.client from twisted.trial import unittest from twisted.web import xmlrpc @@ -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 @@ -222,7 +222,7 @@ call and then returned by the server unmodified, the result should be equal to the original object. """ - when = xmlrpclib.DateTime() + when = xmlrpc.client.DateTime() d = self.proxy().callRemote("echo", when) d.addCallback(self.assertEqual, when) return d @@ -443,7 +443,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/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 @@ frs 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) @@ -155,7 +155,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) @@ -239,7 +239,7 @@ def tearDown(self): # If the test indicated it might leave some server-side connections # around, clean them up. - connections = self.wrapper.protocols.keys() + connections = list(self.wrapper.protocols.keys()) # If there are fewer server-side connections than requested, # that's okay. Some might have noticed that the client closed # the connection and cleaned up after themselves. @@ -382,7 +382,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() @@ -395,7 +395,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), @@ -414,7 +414,7 @@ return d def _cleanupDownloadPageError3(self, ignored): - os.chmod("unwritable", 0700) + os.chmod("unwritable", 0o700) os.unlink("unwritable") return ignored @@ -658,8 +658,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_xml.py (original) +++ twisted/web/test/test_xml.py (refactored) @@ -533,8 +533,8 @@ def testUnicodeTolerance(self): import struct s = '' - j =(u'\r\n\r\n' - u'\u5c02\u9580\u5bb6\u30ea\u30b9\u30c8 ') + j =('\r\n\r\n' + '\u5c02\u9580\u5bb6\u30ea\u30b9\u30c8 ') 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?' @@ -558,14 +558,14 @@ # test that raw text still gets encoded # test that comments get encoded - j3=microdom.parseString(u'') + j3=microdom.parseString('') hdr='' - 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'
\u221a
'.encode('utf8')) + '
\u221a
'.encode('utf8')) def testNamedChildren(self): tests = {"asdfadsf" % (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/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/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()) om 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_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()) + bar>" @@ -573,7 +573,7 @@ 'asdf' : 0, '' : 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/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/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 i 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/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 = (resul ]) 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
" % outname) - except IOError, err: + except IOError as err: content.append(str(err) + "
") 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/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/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 - y: 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= """%s