Raise statement normalization in Lib/.

This commit is contained in:
Collin Winter 2007-08-30 01:19:48 +00:00
parent 8b3febef2f
commit ce36ad8a46
80 changed files with 502 additions and 530 deletions

View File

@ -344,7 +344,7 @@ class RawConfigParser:
def getboolean(self, section, option):
v = self.get(section, option)
if v.lower() not in self._boolean_states:
raise ValueError, 'Not a boolean: %s' % v
raise ValueError('Not a boolean: %s' % v)
return self._boolean_states[v.lower()]
def optionxform(self, optionstr):

View File

@ -127,8 +127,8 @@ class DictMixin:
return default
def pop(self, key, *args):
if len(args) > 1:
raise TypeError, "pop expected at most 2 arguments, got "\
+ repr(1 + len(args))
raise TypeError("pop expected at most 2 arguments, got "
+ repr(1 + len(args)))
try:
value = self[key]
except KeyError:
@ -141,7 +141,7 @@ class DictMixin:
try:
k, v = next(self.iteritems())
except StopIteration:
raise KeyError, 'container is empty'
raise KeyError('container is empty')
del self[k]
return (k, v)
def update(self, other=None, **kwargs):

View File

@ -183,7 +183,7 @@ class MutableString(UserString):
def __init__(self, string=""):
self.data = string
def __hash__(self):
raise TypeError, "unhashable type (it is mutable)"
raise TypeError("unhashable type (it is mutable)")
def __setitem__(self, index, sub):
if isinstance(index, slice):
if isinstance(sub, UserString):

View File

@ -287,14 +287,14 @@ class Aifc_read:
self._soundpos = 0
self._file = Chunk(file)
if self._file.getname() != 'FORM':
raise Error, 'file does not start with FORM id'
raise Error('file does not start with FORM id')
formdata = self._file.read(4)
if formdata == 'AIFF':
self._aifc = 0
elif formdata == 'AIFC':
self._aifc = 1
else:
raise Error, 'not an AIFF or AIFF-C file'
raise Error('not an AIFF or AIFF-C file')
self._comm_chunk_read = 0
while 1:
self._ssnd_seek_needed = 1
@ -317,10 +317,10 @@ class Aifc_read:
elif chunkname in _skiplist:
pass
else:
raise Error, 'unrecognized chunk type '+chunk.chunkname
raise Error('unrecognized chunk type '+chunk.chunkname)
chunk.skip()
if not self._comm_chunk_read or not self._ssnd_chunk:
raise Error, 'COMM chunk and/or SSND chunk missing'
raise Error('COMM chunk and/or SSND chunk missing')
if self._aifc and self._decomp:
import cl
params = [cl.ORIGINAL_FORMAT, 0,
@ -331,7 +331,7 @@ class Aifc_read:
elif self._nchannels == 2:
params[1] = cl.STEREO_INTERLEAVED
else:
raise Error, 'cannot compress more than 2 channels'
raise Error('cannot compress more than 2 channels')
self._decomp.SetParams(params)
def __init__(self, f):
@ -394,11 +394,11 @@ class Aifc_read:
for marker in self._markers:
if id == marker[0]:
return marker
raise Error, 'marker %r does not exist' % (id,)
raise Error('marker %r does not exist' % (id,))
def setpos(self, pos):
if pos < 0 or pos > self._nframes:
raise Error, 'position not in range'
raise Error('position not in range')
self._soundpos = pos
self._ssnd_seek_needed = 1
@ -488,7 +488,7 @@ class Aifc_read:
return
except ImportError:
pass
raise Error, 'cannot read compressed AIFF-C files'
raise Error('cannot read compressed AIFF-C files')
if self._comptype == 'ULAW':
scheme = cl.G711_ULAW
self._framesize = self._framesize / 2
@ -496,7 +496,7 @@ class Aifc_read:
scheme = cl.G711_ALAW
self._framesize = self._framesize / 2
else:
raise Error, 'unsupported compression type'
raise Error('unsupported compression type')
self._decomp = cl.OpenDecompressor(scheme)
self._convert = self._decomp_data
else:
@ -594,53 +594,53 @@ class Aifc_write:
#
def aiff(self):
if self._nframeswritten:
raise Error, 'cannot change parameters after starting to write'
raise Error('cannot change parameters after starting to write')
self._aifc = 0
def aifc(self):
if self._nframeswritten:
raise Error, 'cannot change parameters after starting to write'
raise Error('cannot change parameters after starting to write')
self._aifc = 1
def setnchannels(self, nchannels):
if self._nframeswritten:
raise Error, 'cannot change parameters after starting to write'
raise Error('cannot change parameters after starting to write')
if nchannels < 1:
raise Error, 'bad # of channels'
raise Error('bad # of channels')
self._nchannels = nchannels
def getnchannels(self):
if not self._nchannels:
raise Error, 'number of channels not set'
raise Error('number of channels not set')
return self._nchannels
def setsampwidth(self, sampwidth):
if self._nframeswritten:
raise Error, 'cannot change parameters after starting to write'
raise Error('cannot change parameters after starting to write')
if sampwidth < 1 or sampwidth > 4:
raise Error, 'bad sample width'
raise Error('bad sample width')
self._sampwidth = sampwidth
def getsampwidth(self):
if not self._sampwidth:
raise Error, 'sample width not set'
raise Error('sample width not set')
return self._sampwidth
def setframerate(self, framerate):
if self._nframeswritten:
raise Error, 'cannot change parameters after starting to write'
raise Error('cannot change parameters after starting to write')
if framerate <= 0:
raise Error, 'bad frame rate'
raise Error('bad frame rate')
self._framerate = framerate
def getframerate(self):
if not self._framerate:
raise Error, 'frame rate not set'
raise Error('frame rate not set')
return self._framerate
def setnframes(self, nframes):
if self._nframeswritten:
raise Error, 'cannot change parameters after starting to write'
raise Error('cannot change parameters after starting to write')
self._nframes = nframes
def getnframes(self):
@ -648,9 +648,9 @@ class Aifc_write:
def setcomptype(self, comptype, compname):
if self._nframeswritten:
raise Error, 'cannot change parameters after starting to write'
raise Error('cannot change parameters after starting to write')
if comptype not in ('NONE', 'ULAW', 'ALAW', 'G722'):
raise Error, 'unsupported compression type'
raise Error('unsupported compression type')
self._comptype = comptype
self._compname = compname
@ -668,9 +668,9 @@ class Aifc_write:
def setparams(self, params):
nchannels, sampwidth, framerate, nframes, comptype, compname = params
if self._nframeswritten:
raise Error, 'cannot change parameters after starting to write'
raise Error('cannot change parameters after starting to write')
if comptype not in ('NONE', 'ULAW', 'ALAW', 'G722'):
raise Error, 'unsupported compression type'
raise Error('unsupported compression type')
self.setnchannels(nchannels)
self.setsampwidth(sampwidth)
self.setframerate(framerate)
@ -679,17 +679,17 @@ class Aifc_write:
def getparams(self):
if not self._nchannels or not self._sampwidth or not self._framerate:
raise Error, 'not all parameters set'
raise Error('not all parameters set')
return self._nchannels, self._sampwidth, self._framerate, \
self._nframes, self._comptype, self._compname
def setmark(self, id, pos, name):
if id <= 0:
raise Error, 'marker ID must be > 0'
raise Error('marker ID must be > 0')
if pos < 0:
raise Error, 'marker position must be >= 0'
raise Error('marker position must be >= 0')
if type(name) != type(''):
raise Error, 'marker name must be a string'
raise Error('marker name must be a string')
for i in range(len(self._markers)):
if id == self._markers[i][0]:
self._markers[i] = id, pos, name
@ -700,7 +700,7 @@ class Aifc_write:
for marker in self._markers:
if id == marker[0]:
return marker
raise Error, 'marker %r does not exist' % (id,)
raise Error('marker %r does not exist' % (id,))
def getmarkers(self):
if len(self._markers) == 0:
@ -770,18 +770,18 @@ class Aifc_write:
if not self._sampwidth:
self._sampwidth = 2
if self._sampwidth != 2:
raise Error, 'sample width must be 2 when compressing with ULAW or ALAW'
raise Error('sample width must be 2 when compressing with ULAW or ALAW')
if self._comptype == 'G722':
if not self._sampwidth:
self._sampwidth = 2
if self._sampwidth != 2:
raise Error, 'sample width must be 2 when compressing with G7.22 (ADPCM)'
raise Error('sample width must be 2 when compressing with G7.22 (ADPCM)')
if not self._nchannels:
raise Error, '# channels not specified'
raise Error('# channels not specified')
if not self._sampwidth:
raise Error, 'sample width not specified'
raise Error('sample width not specified')
if not self._framerate:
raise Error, 'sampling rate not specified'
raise Error('sampling rate not specified')
self._write_header(datasize)
def _init_compression(self):
@ -798,13 +798,13 @@ class Aifc_write:
return
except ImportError:
pass
raise Error, 'cannot write compressed AIFF-C files'
raise Error('cannot write compressed AIFF-C files')
if self._comptype == 'ULAW':
scheme = cl.G711_ULAW
elif self._comptype == 'ALAW':
scheme = cl.G711_ALAW
else:
raise Error, 'unsupported compression type'
raise Error('unsupported compression type')
self._comp = cl.OpenCompressor(scheme)
params = [cl.ORIGINAL_FORMAT, 0,
cl.BITS_PER_COMPONENT, self._sampwidth * 8,
@ -816,7 +816,7 @@ class Aifc_write:
elif self._nchannels == 2:
params[1] = cl.STEREO_INTERLEAVED
else:
raise Error, 'cannot compress more than 2 channels'
raise Error('cannot compress more than 2 channels')
self._comp.SetParams(params)
# the compressor produces a header which we ignore
dummy = self._comp.Compress(0, '')
@ -930,7 +930,7 @@ def open(f, mode=None):
elif mode in ('w', 'wb'):
return Aifc_write(f)
else:
raise Error, "mode must be 'r', 'rb', 'w', or 'wb'"
raise Error("mode must be 'r', 'rb', 'w', or 'wb'")
openfp = open # B/W compatibility

View File

@ -59,7 +59,7 @@ for _name in _names:
_errors.append(_mod.error)
if not _defaultmod:
raise ImportError, "no dbm clone found; tried %s" % _names
raise ImportError("no dbm clone found; tried %s" % _names)
error = tuple(_errors)
@ -74,10 +74,10 @@ def open(file, flag = 'r', mode = 0o666):
# flag was used so use default type
mod = _defaultmod
else:
raise error, "need 'c' or 'n' flag to open new db"
raise error("need 'c' or 'n' flag to open new db")
elif result == "":
# db type cannot be determined
raise error, "db type could not be determined"
raise error("db type could not be determined")
else:
mod = __import__(result)
return mod.open(file, flag, mode)

View File

@ -66,10 +66,10 @@ class async_chat (asyncore.dispatcher):
asyncore.dispatcher.__init__ (self, conn)
def collect_incoming_data(self, data):
raise NotImplementedError, "must be implemented in subclass"
raise NotImplementedError("must be implemented in subclass")
def found_terminator(self):
raise NotImplementedError, "must be implemented in subclass"
raise NotImplementedError("must be implemented in subclass")
def set_terminator (self, term):
"Set the input delimiter. Can be a fixed string of any length, an integer, or None"

View File

@ -313,7 +313,7 @@ class dispatcher:
self.connected = True
self.handle_connect()
else:
raise socket.error, (err, errorcode[err])
raise socket.error(err, errorcode[err])
def accept(self):
# XXX can return either an address pair or None

View File

@ -130,7 +130,7 @@ class Bdb:
return False
def do_clear(self, arg):
raise NotImplementedError, "subclass of bdb must implement do_clear()"
raise NotImplementedError("subclass of bdb must implement do_clear()")
def break_anywhere(self, frame):
return self.canonic(frame.f_code.co_filename) in self.breaks

View File

@ -140,7 +140,7 @@ def parse(fp=None, environ=os.environ, keep_blank_values=0, strict_parsing=0):
elif ctype == 'application/x-www-form-urlencoded':
clength = int(environ['CONTENT_LENGTH'])
if maxlen and clength > maxlen:
raise ValueError, 'Maximum content length exceeded'
raise ValueError('Maximum content length exceeded')
qs = fp.read(clength)
else:
qs = '' # Unknown content-type
@ -215,7 +215,7 @@ def parse_qsl(qs, keep_blank_values=0, strict_parsing=0):
nv = name_value.split('=', 1)
if len(nv) != 2:
if strict_parsing:
raise ValueError, "bad query field: %r" % (name_value,)
raise ValueError("bad query field: %r" % (name_value,))
# Handle case of a control-name with no equal sign
if keep_blank_values:
nv.append('')
@ -258,7 +258,7 @@ def parse_multipart(fp, pdict):
if 'boundary' in pdict:
boundary = pdict['boundary']
if not valid_boundary(boundary):
raise ValueError, ('Invalid boundary in multipart form: %r'
raise ValueError('Invalid boundary in multipart form: %r'
% (boundary,))
nextpart = "--" + boundary
@ -280,7 +280,7 @@ def parse_multipart(fp, pdict):
pass
if bytes > 0:
if maxlen and bytes > maxlen:
raise ValueError, 'Maximum content length exceeded'
raise ValueError('Maximum content length exceeded')
data = fp.read(bytes)
else:
data = ""
@ -520,7 +520,7 @@ class FieldStorage:
except ValueError:
pass
if maxlen and clen > maxlen:
raise ValueError, 'Maximum content length exceeded'
raise ValueError('Maximum content length exceeded')
self.length = clen
self.list = self.file = None
@ -542,7 +542,7 @@ class FieldStorage:
def __getattr__(self, name):
if name != 'value':
raise AttributeError, name
raise AttributeError(name)
if self.file:
self.file.seek(0)
value = self.file.read()
@ -556,12 +556,12 @@ class FieldStorage:
def __getitem__(self, key):
"""Dictionary style indexing."""
if self.list is None:
raise TypeError, "not indexable"
raise TypeError("not indexable")
found = []
for item in self.list:
if item.name == key: found.append(item)
if not found:
raise KeyError, key
raise KeyError(key)
if len(found) == 1:
return found[0]
else:
@ -603,7 +603,7 @@ class FieldStorage:
def keys(self):
"""Dictionary style keys() method."""
if self.list is None:
raise TypeError, "not indexable"
raise TypeError("not indexable")
keys = []
for item in self.list:
if item.name not in keys: keys.append(item.name)
@ -612,7 +612,7 @@ class FieldStorage:
def __contains__(self, key):
"""Dictionary style __contains__ method."""
if self.list is None:
raise TypeError, "not indexable"
raise TypeError("not indexable")
for item in self.list:
if item.name == key: return True
return False
@ -636,7 +636,7 @@ class FieldStorage:
"""Internal: read a part that is itself multipart."""
ib = self.innerboundary
if not valid_boundary(ib):
raise ValueError, 'Invalid boundary in multipart form: %r' % (ib,)
raise ValueError('Invalid boundary in multipart form: %r' % (ib,))
self.list = []
klass = self.FieldStorageClass or self.__class__
part = klass(self.fp, {}, ib,
@ -817,7 +817,7 @@ class SvFormContentDict(FormContentDict):
"""
def __getitem__(self, key):
if len(self.dict[key]) > 1:
raise IndexError, 'expecting a single value'
raise IndexError('expecting a single value')
return self.dict[key][0]
def getlist(self, key):
return self.dict[key]

View File

@ -90,7 +90,7 @@ class Chunk:
def isatty(self):
if self.closed:
raise ValueError, "I/O operation on closed file"
raise ValueError("I/O operation on closed file")
return False
def seek(self, pos, whence=0):
@ -100,9 +100,9 @@ class Chunk:
"""
if self.closed:
raise ValueError, "I/O operation on closed file"
raise ValueError("I/O operation on closed file")
if not self.seekable:
raise IOError, "cannot seek"
raise IOError("cannot seek")
if whence == 1:
pos = pos + self.size_read
elif whence == 2:
@ -114,7 +114,7 @@ class Chunk:
def tell(self):
if self.closed:
raise ValueError, "I/O operation on closed file"
raise ValueError("I/O operation on closed file")
return self.size_read
def read(self, size=-1):
@ -124,7 +124,7 @@ class Chunk:
"""
if self.closed:
raise ValueError, "I/O operation on closed file"
raise ValueError("I/O operation on closed file")
if self.size_read >= self.chunksize:
return ''
if size < 0:
@ -148,7 +148,7 @@ class Chunk:
"""
if self.closed:
raise ValueError, "I/O operation on closed file"
raise ValueError("I/O operation on closed file")
if self.seekable:
try:
n = self.chunksize - self.size_read

View File

@ -358,8 +358,8 @@ class Cmd:
nonstrings = [i for i in range(len(list))
if not isinstance(list[i], basestring)]
if nonstrings:
raise TypeError, ("list[i] not a string for i in %s" %
", ".join(map(str, nonstrings)))
raise TypeError("list[i] not a string for i in %s"
% ", ".join(map(str, nonstrings)))
size = len(list)
if size == 1:
self.stdout.write('%s\n'%str(list[0]))

View File

@ -96,7 +96,7 @@ def _maybe_compile(compiler, source, filename, symbol):
if code:
return code
if not code1 and repr(err1) == repr(err2):
raise SyntaxError, err1
raise SyntaxError(err1)
def _compile(source, filename, symbol):
return compile(source, filename, symbol, PyCF_DONT_IMPLY_DEDENT)

View File

@ -62,7 +62,7 @@ def _reduce_ex(self, proto):
state = None
else:
if base is self.__class__:
raise TypeError, "can't pickle %s objects" % base.__name__
raise TypeError("can't pickle %s objects" % base.__name__)
state = base(self)
args = (self.__class__, base, state)
try:
@ -153,7 +153,7 @@ def add_extension(module, name, code):
"""Register an extension code."""
code = int(code)
if not 1 <= code <= 0x7fffffff:
raise ValueError, "code out of range"
raise ValueError("code out of range")
key = (module, name)
if (_extension_registry.get(key) == code and
_inverted_registry.get(code) == key):

View File

@ -104,9 +104,8 @@ class DictWriter:
self.fieldnames = fieldnames # list of keys for the dict
self.restval = restval # for writing short dicts
if extrasaction.lower() not in ("raise", "ignore"):
raise ValueError, \
("extrasaction (%s) must be 'raise' or 'ignore'" %
extrasaction)
raise ValueError("extrasaction (%s) must be 'raise' or 'ignore'"
% extrasaction)
self.extrasaction = extrasaction
self.writer = writer(f, dialect, *args, **kwds)
@ -114,8 +113,8 @@ class DictWriter:
if self.extrasaction == "raise":
wrong_fields = [k for k in rowdict if k not in self.fieldnames]
if wrong_fields:
raise ValueError("dict contains fields not in fieldnames: " +
", ".join(wrong_fields))
raise ValueError("dict contains fields not in fieldnames: "
+ ", ".join(wrong_fields))
return [rowdict.get(key, self.restval) for key in self.fieldnames]
def writerow(self, rowdict):
@ -155,7 +154,7 @@ class Sniffer:
delimiters)
if not delimiter:
raise Error, "Could not determine delimiter"
raise Error("Could not determine delimiter")
class dialect(Dialect):
_name = "sniffed"

View File

@ -2350,7 +2350,7 @@ class Context(object):
# Errors should only be risked on copies of the context
# self._ignored_flags = []
raise error, explanation
raise error(explanation)
def _ignore_all_flags(self):
"""Ignore all flags, if they are raised"""

View File

@ -914,7 +914,7 @@ class Differ:
elif tag == 'equal':
g = self._dump(' ', a, alo, ahi)
else:
raise ValueError, 'unknown tag %r' % (tag,)
raise ValueError('unknown tag %r' % (tag,))
for line in g:
yield line
@ -1026,7 +1026,7 @@ class Differ:
atags += ' ' * la
btags += ' ' * lb
else:
raise ValueError, 'unknown tag %r' % (tag,)
raise ValueError('unknown tag %r' % (tag,))
for line in self._qformat(aelt, belt, atags, btags):
yield line
else:
@ -2005,7 +2005,7 @@ def restore(delta, which):
try:
tag = {1: "- ", 2: "+ "}[int(which)]
except KeyError:
raise ValueError, ('unknown delta choice (must be 1 or 2): %r'
raise ValueError('unknown delta choice (must be 1 or 2): %r'
% which)
prefixes = (" ", tag)
for line in delta:

View File

@ -47,7 +47,7 @@ def distb(tb=None):
try:
tb = sys.last_traceback
except AttributeError:
raise RuntimeError, "no last traceback to disassemble"
raise RuntimeError("no last traceback to disassemble")
while tb.tb_next: tb = tb.tb_next
disassemble(tb.tb_frame.f_code, tb.tb_lasti)

View File

@ -326,9 +326,9 @@ class _OutputRedirectingPdb(pdb.Pdb):
# [XX] Normalize with respect to os.path.pardir?
def _module_relative_path(module, path):
if not inspect.ismodule(module):
raise TypeError, 'Expected a module: %r' % module
raise TypeError('Expected a module: %r' % module)
if path.startswith('/'):
raise ValueError, 'Module-relative files may not have absolute paths'
raise ValueError('Module-relative files may not have absolute paths')
# Find the base directory for the path.
if hasattr(module, '__file__'):

View File

@ -116,18 +116,16 @@ def search_function(encoding):
entry = getregentry()
if not isinstance(entry, codecs.CodecInfo):
if not 4 <= len(entry) <= 7:
raise CodecRegistryError,\
'module "%s" (%s) failed to register' % \
(mod.__name__, mod.__file__)
raise CodecRegistryError('module "%s" (%s) failed to register'
% (mod.__name__, mod.__file__))
if not hasattr(entry[0], '__call__') or \
not hasattr(entry[1], '__call__') or \
(entry[2] is not None and not hasattr(entry[2], '__call__')) or \
(entry[3] is not None and not hasattr(entry[3], '__call__')) or \
(len(entry) > 4 and entry[4] is not None and not hasattr(entry[4], '__call__')) or \
(len(entry) > 5 and entry[5] is not None and not hasattr(entry[5], '__call__')):
raise CodecRegistryError,\
'incompatible codecs in module "%s" (%s)' % \
(mod.__name__, mod.__file__)
raise CodecRegistryError('incompatible codecs in module "%s" (%s)'
% (mod.__name__, mod.__file__))
if len(entry)<7 or entry[6] is None:
entry += (None,)*(6-len(entry)) + (mod.__name__.split(".", 1)[1],)
entry = codecs.CodecInfo(*entry)

View File

@ -135,7 +135,7 @@ def decode_generalized_number(extended, extpos, bias, errors):
char = ord(extended[extpos])
except IndexError:
if errors == "strict":
raise UnicodeError, "incomplete punicode string"
raise UnicodeError("incomplete punicode string")
return extpos + 1, None
extpos += 1
if 0x41 <= char <= 0x5A: # A-Z
@ -172,7 +172,7 @@ def insertion_sort(base, extended, errors):
char += pos // (len(base) + 1)
if char > 0x10FFFF:
if errors == "strict":
raise UnicodeError, ("Invalid character U+%x" % char)
raise UnicodeError("Invalid character U+%x" % char)
char = ord('?')
pos = pos % (len(base) + 1)
base = base[:pos] + chr(char) + base[pos:]
@ -202,7 +202,7 @@ class Codec(codecs.Codec):
def decode(self, input, errors='strict'):
if errors not in ('strict', 'replace', 'ignore'):
raise UnicodeError, "Unsupported error handling "+errors
raise UnicodeError("Unsupported error handling "+errors)
res = punycode_decode(input, errors)
return res, len(input)
@ -213,7 +213,7 @@ class IncrementalEncoder(codecs.IncrementalEncoder):
class IncrementalDecoder(codecs.IncrementalDecoder):
def decode(self, input, final=False):
if self.errors not in ('strict', 'replace', 'ignore'):
raise UnicodeError, "Unsupported error handling "+self.errors
raise UnicodeError("Unsupported error handling "+self.errors)
return punycode_decode(input, self.errors)
class StreamWriter(Codec,codecs.StreamWriter):

View File

@ -132,7 +132,7 @@ class StreamReader(codecs.StreamReader):
elif byteorder == 1:
self.decode = codecs.utf_16_be_decode
elif consumed>=2:
raise UnicodeError,"UTF-16 stream does not start with BOM"
raise UnicodeError("UTF-16 stream does not start with BOM")
return (object, consumed)
### encodings module API

View File

@ -235,7 +235,7 @@ class dircmp:
def __getattr__(self, attr):
if attr not in self.methodmap:
raise AttributeError, attr
raise AttributeError(attr)
self.methodmap[attr](self)
return getattr(self, attr)

View File

@ -99,7 +99,7 @@ def input(files=None, inplace=0, backup="", bufsize=0,
"""
global _state
if _state and _state._file:
raise RuntimeError, "input() already active"
raise RuntimeError("input() already active")
_state = FileInput(files, inplace, backup, bufsize, mode, openhook)
return _state
@ -122,7 +122,7 @@ def nextfile():
last file has been read, this function has no effect.
"""
if not _state:
raise RuntimeError, "no active input()"
raise RuntimeError("no active input()")
return _state.nextfile()
def filename():
@ -131,7 +131,7 @@ def filename():
Before the first line has been read, returns None.
"""
if not _state:
raise RuntimeError, "no active input()"
raise RuntimeError("no active input()")
return _state.filename()
def lineno():
@ -141,7 +141,7 @@ def lineno():
of the last file has been read, returns the line number of that line.
"""
if not _state:
raise RuntimeError, "no active input()"
raise RuntimeError("no active input()")
return _state.lineno()
def filelineno():
@ -151,7 +151,7 @@ def filelineno():
been read, returns the line number of that line within the file.
"""
if not _state:
raise RuntimeError, "no active input()"
raise RuntimeError("no active input()")
return _state.filelineno()
def fileno():
@ -160,7 +160,7 @@ def fileno():
opened, returns -1.
"""
if not _state:
raise RuntimeError, "no active input()"
raise RuntimeError("no active input()")
return _state.fileno()
def isfirstline():
@ -169,7 +169,7 @@ def isfirstline():
otherwise returns false.
"""
if not _state:
raise RuntimeError, "no active input()"
raise RuntimeError("no active input()")
return _state.isfirstline()
def isstdin():
@ -178,7 +178,7 @@ def isstdin():
otherwise returns false.
"""
if not _state:
raise RuntimeError, "no active input()"
raise RuntimeError("no active input()")
return _state.isstdin()
class FileInput:
@ -257,11 +257,11 @@ class FileInput:
def __getitem__(self, i):
if i != self._lineno:
raise RuntimeError, "accessing lines out of order"
raise RuntimeError("accessing lines out of order")
try:
return self.__next__()
except StopIteration:
raise IndexError, "end of input reached"
raise IndexError("end of input reached")
def nextfile(self):
savestdout = self._savestdout

View File

@ -36,7 +36,7 @@ def extract(s):
fraction is 0 or more digits
expo is an integer"""
res = decoder.match(s)
if res is None: raise NotANumber, s
if res is None: raise NotANumber(s)
sign, intpart, fraction, exppart = res.group(1,2,3,4)
if sign == '+': sign = ''
if fraction: fraction = fraction[1:]

View File

@ -212,16 +212,16 @@ class FTP:
if c in ('1', '2', '3'):
return resp
if c == '4':
raise error_temp, resp
raise error_temp(resp)
if c == '5':
raise error_perm, resp
raise error_proto, resp
raise error_perm(resp)
raise error_proto(resp)
def voidresp(self):
"""Expect a response beginning with '2'."""
resp = self.getresp()
if resp[0] != '2':
raise error_reply, resp
raise error_reply(resp)
return resp
def abort(self):
@ -234,7 +234,7 @@ class FTP:
self.sock.sendall(line, MSG_OOB)
resp = self.getmultiline()
if resp[:3] not in ('426', '226'):
raise error_proto, resp
raise error_proto(resp)
def sendcmd(self, cmd):
'''Send a command and return the response.'''
@ -264,7 +264,7 @@ class FTP:
if self.af == socket.AF_INET6:
af = 2
if af == 0:
raise error_proto, 'unsupported address family'
raise error_proto('unsupported address family')
fields = ['', repr(af), host, repr(port), '']
cmd = 'EPRT ' + '|'.join(fields)
return self.voidcmd(cmd)
@ -285,7 +285,7 @@ class FTP:
continue
break
if not sock:
raise socket.error, msg
raise socket.error(msg)
sock.listen(1)
port = sock.getsockname()[1] # Get proper port
host = self.sock.getsockname()[0] # Get proper host
@ -333,7 +333,7 @@ class FTP:
if resp[0] == '2':
resp = self.getresp()
if resp[0] != '1':
raise error_reply, resp
raise error_reply(resp)
else:
sock = self.makeport()
if rest is not None:
@ -343,7 +343,7 @@ class FTP:
if resp[0] == '2':
resp = self.getresp()
if resp[0] != '1':
raise error_reply, resp
raise error_reply(resp)
conn, sockaddr = sock.accept()
if resp[:3] == '150':
# this is conditional in case we received a 125
@ -372,7 +372,7 @@ class FTP:
if resp[0] == '3': resp = self.sendcmd('PASS ' + passwd)
if resp[0] == '3': resp = self.sendcmd('ACCT ' + acct)
if resp[0] != '2':
raise error_reply, resp
raise error_reply(resp)
return resp
def retrbinary(self, cmd, callback, blocksize=8192, rest=None):
@ -477,7 +477,7 @@ class FTP:
'''Rename a file.'''
resp = self.sendcmd('RNFR ' + fromname)
if resp[0] != '3':
raise error_reply, resp
raise error_reply(resp)
return self.voidcmd('RNTO ' + toname)
def delete(self, filename):
@ -486,9 +486,9 @@ class FTP:
if resp[:3] in ('250', '200'):
return resp
elif resp[:1] == '5':
raise error_perm, resp
raise error_perm(resp)
else:
raise error_reply, resp
raise error_reply(resp)
def cwd(self, dirname):
'''Change to a directory.'''
@ -550,7 +550,7 @@ def parse150(resp):
be present in the 150 message.
'''
if resp[:3] != '150':
raise error_reply, resp
raise error_reply(resp)
global _150_re
if _150_re is None:
import re
@ -573,14 +573,14 @@ def parse227(resp):
Return ('host.addr.as.numbers', port#) tuple.'''
if resp[:3] != '227':
raise error_reply, resp
raise error_reply(resp)
global _227_re
if _227_re is None:
import re
_227_re = re.compile(r'(\d+),(\d+),(\d+),(\d+),(\d+),(\d+)')
m = _227_re.search(resp)
if not m:
raise error_proto, resp
raise error_proto(resp)
numbers = m.groups()
host = '.'.join(numbers[:4])
port = (int(numbers[4]) << 8) + int(numbers[5])
@ -593,17 +593,17 @@ def parse229(resp, peer):
Return ('host.addr.as.numbers', port#) tuple.'''
if resp[:3] != '229':
raise error_reply, resp
raise error_reply(resp)
left = resp.find('(')
if left < 0: raise error_proto, resp
if left < 0: raise error_proto(resp)
right = resp.find(')', left + 1)
if right < 0:
raise error_proto, resp # should contain '(|||port|)'
raise error_proto(resp) # should contain '(|||port|)'
if resp[left + 1] != resp[right - 1]:
raise error_proto, resp
raise error_proto(resp)
parts = resp[left + 1:right].split(resp[left+1])
if len(parts) != 5:
raise error_proto, resp
raise error_proto(resp)
host = peer[0]
port = int(parts[3])
return host, port
@ -615,7 +615,7 @@ def parse257(resp):
Returns the directoryname in the 257 reply.'''
if resp[:3] != '257':
raise error_reply, resp
raise error_reply(resp)
if resp[3:5] != ' "':
return '' # Not compliant to RFC 959, but UNIX ftpd does this
dirname = ''
@ -674,8 +674,7 @@ class Netrc:
filename = os.path.join(os.environ["HOME"],
".netrc")
else:
raise IOError, \
"specify file to load or set $HOME"
raise IOError("specify file to load or set $HOME")
self.__hosts = {}
self.__macros = {}
fp = open(filename, "r")

View File

@ -83,11 +83,10 @@ def c2py(plural):
try:
danger = [x for x in tokens if x[0] == token.NAME and x[1] != 'n']
except tokenize.TokenError:
raise ValueError, \
'plural forms expression error, maybe unbalanced parenthesis'
raise ValueError('plural forms expression error, maybe unbalanced parenthesis')
else:
if danger:
raise ValueError, 'plural forms expression could be dangerous'
raise ValueError('plural forms expression could be dangerous')
# Replace some C operators by their Python equivalents
plural = plural.replace('&&', ' and ')
@ -113,7 +112,7 @@ def c2py(plural):
# Actually, we never reach this code, because unbalanced
# parentheses get caught in the security check at the
# beginning.
raise ValueError, 'unbalanced parenthesis in plural form'
raise ValueError('unbalanced parenthesis in plural form')
s = expr.sub(repl, stack.pop())
stack[-1] += '(%s)' % s
else:

View File

@ -119,7 +119,7 @@ class GzipFile:
zlib.DEF_MEM_LEVEL,
0)
else:
raise IOError, "Mode " + mode + " not supported"
raise IOError("Mode " + mode + " not supported")
self.fileobj = fileobj
self.offset = 0
@ -174,10 +174,10 @@ class GzipFile:
def _read_gzip_header(self):
magic = self.fileobj.read(2)
if magic != b'\037\213':
raise IOError, 'Not a gzipped file'
raise IOError('Not a gzipped file')
method = ord( self.fileobj.read(1) )
if method != 8:
raise IOError, 'Unknown compression method'
raise IOError('Unknown compression method')
flag = ord( self.fileobj.read(1) )
# modtime = self.fileobj.read(4)
# extraflag = self.fileobj.read(1)
@ -211,7 +211,7 @@ class GzipFile:
raise IOError(errno.EBADF, "write() on read-only GzipFile object")
if self.fileobj is None:
raise ValueError, "write() on closed GzipFile object"
raise ValueError("write() on closed GzipFile object")
if len(data) > 0:
self.size = self.size + len(data)
self.crc = zlib.crc32(data, self.crc)
@ -257,7 +257,7 @@ class GzipFile:
def _read(self, size=1024):
if self.fileobj is None:
raise EOFError, "Reached EOF"
raise EOFError("Reached EOF")
if self._new_member:
# If the _new_member flag is set, we have to
@ -268,7 +268,7 @@ class GzipFile:
pos = self.fileobj.tell() # Save current position
self.fileobj.seek(0, 2) # Seek to end of file
if pos == self.fileobj.tell():
raise EOFError, "Reached EOF"
raise EOFError("Reached EOF")
else:
self.fileobj.seek( pos ) # Return to original position
@ -287,7 +287,7 @@ class GzipFile:
uncompress = self.decompress.flush()
self._read_eof()
self._add_read_data( uncompress )
raise EOFError, 'Reached EOF'
raise EOFError('Reached EOF')
uncompress = self.decompress.decompress(buf)
self._add_read_data( uncompress )
@ -321,9 +321,9 @@ class GzipFile:
crc32 = read32(self.fileobj)
isize = U32(read32(self.fileobj)) # may exceed 2GB
if U32(crc32) != U32(self.crc):
raise IOError, "CRC check failed"
raise IOError("CRC check failed")
elif isize != LOWU32(self.size):
raise IOError, "Incorrect length of data produced"
raise IOError("Incorrect length of data produced")
def close(self):
if self.mode == WRITE:

View File

@ -74,7 +74,7 @@ def __get_builtin_constructor(name):
elif bs == '384':
return _sha512.sha384
raise ValueError, "unsupported hash type"
raise ValueError("unsupported hash type")
def __py_new(name, data=b''):

View File

@ -271,8 +271,8 @@ class ModuleLoader(BasicModuleLoader):
elif type == PKG_DIRECTORY:
m = self.hooks.load_package(name, filename, file)
else:
raise ImportError, "Unrecognized module type (%r) for %s" % \
(type, name)
raise ImportError("Unrecognized module type (%r) for %s"
% (type, name))
finally:
if file: file.close()
m.__file__ = filename
@ -291,14 +291,13 @@ class FancyModuleLoader(ModuleLoader):
if type == PKG_DIRECTORY:
initstuff = self.find_module_in_dir("__init__", filename, 0)
if not initstuff:
raise ImportError, "No __init__ module in package %s" % name
raise ImportError("No __init__ module in package %s" % name)
initfile, initfilename, initinfo = initstuff
initsuff, initmode, inittype = initinfo
if inittype not in (PY_COMPILED, PY_SOURCE):
if initfile: initfile.close()
raise ImportError, \
"Bad type (%r) for __init__ module in package %s" % (
inittype, name)
raise ImportError("Bad type (%r) for __init__ module"
" in package %s" % (inittype, name))
path = [filename]
file = initfile
realfilename = initfilename
@ -361,14 +360,14 @@ class BasicModuleImporter(_Verbose):
return self.modules[name] # Fast path
stuff = self.loader.find_module(name)
if not stuff:
raise ImportError, "No module named %s" % name
raise ImportError("No module named %s" % name)
return self.loader.load_module(name, stuff)
def reload(self, module, path = None):
name = str(module.__name__)
stuff = self.loader.find_module(name, path)
if not stuff:
raise ImportError, "Module %s not found for reload" % name
raise ImportError("Module %s not found for reload" % name)
return self.loader.load_module(name, stuff)
def unload(self, module):
@ -439,7 +438,7 @@ class ModuleImporter(BasicModuleImporter):
parent = None
q = self.import_it(head, qname, parent)
if q: return q, tail
raise ImportError, "No module named " + qname
raise ImportError("No module named " + qname)
def load_tail(self, q, tail):
m = q
@ -450,7 +449,7 @@ class ModuleImporter(BasicModuleImporter):
mname = "%s.%s" % (m.__name__, head)
m = self.import_it(head, mname, m)
if not m:
raise ImportError, "No module named " + mname
raise ImportError("No module named " + mname)
return m
def ensure_fromlist(self, m, fromlist, recursive=0):
@ -468,11 +467,11 @@ class ModuleImporter(BasicModuleImporter):
subname = "%s.%s" % (m.__name__, sub)
submod = self.import_it(sub, subname, m)
if not submod:
raise ImportError, "No module named " + subname
raise ImportError("No module named " + subname)
def import_it(self, partname, fqname, parent, force_load=0):
if not partname:
raise ValueError, "Empty module name"
raise ValueError("Empty module name")
if not force_load:
try:
return self.modules[fqname]

View File

@ -99,7 +99,7 @@ class ImportManager:
top_module = self._import_top_module(parts[0])
if not top_module:
# the topmost module wasn't found at all.
raise ImportError, 'No module named ' + fqname
raise ImportError('No module named ' + fqname)
# fast-path simple imports
if len(parts) == 1:
@ -137,7 +137,7 @@ class ImportManager:
# If the importer does not exist, then we have to bail. A missing
# importer means that something else imported the module, and we have
# no knowledge of how to get sub-modules out of the thing.
raise ImportError, 'No module named ' + fqname
raise ImportError('No module named ' + fqname)
def _determine_import_context(self, globals):
"""Returns the context in which a module should be imported.
@ -306,7 +306,7 @@ class Importer:
fqname = "%s.%s" % (m.__name__, part)
m = self._import_one(m, part, fqname)
if not m:
raise ImportError, "No module named " + fqname
raise ImportError("No module named " + fqname)
return m
def _import_fromlist(self, package, fromlist):
@ -325,7 +325,7 @@ class Importer:
subname = "%s.%s" % (package.__name__, sub)
submod = self._import_one(package, sub, subname)
if not submod:
raise ImportError, "cannot import name " + subname
raise ImportError("cannot import name " + subname)
def _do_import(self, parent, parts, fromlist):
"""Attempt to import the module relative to parent.
@ -377,7 +377,7 @@ class Importer:
object, then these names/values will be inserted *after* the module
has been loaded/initialized.
"""
raise RuntimeError, "get_code not implemented"
raise RuntimeError("get_code not implemented")
######################################################################
@ -452,7 +452,7 @@ def _os_bootstrap():
a = a + ':'
return a + b
else:
raise ImportError, 'no os specific module found'
raise ImportError('no os specific module found')
if join is None:
def join(a, b, sep=sep):

View File

@ -724,7 +724,7 @@ def getargspec(func):
args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = \
getfullargspec(func)
if kwonlyargs or ann:
raise ValueError, ("Function has keyword-only arguments or annotations"
raise ValueError("Function has keyword-only arguments or annotations"
", use getfullargspec() API which can support them")
return (args, varargs, varkw, defaults)

View File

@ -31,7 +31,7 @@ from Tkinter import _flatten, _cnfmerge, _default_root
# WARNING - TkVersion is a limited precision floating point number
if TkVersion < 3.999:
raise ImportError, "This version of Tix.py requires Tk 4.0 or higher"
raise ImportError("This version of Tix.py requires Tk 4.0 or higher")
import _tkinter # If this fails your Python may not be configured for Tk
@ -323,7 +323,7 @@ class TixWidget(Tkinter.Widget):
def __getattr__(self, name):
if name in self.subwidget_list:
return self.subwidget_list[name]
raise AttributeError, name
raise AttributeError(name)
def set_silent(self, value):
"""Set a variable without calling its action routine"""
@ -334,7 +334,7 @@ class TixWidget(Tkinter.Widget):
the sub-class)."""
n = self._subwidget_name(name)
if not n:
raise TclError, "Subwidget " + name + " not child of " + self._name
raise TclError("Subwidget " + name + " not child of " + self._name)
# Remove header of name and leading dot
n = n[len(self._w)+1:]
return self._nametowidget(n)
@ -385,7 +385,7 @@ class TixWidget(Tkinter.Widget):
if not master:
master = Tkinter._default_root
if not master:
raise RuntimeError, 'Too early to create image'
raise RuntimeError('Too early to create image')
if kw and cnf: cnf = _cnfmerge((cnf, kw))
elif kw: cnf = kw
options = ()
@ -475,7 +475,7 @@ class DisplayStyle:
master = _default_root # global from Tkinter
if not master and 'refwindow' in cnf: master=cnf['refwindow']
elif not master and 'refwindow' in kw: master= kw['refwindow']
elif not master: raise RuntimeError, "Too early to create display style: no root window"
elif not master: raise RuntimeError("Too early to create display style: no root window")
self.tk = master.tk
self.stylename = self.tk.call('tixDisplayStyle', itemtype,
*self._options(cnf,kw) )

View File

@ -158,7 +158,7 @@ def _tkerror(err):
def _exit(code='0'):
"""Internal function. Calling it will throw the exception SystemExit."""
raise SystemExit, code
raise SystemExit(code)
_varnum = 0
class Variable:
@ -1401,7 +1401,7 @@ class CallWrapper:
args = self.subst(*args)
return self.func(*args)
except SystemExit as msg:
raise SystemExit, msg
raise SystemExit(msg)
except:
self.widget._report_exception()
@ -1652,19 +1652,16 @@ class Tk(Misc, Wm):
# Version sanity checks
tk_version = self.tk.getvar('tk_version')
if tk_version != _tkinter.TK_VERSION:
raise RuntimeError, \
"tk.h version (%s) doesn't match libtk.a version (%s)" \
% (_tkinter.TK_VERSION, tk_version)
raise RuntimeError("tk.h version (%s) doesn't match libtk.a version (%s)"
% (_tkinter.TK_VERSION, tk_version))
# Under unknown circumstances, tcl_version gets coerced to float
tcl_version = str(self.tk.getvar('tcl_version'))
if tcl_version != _tkinter.TCL_VERSION:
raise RuntimeError, \
"tcl.h version (%s) doesn't match libtcl.a version (%s)" \
% (_tkinter.TCL_VERSION, tcl_version)
raise RuntimeError("tcl.h version (%s) doesn't match libtcl.a version (%s)" \
% (_tkinter.TCL_VERSION, tcl_version))
if TkVersion < 4.0:
raise RuntimeError, \
"Tk 4.0 or higher is required; found Tk %s" \
% str(TkVersion)
raise RuntimeError("Tk 4.0 or higher is required; found Tk %s"
% str(TkVersion))
# Create and register the tkerror and exit commands
# We need to inline parts of _register here, _ register
# would register differently-named commands.
@ -3182,7 +3179,7 @@ class OptionMenu(Menubutton):
if 'command' in kwargs:
del kwargs['command']
if kwargs:
raise TclError, 'unknown option -'+kwargs.keys()[0]
raise TclError('unknown option -'+kwargs.keys()[0])
menu.add_command(label=value,
command=_setit(variable, value, callback))
for v in values:
@ -3208,7 +3205,7 @@ class Image:
if not master:
master = _default_root
if not master:
raise RuntimeError, 'Too early to create image'
raise RuntimeError('Too early to create image')
self.tk = master.tk
if not name:
Image._last_id += 1

View File

@ -18,7 +18,7 @@ class Dialog:
# FIXME: should this be placed on the module level instead?
if TkVersion < 4.2:
raise TclError, "this module requires Tk 4.2 or newer"
raise TclError("this module requires Tk 4.2 or newer")
self.master = master
self.options = options

View File

@ -79,7 +79,7 @@ class Font:
self.delete_font = False
# confirm font exists
if self.name not in root.tk.call("font", "names"):
raise Tkinter._tkinter.TclError, "named font %s does not already exist" % (self.name,)
raise Tkinter._tkinter.TclError("named font %s does not already exist" % (self.name,))
# if font config info supplied, apply it
if font:
root.tk.call("font", "configure", self.name, *font)

View File

@ -231,7 +231,7 @@ class RawPen:
>>> turtle.color(0, .5, 0)
"""
if not args:
raise Error, "no color arguments"
raise Error("no color arguments")
if len(args) == 1:
color = args[0]
if type(color) == type(""):
@ -239,18 +239,18 @@ class RawPen:
try:
id = self._canvas.create_line(0, 0, 0, 0, fill=color)
except Tkinter.TclError:
raise Error, "bad color string: %r" % (color,)
raise Error("bad color string: %r" % (color,))
self._set_color(color)
return
try:
r, g, b = color
except:
raise Error, "bad color sequence: %r" % (color,)
raise Error("bad color sequence: %r" % (color,))
else:
try:
r, g, b = args
except:
raise Error, "bad color arguments: %r" % (args,)
raise Error("bad color arguments: %r" % (args,))
assert 0 <= r <= 1
assert 0 <= g <= 1
assert 0 <= b <= 1
@ -520,12 +520,12 @@ class RawPen:
try:
x, y = args[0]
except:
raise Error, "bad point argument: %r" % (args[0],)
raise Error("bad point argument: %r" % (args[0],))
else:
try:
x, y = args
except:
raise Error, "bad coordinates: %r" % (args[0],)
raise Error("bad coordinates: %r" % (args[0],))
x0, y0 = self._origin
self._goto(x0+x, y0-y)
@ -752,25 +752,25 @@ def setup(**geometry):
if width >= 0 or width == None:
_width = width
else:
raise ValueError, "width can not be less than 0"
raise ValueError("width can not be less than 0")
height = geometry.get('height',_height)
if height >= 0 or height == None:
_height = height
else:
raise ValueError, "height can not be less than 0"
raise ValueError("height can not be less than 0")
startx = geometry.get('startx', _startx)
if startx >= 0 or startx == None:
_startx = _startx
else:
raise ValueError, "startx can not be less than 0"
raise ValueError("startx can not be less than 0")
starty = geometry.get('starty', _starty)
if starty >= 0 or starty == None:
_starty = starty
else:
raise ValueError, "startx can not be less than 0"
raise ValueError("startx can not be less than 0")
if _root and _width and _height:

View File

@ -72,7 +72,7 @@ except ImportError:
Activates/queries locale processing.
"""
if value not in (None, '', 'C'):
raise Error, '_locale emulation only supports "C" locale'
raise Error('_locale emulation only supports "C" locale')
return 'C'
def strcoll(a,b):
@ -372,7 +372,7 @@ def _parse_localename(localename):
return tuple(code.split('.')[:2])
elif code == 'C':
return None, None
raise ValueError, 'unknown locale: %s' % localename
raise ValueError('unknown locale: %s' % localename)
def _build_localename(localetuple):
@ -458,7 +458,7 @@ def getlocale(category=LC_CTYPE):
"""
localename = _setlocale(category)
if category == LC_ALL and ';' in localename:
raise TypeError, 'category LC_ALL is not supported'
raise TypeError('category LC_ALL is not supported')
return _parse_localename(localename)
def setlocale(category, locale=None):

View File

@ -638,8 +638,8 @@ class Handler(Filterer):
This version is intended to be implemented by subclasses and so
raises a NotImplementedError.
"""
raise NotImplementedError, 'emit must be implemented '\
'by Handler subclasses'
raise NotImplementedError('emit must be implemented '
'by Handler subclasses')
def handle(self, record):
"""
@ -834,8 +834,8 @@ def setLoggerClass(klass):
"""
if klass != Logger:
if not issubclass(klass, Logger):
raise TypeError, "logger not derived from logging.Logger: " + \
klass.__name__
raise TypeError("logger not derived from logging.Logger: "
+ klass.__name__)
global _loggerClass
_loggerClass = klass
@ -1047,7 +1047,7 @@ class Logger(Filterer):
"""
if not isinstance(level, int):
if raiseExceptions:
raise TypeError, "level must be an integer"
raise TypeError("level must be an integer")
else:
return
if self.isEnabledFor(level):

View File

@ -246,7 +246,7 @@ def listen(port=DEFAULT_LOGGING_CONFIG_PORT):
stopListening().
"""
if not thread:
raise NotImplementedError, "listen() needs threading to work"
raise NotImplementedError("listen() needs threading to work")
class ConfigStreamHandler(StreamRequestHandler):
"""

View File

@ -920,7 +920,7 @@ class HTTPHandler(logging.Handler):
logging.Handler.__init__(self)
method = method.upper()
if method not in ["GET", "POST"]:
raise ValueError, "method must be GET or POST"
raise ValueError("method must be GET or POST")
self.host = host
self.url = url
self.method = method

View File

@ -143,7 +143,7 @@ def normpath(s):
i = i - 1
else:
# best way to handle this is to raise an exception
raise norm_error, 'Cannot use :: immediately after volume name'
raise norm_error('Cannot use :: immediately after volume name')
else:
i = i + 1

View File

@ -15,12 +15,12 @@ def url2pathname(pathname):
#
tp = urllib.splittype(pathname)[0]
if tp and tp != 'file':
raise RuntimeError, 'Cannot convert non-local URL to pathname'
raise RuntimeError('Cannot convert non-local URL to pathname')
# Turn starting /// into /, an empty hostname means current host
if pathname[:3] == '///':
pathname = pathname[2:]
elif pathname[:2] == '//':
raise RuntimeError, 'Cannot convert non-local URL to pathname'
raise RuntimeError('Cannot convert non-local URL to pathname')
components = pathname.split('/')
# Remove . and embedded ..
i = 0
@ -53,7 +53,7 @@ def pathname2url(pathname):
"""OS-specific conversion from a file system path to a relative URL
of the 'file' scheme; not recommended for general use."""
if '/' in pathname:
raise RuntimeError, "Cannot convert pathname containing slashes"
raise RuntimeError("Cannot convert pathname containing slashes")
components = pathname.split(':')
# Remove empty first and/or last component
if components[0] == '':

View File

@ -104,7 +104,7 @@ class MH:
if not os.path.isabs(path) and path[0] != '~':
path = os.path.join('~', path)
path = os.path.expanduser(path)
if not os.path.isdir(path): raise Error, 'MH() path not found'
if not os.path.isdir(path): raise Error('MH() path not found')
self.path = path
def __repr__(self):
@ -243,7 +243,7 @@ class Folder:
self.mh = mh
self.name = name
if not os.path.isdir(self.getfullname()):
raise Error, 'no folder %s' % name
raise Error('no folder %s' % name)
def __repr__(self):
"""String representation."""
@ -332,7 +332,7 @@ class Folder:
try:
return max(seqs['cur'])
except (ValueError, KeyError):
raise Error, "no cur message"
raise Error("no cur message")
def setcurrent(self, n):
"""Set the current message."""
@ -350,7 +350,7 @@ class Folder:
all = self.listmessages()
# Observed behavior: test for empty folder is done first
if not all:
raise Error, "no messages in %s" % self.name
raise Error("no messages in %s" % self.name)
# Common case first: all is frequently the default
if seq == 'all':
return all
@ -361,7 +361,7 @@ class Folder:
if tail[:1] in '-+':
dir, tail = tail[:1], tail[1:]
if not isnumeric(tail):
raise Error, "bad message list %s" % seq
raise Error("bad message list %s" % seq)
try:
count = int(tail)
except (ValueError, OverflowError):
@ -374,10 +374,10 @@ class Folder:
if not head in seqs:
if not msg:
msg = "bad message list %s" % seq
raise Error, msg, sys.exc_info()[2]
raise Error(msg).with_traceback(sys.exc_info()[2])
msgs = seqs[head]
if not msgs:
raise Error, "sequence %s empty" % head
raise Error("sequence %s empty" % head)
if dir == '-':
return msgs[-count:]
else:
@ -401,7 +401,7 @@ class Folder:
j = bisect(all, end)
r = all[i:j]
if not r:
raise Error, "bad message list %s" % seq
raise Error("bad message list %s" % seq)
return r
# Neither X:Y nor X-Y; must be a number or a (pseudo-)sequence
try:
@ -411,14 +411,14 @@ class Folder:
if not seq in seqs:
if not msg:
msg = "bad message list %s" % seq
raise Error, msg
raise Error(msg)
return seqs[seq]
else:
if n not in all:
if isnumeric(seq):
raise Error, "message %d doesn't exist" % n
raise Error("message %d doesn't exist" % n)
else:
raise Error, "no %s message" % seq
raise Error("no %s message" % seq)
else:
return [n]
@ -441,17 +441,17 @@ class Folder:
try:
return all[i]
except IndexError:
raise Error, "no next message"
raise Error("no next message")
if seq == 'prev':
n = self.getcurrent()
i = bisect(all, n-1)
if i == 0:
raise Error, "no prev message"
raise Error("no prev message")
try:
return all[i-1]
except IndexError:
raise Error, "no prev message"
raise Error, None
raise Error("no prev message")
raise Error()
def openmessage(self, n):
"""Open a message -- returns a Message object."""
@ -478,9 +478,9 @@ class Folder:
self.removefromallsequences(deleted)
if errors:
if len(errors) == 1:
raise os.error, errors[0]
raise os.error(errors[0])
else:
raise os.error, ('multiple errors:', errors)
raise os.error('multiple errors:', errors)
def refilemessages(self, list, tofolder, keepsequences=0):
"""Refile one or more messages -- may raise os.error.
@ -513,9 +513,9 @@ class Folder:
self.removefromallsequences(refiled.keys())
if errors:
if len(errors) == 1:
raise os.error, errors[0]
raise os.error(errors[0])
else:
raise os.error, ('multiple errors:', errors)
raise os.error('multiple errors:', errors)
def _copysequences(self, fromfolder, refileditems):
"""Helper for refilemessages() to copy sequences."""
@ -706,10 +706,10 @@ class Message(mimetools.Message):
list of SubMessage objects. Each submessage object behaves
(almost) as a Message object."""
if self.getmaintype() != 'multipart':
raise Error, 'Content-Type is not multipart/*'
raise Error('Content-Type is not multipart/*')
bdry = self.getparam('boundary')
if not bdry:
raise Error, 'multipart/* without boundary param'
raise Error('multipart/* without boundary param')
self.fp.seek(self.startofbody)
mf = multifile.MultiFile(self.fp)
mf.push(bdry)
@ -890,7 +890,7 @@ class IntSet:
elif len(list) == 2 and list[0] <= list[1]:
new.append((list[0], list[1]))
else:
raise ValueError, 'bad data passed to IntSet'
raise ValueError('bad data passed to IntSet')
self.pairs = self.pairs + new
self.normalize()

View File

@ -162,8 +162,7 @@ def decode(input, output, encoding):
if encoding in decodetab:
pipethrough(input, decodetab[encoding], output)
else:
raise ValueError, \
'unknown Content-Transfer-Encoding: %s' % encoding
raise ValueError('unknown Content-Transfer-Encoding: %s' % encoding)
def encode(input, output, encoding):
"""Encode common content-transfer-encodings (base64, quopri, uuencode)."""
@ -181,8 +180,7 @@ def encode(input, output, encoding):
if encoding in encodetab:
pipethrough(input, encodetab[encoding], output)
else:
raise ValueError, \
'unknown Content-Transfer-Encoding: %s' % encoding
raise ValueError('unknown Content-Transfer-Encoding: %s' % encoding)
# The following is no longer used for standard encodings

View File

@ -146,7 +146,7 @@ class ModuleFinder:
self.msgout(4, "determine_parent ->", parent)
return parent
if pname.count(".") < level:
raise ImportError, "relative importpath too deep"
raise ImportError("relative importpath too deep")
pname = ".".join(pname.split(".")[:-level])
parent = self.modules[pname]
self.msgout(4, "determine_parent ->", parent)
@ -191,7 +191,7 @@ class ModuleFinder:
self.msgout(4, "find_head_package ->", (q, tail))
return q, tail
self.msgout(4, "raise ImportError: No module named", qname)
raise ImportError, "No module named " + qname
raise ImportError("No module named " + qname)
def load_tail(self, q, tail):
self.msgin(4, "load_tail", q, tail)
@ -204,7 +204,7 @@ class ModuleFinder:
m = self.import_module(head, mname, m)
if not m:
self.msgout(4, "raise ImportError: No module named", mname)
raise ImportError, "No module named " + mname
raise ImportError("No module named " + mname)
self.msgout(4, "load_tail ->", m)
return m
@ -220,7 +220,7 @@ class ModuleFinder:
subname = "%s.%s" % (m.__name__, sub)
submod = self.import_module(sub, subname, m)
if not submod:
raise ImportError, "No module named " + subname
raise ImportError("No module named " + subname)
def find_all_submodules(self, m):
if not m.__path__:
@ -291,7 +291,7 @@ class ModuleFinder:
elif type == imp.PY_COMPILED:
if fp.read(4) != imp.get_magic():
self.msgout(2, "raise ImportError: Bad magic number", pathname)
raise ImportError, "Bad magic number in %s" % pathname
raise ImportError("Bad magic number in %s" % pathname)
fp.read(4)
co = marshal.load(fp)
else:
@ -470,7 +470,7 @@ class ModuleFinder:
fullname = name
if fullname in self.excludes:
self.msgout(3, "find_module -> Excluded", fullname)
raise ImportError, name
raise ImportError(name)
if path is None:
if name in sys.builtin_module_names:

View File

@ -89,7 +89,7 @@ def change_sequence(seq, action, seqno=_Unspecified, cond = _Unspecified):
seqno = seq[i][2]
seq[i] = (action, cond, seqno)
return
raise ValueError, "Action not found in sequence"
raise ValueError("Action not found in sequence")
def add_data(db, table, values):
v = db.OpenView("SELECT * FROM `%s`" % table)
@ -108,7 +108,7 @@ def add_data(db, table, values):
elif isinstance(field, Binary):
r.SetStream(i+1, field.name)
else:
raise TypeError, "Unsupported type %s" % field.__class__.__name__
raise TypeError("Unsupported type %s" % field.__class__.__name__)
try:
v.Modify(MSIMODIFY_INSERT, r)
except Exception as e:

View File

@ -60,10 +60,10 @@ class MultiFile:
if self.level > 0:
pos = pos + self.lastpos
else:
raise Error, "can't use whence=2 yet"
raise Error("can't use whence=2 yet")
if not 0 <= pos <= here or \
self.level > 0 and pos > self.lastpos:
raise Error, 'bad MultiFile.seek() call'
raise Error('bad MultiFile.seek() call')
self.fp.seek(pos + self.start)
self.level = 0
self.last = 0
@ -77,7 +77,7 @@ class MultiFile:
self.level = len(self.stack)
self.last = (self.level > 0)
if self.last:
raise Error, 'sudden EOF in MultiFile.readline()'
raise Error('sudden EOF in MultiFile.readline()')
return ''
assert self.level == 0
# Fast check to see if this is just data
@ -102,7 +102,7 @@ class MultiFile:
self.lastpos = self.tell() - len(line)
self.level = i+1
if self.level > 1:
raise Error,'Missing endmarker in MultiFile.readline()'
raise Error('Missing endmarker in MultiFile.readline()')
return ''
def readlines(self):
@ -128,7 +128,7 @@ class MultiFile:
def push(self, sep):
if self.level > 0:
raise Error, 'bad MultiFile.push() call'
raise Error('bad MultiFile.push() call')
self.stack.append(sep)
if self.seekable:
self.posstack.append(self.start)
@ -136,7 +136,7 @@ class MultiFile:
def pop(self):
if self.stack == []:
raise Error, 'bad MultiFile.pop() call'
raise Error('bad MultiFile.pop() call')
if self.level <= 1:
self.last = 0
else:

View File

@ -23,7 +23,7 @@ def url2pathname(url):
comp = url.split('|')
if len(comp) != 2 or comp[0][-1] not in string.ascii_letters:
error = 'Bad URL: ' + url
raise IOError, error
raise IOError(error)
drive = comp[0][-1].upper()
components = comp[1].split('/')
path = drive + ':'
@ -52,7 +52,7 @@ def pathname2url(p):
comp = p.split(':')
if len(comp) != 2 or len(comp[0]) > 1:
error = 'Bad path: ' + p
raise IOError, error
raise IOError(error)
drive = urllib.quote(comp[0].upper())
components = comp[1].split('\\')

View File

@ -239,10 +239,10 @@ class HelpFormatter:
self.level -= 1
def format_usage(self, usage):
raise NotImplementedError, "subclasses must implement"
raise NotImplementedError("subclasses must implement")
def format_heading(self, heading):
raise NotImplementedError, "subclasses must implement"
raise NotImplementedError("subclasses must implement")
def _format_text(self, text):
"""
@ -805,7 +805,7 @@ class Option:
parser.print_version()
parser.exit()
else:
raise RuntimeError, "unknown action %r" % self.action
raise RuntimeError("unknown action %r" % self.action)
return 1
@ -865,7 +865,7 @@ class Values:
elif mode == "loose":
self._update_loose(dict)
else:
raise ValueError, "invalid update mode: %r" % mode
raise ValueError("invalid update mode: %r" % mode)
def read_module(self, modname, mode="careful"):
__import__(modname)
@ -944,7 +944,7 @@ class OptionContainer:
def set_conflict_handler(self, handler):
if handler not in ("error", "resolve"):
raise ValueError, "invalid conflict_resolution value %r" % handler
raise ValueError("invalid conflict_resolution value %r" % handler)
self.conflict_handler = handler
def set_description(self, description):
@ -999,9 +999,9 @@ class OptionContainer:
elif len(args) == 1 and not kwargs:
option = args[0]
if not isinstance(option, Option):
raise TypeError, "not an Option instance: %r" % option
raise TypeError("not an Option instance: %r" % option)
else:
raise TypeError, "invalid arguments"
raise TypeError("invalid arguments")
self._check_conflict(option)
@ -1310,11 +1310,11 @@ class OptionParser (OptionContainer):
elif len(args) == 1 and not kwargs:
group = args[0]
if not isinstance(group, OptionGroup):
raise TypeError, "not an OptionGroup instance: %r" % group
raise TypeError("not an OptionGroup instance: %r" % group)
if group.parser is not self:
raise ValueError, "invalid OptionGroup (wrong parser)"
raise ValueError("invalid OptionGroup (wrong parser)")
else:
raise TypeError, "invalid arguments"
raise TypeError("invalid arguments")
self.option_groups.append(group)
return group

View File

@ -111,45 +111,33 @@ class Template:
def append(self, cmd, kind):
"""t.append(cmd, kind) adds a new step at the end."""
if type(cmd) is not type(''):
raise TypeError, \
'Template.append: cmd must be a string'
raise TypeError('Template.append: cmd must be a string')
if kind not in stepkinds:
raise ValueError, \
'Template.append: bad kind %r' % (kind,)
raise ValueError('Template.append: bad kind %r' % (kind,))
if kind == SOURCE:
raise ValueError, \
'Template.append: SOURCE can only be prepended'
raise ValueError('Template.append: SOURCE can only be prepended')
if self.steps and self.steps[-1][1] == SINK:
raise ValueError, \
'Template.append: already ends with SINK'
raise ValueError('Template.append: already ends with SINK')
if kind[0] == 'f' and not re.search(r'\$IN\b', cmd):
raise ValueError, \
'Template.append: missing $IN in cmd'
raise ValueError('Template.append: missing $IN in cmd')
if kind[1] == 'f' and not re.search(r'\$OUT\b', cmd):
raise ValueError, \
'Template.append: missing $OUT in cmd'
raise ValueError('Template.append: missing $OUT in cmd')
self.steps.append((cmd, kind))
def prepend(self, cmd, kind):
"""t.prepend(cmd, kind) adds a new step at the front."""
if type(cmd) is not type(''):
raise TypeError, \
'Template.prepend: cmd must be a string'
raise TypeError('Template.prepend: cmd must be a string')
if kind not in stepkinds:
raise ValueError, \
'Template.prepend: bad kind %r' % (kind,)
raise ValueError('Template.prepend: bad kind %r' % (kind,))
if kind == SINK:
raise ValueError, \
'Template.prepend: SINK can only be appended'
raise ValueError('Template.prepend: SINK can only be appended')
if self.steps and self.steps[0][1] == SOURCE:
raise ValueError, \
'Template.prepend: already begins with SOURCE'
raise ValueError('Template.prepend: already begins with SOURCE')
if kind[0] == 'f' and not re.search(r'\$IN\b', cmd):
raise ValueError, \
'Template.prepend: missing $IN in cmd'
raise ValueError('Template.prepend: missing $IN in cmd')
if kind[1] == 'f' and not re.search(r'\$OUT\b', cmd):
raise ValueError, \
'Template.prepend: missing $OUT in cmd'
raise ValueError('Template.prepend: missing $OUT in cmd')
self.steps.insert(0, (cmd, kind))
def open(self, file, rw):
@ -159,8 +147,8 @@ class Template:
return self.open_r(file)
if rw == 'w':
return self.open_w(file)
raise ValueError, \
'Template.open: rw must be \'r\' or \'w\', not %r' % (rw,)
raise ValueError('Template.open: rw must be \'r\' or \'w\', not %r'
% (rw,))
def open_r(self, file):
"""t.open_r(file) and t.open_w(file) implement
@ -168,8 +156,7 @@ class Template:
if not self.steps:
return open(file, 'r')
if self.steps[-1][1] == SINK:
raise ValueError, \
'Template.open_r: pipeline ends width SINK'
raise ValueError('Template.open_r: pipeline ends width SINK')
cmd = self.makepipeline(file, '')
return os.popen(cmd, 'r')
@ -177,8 +164,7 @@ class Template:
if not self.steps:
return open(file, 'w')
if self.steps[0][1] == SOURCE:
raise ValueError, \
'Template.open_w: pipeline begins with SOURCE'
raise ValueError('Template.open_w: pipeline begins with SOURCE')
cmd = self.makepipeline('', file)
return os.popen(cmd, 'w')

View File

@ -378,7 +378,7 @@ class _popen:
def __init__(self,cmd,mode='r',bufsize=None):
if mode != 'r':
raise ValueError,'popen()-emulation only supports read mode'
raise ValueError('popen()-emulation only supports read mode')
import tempfile
self.tmpfile = tmpfile = tempfile.mktemp()
os.system(cmd + ' > %s' % tmpfile)
@ -490,7 +490,7 @@ def _syscmd_ver(system='', release='', version='',
pipe = popen(cmd)
info = pipe.read()
if pipe.close():
raise os.error,'command failed'
raise os.error('command failed')
# XXX How can I supress shell errors from being written
# to stderr ?
except os.error as why:

View File

@ -340,7 +340,7 @@ class POP3_SSL(POP3):
continue
break
if not self.sock:
raise socket.error, msg
raise socket.error(msg)
self.file = self.sock.makefile('rb')
self.sslobj = socket.ssl(self.sock, self.keyfile, self.certfile)
self._debugging = 0

View File

@ -83,7 +83,7 @@ class Stats:
keys = kwds.keys()
keys.sort()
extras = ", ".join(["%s=%s" % (k, kwds[k]) for k in keys])
raise ValueError, "unrecognized keyword args: %s" % extras
raise ValueError("unrecognized keyword args: %s" % extras)
if not len(args):
arg = None
else:
@ -131,8 +131,8 @@ class Stats:
self.stats = arg.stats
arg.stats = {}
if not self.stats:
raise TypeError, "Cannot create or construct a %r object from '%r''" % (
self.__class__, arg)
raise TypeError("Cannot create or construct a %r object from '%r''"
% (self.__class__, arg))
return
def get_top_level_stats(self):

View File

@ -57,7 +57,7 @@ def _open_terminal():
try:
tty_name, master_fd = sgi._getpty(os.O_RDWR, 0o666, 0)
except IOError as msg:
raise os.error, msg
raise os.error(msg)
return master_fd, tty_name
for x in 'pqrstuvwxyzPQRST':
for y in '0123456789abcdef':
@ -67,7 +67,7 @@ def _open_terminal():
except os.error:
continue
return (fd, '/dev/tty' + x + y)
raise os.error, 'out of pty devices'
raise os.error('out of pty devices')
def slave_open(tty_name):
"""slave_open(tty_name) -> slave_fd

View File

@ -328,7 +328,7 @@ class Doc:
"""Raise an exception for unimplemented types."""
message = "don't know how to document object%s of type %s" % (
name and ' ' + repr(name), type(object).__name__)
raise TypeError, message
raise TypeError(message)
docmodule = docclass = docroutine = docother = docproperty = docdata = fail
@ -1463,7 +1463,7 @@ def resolve(thing, forceload=0):
if isinstance(thing, str):
object = locate(thing, forceload)
if not object:
raise ImportError, 'no Python documentation found for %r' % thing
raise ImportError('no Python documentation found for %r' % thing)
return object, thing
else:
return thing, getattr(thing, '__name__', None)

View File

@ -157,18 +157,18 @@ class Random(_random.Random):
# common case while still doing adequate error checking.
istart = int(start)
if istart != start:
raise ValueError, "non-integer arg 1 for randrange()"
raise ValueError("non-integer arg 1 for randrange()")
if stop is default:
if istart > 0:
if istart >= maxwidth:
return self._randbelow(istart)
return int(self.random() * istart)
raise ValueError, "empty range for randrange()"
raise ValueError("empty range for randrange()")
# stop argument supplied.
istop = int(stop)
if istop != stop:
raise ValueError, "non-integer stop for randrange()"
raise ValueError("non-integer stop for randrange()")
width = istop - istart
if step == 1 and width > 0:
# Note that
@ -188,21 +188,21 @@ class Random(_random.Random):
return int(istart + self._randbelow(width))
return int(istart + int(self.random()*width))
if step == 1:
raise ValueError, "empty range for randrange() (%d,%d, %d)" % (istart, istop, width)
raise ValueError("empty range for randrange() (%d,%d, %d)" % (istart, istop, width))
# Non-unit step argument supplied.
istep = int(step)
if istep != step:
raise ValueError, "non-integer step for randrange()"
raise ValueError("non-integer step for randrange()")
if istep > 0:
n = (width + istep - 1) // istep
elif istep < 0:
n = (width + istep + 1) // istep
else:
raise ValueError, "zero step for randrange()"
raise ValueError("zero step for randrange()")
if n <= 0:
raise ValueError, "empty range for randrange()"
raise ValueError("empty range for randrange()")
if n >= maxwidth:
return istart + istep*self._randbelow(n)
@ -300,7 +300,7 @@ class Random(_random.Random):
n = len(population)
if not 0 <= k <= n:
raise ValueError, "sample larger than population"
raise ValueError("sample larger than population")
random = self.random
_int = int
result = [None] * k
@ -459,7 +459,7 @@ class Random(_random.Random):
# Warning: a few older sources define the gamma distribution in terms
# of alpha > -1.0
if alpha <= 0.0 or beta <= 0.0:
raise ValueError, 'gammavariate: alpha and beta must be > 0.0'
raise ValueError('gammavariate: alpha and beta must be > 0.0')
random = self.random
if alpha > 1.0:

View File

@ -226,11 +226,8 @@ def _compile(*key):
if isinstance(pattern, _pattern_type):
return pattern
if not sre_compile.isstring(pattern):
raise TypeError, "first argument must be string or compiled pattern"
try:
raise TypeError("first argument must be string or compiled pattern")
p = sre_compile.compile(pattern, flags)
except error as v:
raise error, v # invalid expression
if len(_cache) >= _MAXCACHE:
_cache.clear()
_cache[cachekey] = p
@ -242,10 +239,7 @@ def _compile_repl(*key):
if p is not None:
return p
repl, pattern = key
try:
p = sre_parse.parse_template(repl, pattern)
except error as v:
raise error, v # invalid expression
if len(_cache_repl) >= _MAXCACHE:
_cache_repl.clear()
_cache_repl[key] = p

View File

@ -112,7 +112,7 @@ class Message:
def rewindbody(self):
"""Rewind the file to the start of the body (if seekable)."""
if not self.seekable:
raise IOError, "unseekable file"
raise IOError("unseekable file")
self.fp.seek(self.startofbody)
def readheaders(self):

View File

@ -55,7 +55,7 @@ class Completer:
"""
if namespace and not isinstance(namespace, dict):
raise TypeError,'namespace must be a dictionary'
raise TypeError('namespace must be a dictionary')
# Don't bind to namespace quite yet, but flag whether the user wants a
# specific namespace or to use __main__.__dict__. This will allow us

View File

@ -166,7 +166,7 @@ class shlex:
if self.debug >= 2:
print("shlex: I see EOF in quotes state")
# XXX what error should be raised here?
raise ValueError, "No closing quotation"
raise ValueError("No closing quotation")
if nextchar == self.state:
if not self.posix:
self.token = self.token + nextchar
@ -185,7 +185,7 @@ class shlex:
if self.debug >= 2:
print("shlex: I see EOF in escape state")
# XXX what error should be raised here?
raise ValueError, "No escaped character"
raise ValueError("No escaped character")
# In posix shells, only the quote itself or the escape
# character may be escaped within quotes.
if escapedstate in self.quotes and \

View File

@ -38,7 +38,7 @@ def _samefile(src, dst):
def copyfile(src, dst):
"""Copy data from src to dst"""
if _samefile(src, dst):
raise Error, "`%s` and `%s` are the same file" % (src, dst)
raise Error("`%s` and `%s` are the same file" % (src, dst))
fsrc = None
fdst = None
@ -137,7 +137,7 @@ def copytree(src, dst, symlinks=False):
except OSError as why:
errors.extend((src, dst, str(why)))
if errors:
raise Error, errors
raise Error(errors)
def rmtree(path, ignore_errors=False, onerror=None):
"""Recursively delete a directory tree.
@ -194,7 +194,7 @@ def move(src, dst):
except OSError:
if os.path.isdir(src):
if destinsrc(src, dst):
raise Error, "Cannot move a directory '%s' into itself '%s'." % (src, dst)
raise Error("Cannot move a directory '%s' into itself '%s'." % (src, dst))
copytree(src, dst, symlinks=True)
rmtree(src)
else:

View File

@ -69,7 +69,7 @@ def _compile(code, pattern, flags):
emit(OPCODES[ANY])
elif op in REPEATING_CODES:
if flags & SRE_FLAG_TEMPLATE:
raise error, "internal: unsupported template operator"
raise error("internal: unsupported template operator")
emit(OPCODES[REPEAT])
skip = _len(code); emit(0)
emit(av[0])
@ -118,7 +118,7 @@ def _compile(code, pattern, flags):
else:
lo, hi = av[1].getwidth()
if lo != hi:
raise error, "look-behind requires fixed-width pattern"
raise error("look-behind requires fixed-width pattern")
emit(lo) # look behind
_compile(code, av[1], flags)
emit(OPCODES[SUCCESS])
@ -179,7 +179,7 @@ def _compile(code, pattern, flags):
else:
code[skipyes] = _len(code) - skipyes + 1
else:
raise ValueError, ("unsupported operand type", op)
raise ValueError("unsupported operand type", op)
def _compile_charset(charset, flags, code, fixup=None):
# compile charset subprogram
@ -207,7 +207,7 @@ def _compile_charset(charset, flags, code, fixup=None):
else:
emit(CHCODES[av])
else:
raise error, "internal: unsupported set operator"
raise error("internal: unsupported set operator")
emit(OPCODES[FAILURE])
def _optimize_charset(charset, fixup):
@ -362,7 +362,7 @@ def _simple(av):
# check if av is a "simple" operator
lo, hi = av[2].getwidth()
if lo == 0 and hi == MAXREPEAT:
raise error, "nothing to repeat"
raise error("nothing to repeat")
return lo == hi == 1 and av[2][0][0] != SUBPATTERN
def _compile_info(code, pattern, flags):

View File

@ -81,7 +81,7 @@ class Pattern:
if name is not None:
ogid = self.groupdict.get(name, None)
if ogid is not None:
raise error, ("redefinition of group name %s as group %d; "
raise error("redefinition of group name %s as group %d; "
"was group %d" % (repr(name), gid, ogid))
self.groupdict[name] = gid
self.open.append(gid)
@ -196,7 +196,7 @@ class Tokenizer:
try:
c = self.string[self.index + 1]
except IndexError:
raise error, "bogus escape (end of line)"
raise error("bogus escape (end of line)")
char = char + c
self.index = self.index + len(char)
self.next = char
@ -246,7 +246,7 @@ def _class_escape(source, escape):
escape = escape + source.get()
escape = escape[2:]
if len(escape) != 2:
raise error, "bogus escape: %s" % repr("\\" + escape)
raise error("bogus escape: %s" % repr("\\" + escape))
return LITERAL, int(escape, 16) & 0xff
elif c in OCTDIGITS:
# octal escape (up to three digits)
@ -255,12 +255,12 @@ def _class_escape(source, escape):
escape = escape[1:]
return LITERAL, int(escape, 8) & 0xff
elif c in DIGITS:
raise error, "bogus escape: %s" % repr(escape)
raise error("bogus escape: %s" % repr(escape))
if len(escape) == 2:
return LITERAL, ord(escape[1])
except ValueError:
pass
raise error, "bogus escape: %s" % repr(escape)
raise error("bogus escape: %s" % repr(escape))
def _escape(source, escape, state):
# handle escape code in expression
@ -297,14 +297,14 @@ def _escape(source, escape, state):
group = int(escape[1:])
if group < state.groups:
if not state.checkgroup(group):
raise error, "cannot refer to open group"
raise error("cannot refer to open group")
return GROUPREF, group
raise ValueError
if len(escape) == 2:
return LITERAL, ord(escape[1])
except ValueError:
pass
raise error, "bogus escape: %s" % repr(escape)
raise error("bogus escape: %s" % repr(escape))
def _parse_sub(source, state, nested=1):
# parse an alternation: a|b|c
@ -321,7 +321,7 @@ def _parse_sub(source, state, nested=1):
if not source.next or sourcematch(")", 0):
break
else:
raise error, "pattern not properly closed"
raise error("pattern not properly closed")
if len(items) == 1:
return items[0]
@ -370,11 +370,11 @@ def _parse_sub_cond(source, state, condgroup):
if source.match("|"):
item_no = _parse(source, state)
if source.match("|"):
raise error, "conditional backref with more than two branches"
raise error("conditional backref with more than two branches")
else:
item_no = None
if source.next and not source.match(")", 0):
raise error, "pattern not properly closed"
raise error("pattern not properly closed")
subpattern = SubPattern(state)
subpattern.append((GROUPREF_EXISTS, (condgroup, item_yes, item_no)))
return subpattern
@ -439,7 +439,7 @@ def _parse(source, state):
elif this:
code1 = LITERAL, ord(this)
else:
raise error, "unexpected end of regular expression"
raise error("unexpected end of regular expression")
if sourcematch("-"):
# potential range
this = sourceget()
@ -455,14 +455,14 @@ def _parse(source, state):
else:
code2 = LITERAL, ord(this)
if code1[0] != LITERAL or code2[0] != LITERAL:
raise error, "bad character range"
raise error("bad character range")
lo = code1[1]
hi = code2[1]
if hi < lo:
raise error, "bad character range"
raise error("bad character range")
setappend((RANGE, (lo, hi)))
else:
raise error, "unexpected end of regular expression"
raise error("unexpected end of regular expression")
else:
if code1[0] is IN:
code1 = code1[1][0]
@ -509,18 +509,18 @@ def _parse(source, state):
if hi:
max = int(hi)
if max < min:
raise error, "bad repeat interval"
raise error("bad repeat interval")
else:
raise error, "not supported"
raise error("not supported")
# figure out which item to repeat
if subpattern:
item = subpattern[-1:]
else:
item = None
if not item or (_len(item) == 1 and item[0][0] == AT):
raise error, "nothing to repeat"
raise error("nothing to repeat")
if item[0][0] in REPEATCODES:
raise error, "multiple repeat"
raise error("multiple repeat")
if sourcematch("?"):
subpattern[-1] = (MIN_REPEAT, (min, max, item))
else:
@ -544,35 +544,35 @@ def _parse(source, state):
while 1:
char = sourceget()
if char is None:
raise error, "unterminated name"
raise error("unterminated name")
if char == ">":
break
name = name + char
group = 1
if not isname(name):
raise error, "bad character in group name"
raise error("bad character in group name")
elif sourcematch("="):
# named backreference
name = ""
while 1:
char = sourceget()
if char is None:
raise error, "unterminated name"
raise error("unterminated name")
if char == ")":
break
name = name + char
if not isname(name):
raise error, "bad character in group name"
raise error("bad character in group name")
gid = state.groupdict.get(name)
if gid is None:
raise error, "unknown group name"
raise error("unknown group name")
subpatternappend((GROUPREF, gid))
continue
else:
char = sourceget()
if char is None:
raise error, "unexpected end of pattern"
raise error, "unknown specifier: ?P%s" % char
raise error("unexpected end of pattern")
raise error("unknown specifier: ?P%s" % char)
elif sourcematch(":"):
# non-capturing group
group = 2
@ -583,7 +583,7 @@ def _parse(source, state):
break
sourceget()
if not sourcematch(")"):
raise error, "unbalanced parenthesis"
raise error("unbalanced parenthesis")
continue
elif source.next in ASSERTCHARS:
# lookahead assertions
@ -591,12 +591,12 @@ def _parse(source, state):
dir = 1
if char == "<":
if source.next not in LOOKBEHINDASSERTCHARS:
raise error, "syntax error"
raise error("syntax error")
dir = -1 # lookbehind
char = sourceget()
p = _parse_sub(source, state)
if not sourcematch(")"):
raise error, "unbalanced parenthesis"
raise error("unbalanced parenthesis")
if char == "=":
subpatternappend((ASSERT, (dir, p)))
else:
@ -608,7 +608,7 @@ def _parse(source, state):
while 1:
char = sourceget()
if char is None:
raise error, "unterminated name"
raise error("unterminated name")
if char == ")":
break
condname = condname + char
@ -616,16 +616,16 @@ def _parse(source, state):
if isname(condname):
condgroup = state.groupdict.get(condname)
if condgroup is None:
raise error, "unknown group name"
raise error("unknown group name")
else:
try:
condgroup = int(condname)
except ValueError:
raise error, "bad character in group name"
raise error("bad character in group name")
else:
# flags
if not source.next in FLAGS:
raise error, "unexpected end of pattern"
raise error("unexpected end of pattern")
while source.next in FLAGS:
state.flags = state.flags | FLAGS[sourceget()]
if group:
@ -640,7 +640,7 @@ def _parse(source, state):
else:
p = _parse_sub(source, state)
if not sourcematch(")"):
raise error, "unbalanced parenthesis"
raise error("unbalanced parenthesis")
if group is not None:
state.closegroup(group)
subpatternappend((SUBPATTERN, (group, p)))
@ -648,10 +648,10 @@ def _parse(source, state):
while 1:
char = sourceget()
if char is None:
raise error, "unexpected end of pattern"
raise error("unexpected end of pattern")
if char == ")":
break
raise error, "unknown extension"
raise error("unknown extension")
elif this == "^":
subpatternappend((AT, AT_BEGINNING))
@ -664,7 +664,7 @@ def _parse(source, state):
subpatternappend(code)
else:
raise error, "parser error"
raise error("parser error")
return subpattern
@ -682,9 +682,9 @@ def parse(str, flags=0, pattern=None):
tail = source.get()
if tail == ")":
raise error, "unbalanced parenthesis"
raise error("unbalanced parenthesis")
elif tail:
raise error, "bogus characters at end of regular expression"
raise error("bogus characters at end of regular expression")
if flags & SRE_FLAG_DEBUG:
p.dump()
@ -726,23 +726,23 @@ def parse_template(source, pattern):
while 1:
char = sget()
if char is None:
raise error, "unterminated group name"
raise error("unterminated group name")
if char == ">":
break
name = name + char
if not name:
raise error, "bad group name"
raise error("bad group name")
try:
index = int(name)
if index < 0:
raise error, "negative group number"
raise error("negative group number")
except ValueError:
if not isname(name):
raise error, "bad character in group name"
raise error("bad character in group name")
try:
index = pattern.groupindex[name]
except KeyError:
raise IndexError, "unknown group name"
raise IndexError("unknown group name")
a((MARK, index))
elif c == "0":
if s.next in OCTDIGITS:
@ -792,7 +792,7 @@ def expand_template(template, match):
for index, group in groups:
literals[index] = s = g(group)
if s is None:
raise error, "unmatched group"
raise error("unmatched group")
except IndexError:
raise error, "invalid group reference"
raise error("invalid group reference")
return sep.join(literals)

View File

@ -55,7 +55,7 @@ def maketrans(fromstr, tostr):
"""
if len(fromstr) != len(tostr):
raise ValueError, "maketrans arguments must have same length"
raise ValueError("maketrans arguments must have same length")
global _idmapL
if not _idmapL:
_idmapL = list(_idmap)

View File

@ -166,18 +166,18 @@ class Au_read:
self._soundpos = 0
magic = int(_read_u32(file))
if magic != AUDIO_FILE_MAGIC:
raise Error, 'bad magic number'
raise Error('bad magic number')
self._hdr_size = int(_read_u32(file))
if self._hdr_size < 24:
raise Error, 'header size too small'
raise Error('header size too small')
if self._hdr_size > 100:
raise Error, 'header size ridiculously large'
raise Error('header size ridiculously large')
self._data_size = _read_u32(file)
if self._data_size != AUDIO_UNKNOWN_SIZE:
self._data_size = int(self._data_size)
self._encoding = int(_read_u32(file))
if self._encoding not in _simple_encodings:
raise Error, 'encoding not (yet) supported'
raise Error('encoding not (yet) supported')
if self._encoding in (AUDIO_FILE_ENCODING_MULAW_8,
AUDIO_FILE_ENCODING_ALAW_8):
self._sampwidth = 2
@ -191,7 +191,7 @@ class Au_read:
elif self._encoding == AUDIO_FILE_ENCODING_LINEAR_32:
self._framesize = self._sampwidth = 4
else:
raise Error, 'unknown encoding'
raise Error('unknown encoding')
self._framerate = int(_read_u32(file))
self._nchannels = int(_read_u32(file))
self._framesize = self._framesize * self._nchannels
@ -248,7 +248,7 @@ class Au_read:
return None
def getmark(self, id):
raise Error, 'no marks'
raise Error('no marks')
def readframes(self, nframes):
if self._encoding in _simple_encodings:
@ -271,7 +271,7 @@ class Au_read:
def setpos(self, pos):
if pos < 0 or pos > self.getnframes():
raise Error, 'position not in range'
raise Error('position not in range')
self._file.seek(pos * self._framesize + self._hdr_size)
self._soundpos = pos
@ -305,43 +305,43 @@ class Au_write:
def setnchannels(self, nchannels):
if self._nframeswritten:
raise Error, 'cannot change parameters after starting to write'
raise Error('cannot change parameters after starting to write')
if nchannels not in (1, 2, 4):
raise Error, 'only 1, 2, or 4 channels supported'
raise Error('only 1, 2, or 4 channels supported')
self._nchannels = nchannels
def getnchannels(self):
if not self._nchannels:
raise Error, 'number of channels not set'
raise Error('number of channels not set')
return self._nchannels
def setsampwidth(self, sampwidth):
if self._nframeswritten:
raise Error, 'cannot change parameters after starting to write'
raise Error('cannot change parameters after starting to write')
if sampwidth not in (1, 2, 4):
raise Error, 'bad sample width'
raise Error('bad sample width')
self._sampwidth = sampwidth
def getsampwidth(self):
if not self._framerate:
raise Error, 'sample width not specified'
raise Error('sample width not specified')
return self._sampwidth
def setframerate(self, framerate):
if self._nframeswritten:
raise Error, 'cannot change parameters after starting to write'
raise Error('cannot change parameters after starting to write')
self._framerate = framerate
def getframerate(self):
if not self._framerate:
raise Error, 'frame rate not set'
raise Error('frame rate not set')
return self._framerate
def setnframes(self, nframes):
if self._nframeswritten:
raise Error, 'cannot change parameters after starting to write'
raise Error('cannot change parameters after starting to write')
if nframes < 0:
raise Error, '# of frames cannot be negative'
raise Error('# of frames cannot be negative')
self._nframes = nframes
def getnframes(self):
@ -351,7 +351,7 @@ class Au_write:
if type in ('NONE', 'ULAW'):
self._comptype = type
else:
raise Error, 'unknown compression type'
raise Error('unknown compression type')
def getcomptype(self):
return self._comptype
@ -411,11 +411,11 @@ class Au_write:
def _ensure_header_written(self):
if not self._nframeswritten:
if not self._nchannels:
raise Error, '# of channels not specified'
raise Error('# of channels not specified')
if not self._sampwidth:
raise Error, 'sample width not specified'
raise Error('sample width not specified')
if not self._framerate:
raise Error, 'frame rate not specified'
raise Error('frame rate not specified')
self._write_header()
def _write_header(self):
@ -430,12 +430,12 @@ class Au_write:
encoding = AUDIO_FILE_ENCODING_LINEAR_32
self._framesize = 4
else:
raise Error, 'internal error'
raise Error('internal error')
elif self._comptype == 'ULAW':
encoding = AUDIO_FILE_ENCODING_MULAW_8
self._framesize = 1
else:
raise Error, 'internal error'
raise Error('internal error')
self._framesize = self._framesize * self._nchannels
_write_u32(self._file, AUDIO_FILE_MAGIC)
header_size = 25 + len(self._info)
@ -470,6 +470,6 @@ def open(f, mode=None):
elif mode in ('w', 'wb'):
return Au_write(f)
else:
raise Error, "mode must be 'r', 'rb', 'w', or 'wb'"
raise Error("mode must be 'r', 'rb', 'w', or 'wb'")
openfp = open

View File

@ -14,7 +14,7 @@ def get_long_be(s):
def gethdr(fp):
"""Read a sound header from an open file."""
if fp.read(4) != MAGIC:
raise error, 'gethdr: bad magic word'
raise error('gethdr: bad magic word')
hdr_size = get_long_be(fp.read(4))
data_size = get_long_be(fp.read(4))
encoding = get_long_be(fp.read(4))
@ -22,7 +22,7 @@ def gethdr(fp):
channels = get_long_be(fp.read(4))
excess = hdr_size - 24
if excess < 0:
raise error, 'gethdr: bad hdr_size'
raise error('gethdr: bad hdr_size')
if excess > 0:
info = fp.read(excess)
else:

View File

@ -240,7 +240,7 @@ class Symbol:
Raises ValueError if the name is bound to multiple namespaces.
"""
if len(self.__namespaces) != 1:
raise ValueError, "name is bound to multiple namespaces"
raise ValueError("name is bound to multiple namespaces")
return self.__namespaces[0]
if __name__ == "__main__":

View File

@ -57,7 +57,7 @@ if sys.platform == 'mac':
# handling. In many places it is assumed a simple substitution of / by the
# local os.path.sep is good enough to convert pathnames, but this does not
# work with the mac rooted:path:name versus :nonrooted:path:name syntax
raise ImportError, "tarfile does not work for platform==mac"
raise ImportError("tarfile does not work for platform==mac")
try:
import grp, pwd

View File

@ -394,7 +394,7 @@ class Telnet:
buf = self.cookedq
self.cookedq = ''
if not buf and self.eof and not self.rawq:
raise EOFError, 'telnet connection closed'
raise EOFError('telnet connection closed')
return buf
def read_sb_data(self):

View File

@ -204,8 +204,8 @@ def _get_default_tempdir():
if e[0] != _errno.EEXIST:
break # no point trying more names in this directory
pass
raise IOError, (_errno.ENOENT,
("No usable temporary directory found in %s" % dirlist))
raise IOError(_errno.ENOENT,
"No usable temporary directory found in %s" % dirlist)
_name_sequence = None
@ -240,7 +240,7 @@ def _mkstemp_inner(dir, pre, suf, flags):
continue # try again
raise
raise IOError, (_errno.EEXIST, "No usable temporary file name found")
raise IOError(_errno.EEXIST, "No usable temporary file name found")
# User visible interfaces.
@ -331,7 +331,7 @@ def mkdtemp(suffix="", prefix=template, dir=None):
continue # try again
raise
raise IOError, (_errno.EEXIST, "No usable temporary directory name found")
raise IOError(_errno.EEXIST, "No usable temporary directory name found")
def mktemp(suffix="", prefix=template, dir=None):
"""mktemp([suffix, [prefix, [dir]]])
@ -361,7 +361,7 @@ def mktemp(suffix="", prefix=template, dir=None):
if not _exists(file):
return file
raise IOError, (_errno.EEXIST, "No usable temporary filename found")
raise IOError(_errno.EEXIST, "No usable temporary filename found")
class _TemporaryFileWrapper:
"""Temporary file wrapper

View File

@ -326,7 +326,7 @@ class _BoundedSemaphore(_Semaphore):
def release(self):
if self._value >= self._initial_value:
raise ValueError, "Semaphore released too many times"
raise ValueError("Semaphore released too many times")
return _Semaphore.release(self)

View File

@ -269,7 +269,7 @@ def generate_tokens(readline):
if contstr: # continued string
if not line:
raise TokenError, ("EOF in multi-line string", strstart)
raise TokenError("EOF in multi-line string", strstart)
endmatch = endprog.match(line)
if endmatch:
pos = end = endmatch.end(0)
@ -325,7 +325,7 @@ def generate_tokens(readline):
else: # continued statement
if not line:
raise TokenError, ("EOF in multi-line statement", (lnum, 0))
raise TokenError("EOF in multi-line statement", (lnum, 0))
continued = 0
while pos < max:

View File

@ -130,7 +130,8 @@ class TestResult:
if exctype is test.failureException:
# Skip assert*() traceback levels
length = self._count_relevant_tb_levels(tb)
return ''.join(traceback.format_exception(exctype, value, tb, length))
return ''.join(traceback.format_exception(exctype, value,
tb, length))
return ''.join(traceback.format_exception(exctype, value, tb))
def _is_relevant_tb_level(self, tb):
@ -186,8 +187,8 @@ class TestCase:
testMethod = getattr(self, methodName)
self._testMethodDoc = testMethod.__doc__
except AttributeError:
raise ValueError, "no such test method in %s: %s" % \
(self.__class__, methodName)
raise ValueError("no such test method in %s: %s"
% (self.__class__, methodName))
def setUp(self):
"Hook method for setting up the test fixture before exercising it."
@ -288,15 +289,15 @@ class TestCase:
def fail(self, msg=None):
"""Fail immediately, with the given message."""
raise self.failureException, msg
raise self.failureException(msg)
def failIf(self, expr, msg=None):
"Fail the test if the expression is true."
if expr: raise self.failureException, msg
if expr: raise self.failureException(msg)
def failUnless(self, expr, msg=None):
"""Fail the test unless the expression is true."""
if not expr: raise self.failureException, msg
if not expr: raise self.failureException(msg)
def failUnlessRaises(self, excClass, callableObj, *args, **kwargs):
"""Fail unless an exception of class excClass is thrown
@ -313,24 +314,22 @@ class TestCase:
else:
excName = str(getattr(excClass, '__name__', excClass))
objName = str(getattr(callableObj, '__name__', callableObj))
raise self.failureException, "%s not raised by %s" % (excName,
objName)
raise self.failureException("%s not raised by %s" % (excName,
objName))
def failUnlessEqual(self, first, second, msg=None):
"""Fail if the two objects are unequal as determined by the '=='
operator.
"""
if not first == second:
raise self.failureException, \
(msg or '%r != %r' % (first, second))
raise self.failureException(msg or '%r != %r' % (first, second))
def failIfEqual(self, first, second, msg=None):
"""Fail if the two objects are equal as determined by the '=='
operator.
"""
if first == second:
raise self.failureException, \
(msg or '%r == %r' % (first, second))
raise self.failureException(msg or '%r == %r' % (first, second))
def failUnlessAlmostEqual(self, first, second, places=7, msg=None):
"""Fail if the two objects are unequal as determined by their
@ -341,8 +340,8 @@ class TestCase:
as significant digits (measured from the most signficant digit).
"""
if round(second-first, places) != 0:
raise self.failureException, \
(msg or '%r != %r within %r places' % (first, second, places))
raise self.failureException(msg or '%r != %r within %r places'
% (first, second, places))
def failIfAlmostEqual(self, first, second, places=7, msg=None):
"""Fail if the two objects are equal as determined by their
@ -353,8 +352,8 @@ class TestCase:
as significant digits (measured from the most signficant digit).
"""
if round(second-first, places) == 0:
raise self.failureException, \
(msg or '%r == %r within %r places' % (first, second, places))
raise self.failureException(msg or '%r == %r within %r places'
% (first, second, places))
# Synonyms for assertion methods
@ -487,10 +486,12 @@ class FunctionTestCase(TestCase):
self.__testFunc, self.__description))
def __str__(self):
return "%s (%s)" % (_strclass(self.__class__), self.__testFunc.__name__)
return "%s (%s)" % (_strclass(self.__class__),
self.__testFunc.__name__)
def __repr__(self):
return "<%s testFunc=%s>" % (_strclass(self.__class__), self.__testFunc)
return "<%s testFunc=%s>" % (_strclass(self.__class__),
self.__testFunc)
def shortDescription(self):
if self.__description is not None: return self.__description
@ -514,7 +515,8 @@ class TestLoader:
def loadTestsFromTestCase(self, testCaseClass):
"""Return a suite of all tests cases contained in testCaseClass"""
if issubclass(testCaseClass, TestSuite):
raise TypeError("Test cases should not be derived from TestSuite. Maybe you meant to derive from TestCase?")
raise TypeError("Test cases should not be derived from TestSuite."
"Maybe you meant to derive from TestCase?")
testCaseNames = self.getTestCaseNames(testCaseClass)
if not testCaseNames and hasattr(testCaseClass, 'runTest'):
testCaseNames = ['runTest']
@ -585,8 +587,10 @@ class TestLoader:
def getTestCaseNames(self, testCaseClass):
"""Return a sorted sequence of method names found within testCaseClass
"""
def isTestMethod(attrname, testCaseClass=testCaseClass, prefix=self.testMethodPrefix):
return attrname.startswith(prefix) and hasattr(getattr(testCaseClass, attrname), '__call__')
def isTestMethod(attrname, testCaseClass=testCaseClass,
prefix=self.testMethodPrefix):
return attrname.startswith(prefix) \
and hasattr(getattr(testCaseClass, attrname), '__call__')
testFnNames = list(filter(isTestMethod, dir(testCaseClass)))
if self.sortTestMethodsUsing:
testFnNames.sort(self.sortTestMethodsUsing)

View File

@ -196,12 +196,12 @@ class URLopener:
def open_unknown(self, fullurl, data=None):
"""Overridable interface to open unknown URL type."""
type, url = splittype(fullurl)
raise IOError, ('url error', 'unknown url type', type)
raise IOError('url error', 'unknown url type', type)
def open_unknown_proxy(self, proxy, fullurl, data=None):
"""Overridable interface to open unknown URL type."""
type, url = splittype(fullurl)
raise IOError, ('url error', 'invalid proxy for %s' % type, proxy)
raise IOError('url error', 'invalid proxy for %s' % type, proxy)
# External interface
def retrieve(self, url, filename=None, reporthook=None, data=None):
@ -308,7 +308,7 @@ class URLopener:
host = realhost
#print "proxy via http:", host, selector
if not host: raise IOError, ('http error', 'no host given')
if not host: raise IOError('http error', 'no host given')
if proxy_passwd:
import base64
@ -380,7 +380,7 @@ class URLopener:
"""Default error handler: close the connection and raise IOError."""
void = fp.read()
fp.close()
raise IOError, ('http error', errcode, errmsg, headers)
raise IOError('http error', errcode, errmsg, headers)
if hasattr(socket, "ssl"):
def _https_connection(self, host):
@ -395,7 +395,7 @@ class URLopener:
def open_file(self, url):
"""Use local file or FTP depending on form of URL."""
if not isinstance(url, str):
raise IOError, ('file error', 'proxy support for file protocol currently not implemented')
raise IOError('file error', 'proxy support for file protocol currently not implemented')
if url[:2] == '//' and url[2:3] != '/' and url[2:12].lower() != 'localhost/':
return self.open_ftp(url)
else:
@ -441,16 +441,16 @@ class URLopener:
urlfile = 'file://' + file
return addinfourl(open(localname, 'rb'),
headers, urlfile)
raise IOError, ('local file error', 'not on local host')
raise IOError('local file error', 'not on local host')
def open_ftp(self, url):
"""Use FTP protocol."""
if not isinstance(url, str):
raise IOError, ('ftp error', 'proxy support for ftp protocol currently not implemented')
raise IOError('ftp error', 'proxy support for ftp protocol currently not implemented')
import mimetypes, mimetools
from io import StringIO
host, path = splithost(url)
if not host: raise IOError, ('ftp error', 'no host given')
if not host: raise IOError('ftp error', 'no host given')
host, port = splitport(host)
user, host = splituser(host)
if user: user, passwd = splitpasswd(user)
@ -505,7 +505,7 @@ class URLopener:
def open_data(self, url, data=None):
"""Use "data" URL."""
if not isinstance(url, str):
raise IOError, ('data error', 'proxy support for data protocol currently not implemented')
raise IOError('data error', 'proxy support for data protocol currently not implemented')
# ignore POSTed data
#
# syntax of data URLs:
@ -518,7 +518,7 @@ class URLopener:
try:
[type, data] = url.split(',', 1)
except ValueError:
raise IOError, ('data error', 'bad data URL')
raise IOError('data error', 'bad data URL')
if not type:
type = 'text/plain;charset=US-ASCII'
semi = type.rfind(';')
@ -1032,7 +1032,7 @@ def splitnport(host, defport=-1):
if match:
host, port = match.group(1, 2)
try:
if not port: raise ValueError, "no digits"
if not port: raise ValueError("no digits")
nport = int(port)
except ValueError:
nport = None

View File

@ -210,7 +210,7 @@ class Request:
if hasattr(Request, 'get_' + name):
getattr(self, 'get_' + name)()
return getattr(self, attr)
raise AttributeError, attr
raise AttributeError(attr)
def get_method(self):
if self.has_data():
@ -236,7 +236,7 @@ class Request:
if self.type is None:
self.type, self.__r_type = splittype(self.__original)
if self.type is None:
raise ValueError, "unknown url type: %s" % self.__original
raise ValueError("unknown url type: %s" % self.__original)
return self.type
def get_host(self):
@ -1250,7 +1250,7 @@ class FTPHandler(BaseHandler):
import mimetypes
host = req.get_host()
if not host:
raise IOError, ('ftp error', 'no host given')
raise IOError('ftp error', 'no host given')
host, port = splitport(host)
if port is None:
port = ftplib.FTP_PORT

View File

@ -127,9 +127,9 @@ class Wave_read:
self._soundpos = 0
self._file = Chunk(file, bigendian = 0)
if self._file.getname() != b'RIFF':
raise Error, 'file does not start with RIFF id'
raise Error('file does not start with RIFF id')
if self._file.read(4) != b'WAVE':
raise Error, 'not a WAVE file'
raise Error('not a WAVE file')
self._fmt_chunk_read = 0
self._data_chunk = None
while 1:
@ -144,14 +144,14 @@ class Wave_read:
self._fmt_chunk_read = 1
elif chunkname == b'data':
if not self._fmt_chunk_read:
raise Error, 'data chunk before fmt chunk'
raise Error('data chunk before fmt chunk')
self._data_chunk = chunk
self._nframes = chunk.chunksize // self._framesize
self._data_seek_needed = 0
break
chunk.skip()
if not self._fmt_chunk_read or not self._data_chunk:
raise Error, 'fmt chunk and/or data chunk missing'
raise Error('fmt chunk and/or data chunk missing')
def __init__(self, f):
self._i_opened_the_file = None
@ -214,11 +214,11 @@ class Wave_read:
return None
def getmark(self, id):
raise Error, 'no marks'
raise Error('no marks')
def setpos(self, pos):
if pos < 0 or pos > self._nframes:
raise Error, 'position not in range'
raise Error('position not in range')
self._soundpos = pos
self._data_seek_needed = 1
@ -266,7 +266,7 @@ class Wave_read:
sampwidth = struct.unpack_from('<h', chunk.read(2))[0]
self._sampwidth = (sampwidth + 7) // 8
else:
raise Error, 'unknown format: %r' % (wFormatTag,)
raise Error('unknown format: %r' % (wFormatTag,))
self._framesize = self._nchannels * self._sampwidth
self._comptype = 'NONE'
self._compname = 'not compressed'
@ -328,43 +328,43 @@ class Wave_write:
#
def setnchannels(self, nchannels):
if self._datawritten:
raise Error, 'cannot change parameters after starting to write'
raise Error('cannot change parameters after starting to write')
if nchannels < 1:
raise Error, 'bad # of channels'
raise Error('bad # of channels')
self._nchannels = nchannels
def getnchannels(self):
if not self._nchannels:
raise Error, 'number of channels not set'
raise Error('number of channels not set')
return self._nchannels
def setsampwidth(self, sampwidth):
if self._datawritten:
raise Error, 'cannot change parameters after starting to write'
raise Error('cannot change parameters after starting to write')
if sampwidth < 1 or sampwidth > 4:
raise Error, 'bad sample width'
raise Error('bad sample width')
self._sampwidth = sampwidth
def getsampwidth(self):
if not self._sampwidth:
raise Error, 'sample width not set'
raise Error('sample width not set')
return self._sampwidth
def setframerate(self, framerate):
if self._datawritten:
raise Error, 'cannot change parameters after starting to write'
raise Error('cannot change parameters after starting to write')
if framerate <= 0:
raise Error, 'bad frame rate'
raise Error('bad frame rate')
self._framerate = framerate
def getframerate(self):
if not self._framerate:
raise Error, 'frame rate not set'
raise Error('frame rate not set')
return self._framerate
def setnframes(self, nframes):
if self._datawritten:
raise Error, 'cannot change parameters after starting to write'
raise Error('cannot change parameters after starting to write')
self._nframes = nframes
def getnframes(self):
@ -372,9 +372,9 @@ class Wave_write:
def setcomptype(self, comptype, compname):
if self._datawritten:
raise Error, 'cannot change parameters after starting to write'
raise Error('cannot change parameters after starting to write')
if comptype not in ('NONE',):
raise Error, 'unsupported compression type'
raise Error('unsupported compression type')
self._comptype = comptype
self._compname = compname
@ -387,7 +387,7 @@ class Wave_write:
def setparams(self, params):
nchannels, sampwidth, framerate, nframes, comptype, compname = params
if self._datawritten:
raise Error, 'cannot change parameters after starting to write'
raise Error('cannot change parameters after starting to write')
self.setnchannels(nchannels)
self.setsampwidth(sampwidth)
self.setframerate(framerate)
@ -396,15 +396,15 @@ class Wave_write:
def getparams(self):
if not self._nchannels or not self._sampwidth or not self._framerate:
raise Error, 'not all parameters set'
raise Error('not all parameters set')
return self._nchannels, self._sampwidth, self._framerate, \
self._nframes, self._comptype, self._compname
def setmark(self, id, pos, name):
raise Error, 'setmark() not supported'
raise Error('setmark() not supported')
def getmark(self, id):
raise Error, 'no marks'
raise Error('no marks')
def getmarkers(self):
return None
@ -451,11 +451,11 @@ class Wave_write:
def _ensure_header_written(self, datasize):
if not self._datawritten:
if not self._nchannels:
raise Error, '# channels not specified'
raise Error('# channels not specified')
if not self._sampwidth:
raise Error, 'sample width not specified'
raise Error('sample width not specified')
if not self._framerate:
raise Error, 'sampling rate not specified'
raise Error('sampling rate not specified')
self._write_header(datasize)
def _write_header(self, initlength):
@ -495,6 +495,6 @@ def open(f, mode=None):
elif mode in ('w', 'wb'):
return Wave_write(f)
else:
raise Error, "mode must be 'r', 'rb', 'w', or 'wb'"
raise Error("mode must be 'r', 'rb', 'w', or 'wb'")
openfp = open # B/W compatibility

View File

@ -51,7 +51,7 @@ class WeakValueDictionary(UserDict.UserDict):
def __getitem__(self, key):
o = self.data[key]()
if o is None:
raise KeyError, key
raise KeyError(key)
else:
return o
@ -142,7 +142,7 @@ class WeakValueDictionary(UserDict.UserDict):
return args[0]
raise
if o is None:
raise KeyError, key
raise KeyError(key)
else:
return o

View File

@ -66,16 +66,16 @@ class Packer:
def pack_float(self, x):
try: self.__buf.write(struct.pack('>f', x))
except struct.error as msg:
raise ConversionError, msg
raise ConversionError(msg)
def pack_double(self, x):
try: self.__buf.write(struct.pack('>d', x))
except struct.error as msg:
raise ConversionError, msg
raise ConversionError(msg)
def pack_fstring(self, n, s):
if n < 0:
raise ValueError, 'fstring size must be nonnegative'
raise ValueError('fstring size must be nonnegative')
data = s[:n]
n = ((n+3)//4)*4
data = data + (n - len(data)) * b'\0'
@ -99,7 +99,7 @@ class Packer:
def pack_farray(self, n, list, pack_item):
if len(list) != n:
raise ValueError, 'wrong array size'
raise ValueError('wrong array size')
for item in list:
pack_item(item)
@ -187,7 +187,7 @@ class Unpacker:
def unpack_fstring(self, n):
if n < 0:
raise ValueError, 'fstring size must be nonnegative'
raise ValueError('fstring size must be nonnegative')
i = self.__pos
j = i + (n+3)//4*4
if j > len(self.__buf):
@ -210,7 +210,7 @@ class Unpacker:
x = self.unpack_uint()
if x == 0: break
if x != 1:
raise ConversionError, '0 or 1 expected, got %r' % (x,)
raise ConversionError('0 or 1 expected, got %r' % (x,))
item = unpack_item()
list.append(item)
return list

View File

@ -570,13 +570,13 @@ class Marshaller:
try:
value.__dict__
except:
raise TypeError, "cannot marshal %s objects" % type(value)
raise TypeError("cannot marshal %s objects" % type(value))
# check if this class is a sub-class of a basic type,
# because we don't know how to marshal these types
# (e.g. a string sub-class)
for type_ in type(value).__mro__:
if type_ in self.dispatch.keys():
raise TypeError, "cannot marshal %s objects" % type(value)
raise TypeError("cannot marshal %s objects" % type(value))
# XXX(twouters): using "_arbitrary_instance" as key as a quick-fix
# for the p3yk merge, this should probably be fixed more neatly.
f = self.dispatch["_arbitrary_instance"]
@ -584,14 +584,14 @@ class Marshaller:
def dump_nil (self, value, write):
if not self.allow_none:
raise TypeError, "cannot marshal None unless allow_none is enabled"
raise TypeError("cannot marshal None unless allow_none is enabled")
write("<value><nil/></value>")
dispatch[type(None)] = dump_nil
def dump_int(self, value, write):
# in case ints are > 32 bits
if value > MAXINT or value < MININT:
raise OverflowError, "int exceeds XML-RPC limits"
raise OverflowError("int exceeds XML-RPC limits")
write("<value><int>")
write(str(value))
write("</int></value>\n")
@ -606,7 +606,7 @@ class Marshaller:
def dump_long(self, value, write):
if value > MAXINT or value < MININT:
raise OverflowError, "long int exceeds XML-RPC limits"
raise OverflowError("long int exceeds XML-RPC limits")
write("<value><int>")
write(str(int(value)))
write("</int></value>\n")
@ -633,7 +633,7 @@ class Marshaller:
def dump_array(self, value, write):
i = id(value)
if i in self.memo:
raise TypeError, "cannot marshal recursive sequences"
raise TypeError("cannot marshal recursive sequences")
self.memo[i] = None
dump = self.__dump
write("<value><array><data>\n")
@ -647,14 +647,14 @@ class Marshaller:
def dump_struct(self, value, write, escape=escape):
i = id(value)
if i in self.memo:
raise TypeError, "cannot marshal recursive dictionaries"
raise TypeError("cannot marshal recursive dictionaries")
self.memo[i] = None
dump = self.__dump
write("<value><struct>\n")
for k, v in value.items():
write("<member>\n")
if not isinstance(k, basestring):
raise TypeError, "dictionary key must be string"
raise TypeError("dictionary key must be string")
write("<name>%s</name>\n" % escape(k))
dump(v, write)
write("</member>\n")
@ -724,7 +724,7 @@ class Unmarshaller:
self.append = self._stack.append
self._use_datetime = use_datetime
if use_datetime and not datetime:
raise ValueError, "the datetime module is not available"
raise ValueError("the datetime module is not available")
def close(self):
# return response tuple and target method
@ -791,7 +791,7 @@ class Unmarshaller:
elif data == "1":
self.append(True)
else:
raise TypeError, "bad boolean value"
raise TypeError("bad boolean value")
self._value = 0
dispatch["boolean"] = end_boolean
@ -897,8 +897,7 @@ class MultiCallIterator:
elif type(item) == type([]):
return item[0]
else:
raise ValueError,\
"unexpected type in multicall result"
raise ValueError("unexpected type in multicall result")
class MultiCall:
"""server -> a object used to boxcar method calls
@ -952,7 +951,7 @@ def getparser(use_datetime=0):
to an unmarshalling object. Return both objects.
"""
if use_datetime and not datetime:
raise ValueError, "the datetime module is not available"
raise ValueError("the datetime module is not available")
if FastParser and FastUnmarshaller:
if use_datetime:
mkdatetime = _datetime_type
@ -1321,7 +1320,7 @@ class ServerProxy:
import urllib
type, uri = urllib.splittype(uri)
if type not in ("http", "https"):
raise IOError, "unsupported XML-RPC protocol"
raise IOError("unsupported XML-RPC protocol")
self.__host, self.__handler = urllib.splithost(uri)
if not self.__handler:
self.__handler = "/RPC2"

View File

@ -277,7 +277,7 @@ class ZipInfo (object):
elif ln == 0:
counts = ()
else:
raise RuntimeError, "Corrupt extra field %s"%(ln,)
raise RuntimeError("Corrupt extra field %s"%(ln,))
idx = 0
@ -581,10 +581,10 @@ class ZipFile:
pass
elif compression == ZIP_DEFLATED:
if not zlib:
raise RuntimeError,\
"Compression requires the (missing) zlib module"
raise RuntimeError(
"Compression requires the (missing) zlib module")
else:
raise RuntimeError, "That compression method is not supported"
raise RuntimeError("That compression method is not supported")
self._allowZip64 = allowZip64
self._didModify = False
@ -629,7 +629,7 @@ class ZipFile:
if not self._filePassed:
self.fp.close()
self.fp = None
raise RuntimeError, 'Mode must be "r", "w" or "a"'
raise RuntimeError('Mode must be "r", "w" or "a"')
def _GetContents(self):
"""Read the directory, making sure we close the file if the format
@ -647,7 +647,7 @@ class ZipFile:
fp = self.fp
endrec = _EndRecData(fp)
if not endrec:
raise BadZipfile, "File is not a zip file"
raise BadZipfile("File is not a zip file")
if self.debug > 1:
print(endrec)
size_cd = endrec[5] # bytes in central directory
@ -672,7 +672,7 @@ class ZipFile:
centdir = fp.read(46)
total = total + 46
if centdir[0:4] != stringCentralDir:
raise BadZipfile, "Bad magic number for central directory"
raise BadZipfile("Bad magic number for central directory")
centdir = struct.unpack(structCentralDir, centdir)
if self.debug > 2:
print(centdir)
@ -752,10 +752,10 @@ class ZipFile:
def open(self, name, mode="r", pwd=None):
"""Return file-like object for 'name'."""
if mode not in ("r", "U", "rU"):
raise RuntimeError, 'open() requires mode "r", "U", or "rU"'
raise RuntimeError('open() requires mode "r", "U", or "rU"')
if not self.fp:
raise RuntimeError, \
"Attempt to read ZIP archive that was already closed"
raise RuntimeError(
"Attempt to read ZIP archive that was already closed")
# Only open a new file for instances where we were not
# given a file object in the constructor
@ -774,7 +774,7 @@ class ZipFile:
# Skip the file header:
fheader = zef_file.read(30)
if fheader[0:4] != stringFileHeader:
raise BadZipfile, "Bad magic number for file header"
raise BadZipfile("Bad magic number for file header")
fheader = struct.unpack(structFileHeader, fheader)
fname = zef_file.read(fheader[_FH_FILENAME_LENGTH])
@ -782,9 +782,9 @@ class ZipFile:
zef_file.read(fheader[_FH_EXTRA_FIELD_LENGTH])
if fname != zinfo.orig_filename.encode("utf-8"):
raise BadZipfile, \
'File name in directory %r and header %r differ.' % (
zinfo.orig_filename, fname)
raise BadZipfile(
'File name in directory %r and header %r differ.'
% (zinfo.orig_filename, fname))
# check for encrypted flag & handle password
is_encrypted = zinfo.flag_bits & 0x1
@ -793,8 +793,8 @@ class ZipFile:
if not pwd:
pwd = self.pwd
if not pwd:
raise RuntimeError, "File %s is encrypted, " \
"password required for extraction" % name
raise RuntimeError("File %s is encrypted, "
"password required for extraction" % name)
zd = _ZipDecrypter(pwd)
# The first 12 bytes in the cypher stream is an encryption header
@ -804,7 +804,7 @@ class ZipFile:
bytes = zef_file.read(12)
h = list(map(zd, bytes[0:12]))
if h[11] != ((zinfo.CRC>>24) & 255):
raise RuntimeError, "Bad password for file %s" % name
raise RuntimeError("Bad password for file %s" % name)
# build and return a ZipExtFile
if zd is None:
@ -823,22 +823,22 @@ class ZipFile:
if self.debug: # Warning for duplicate names
print("Duplicate name:", zinfo.filename)
if self.mode not in ("w", "a"):
raise RuntimeError, 'write() requires mode "w" or "a"'
raise RuntimeError('write() requires mode "w" or "a"')
if not self.fp:
raise RuntimeError, \
"Attempt to write ZIP archive that was already closed"
raise RuntimeError(
"Attempt to write ZIP archive that was already closed")
if zinfo.compress_type == ZIP_DEFLATED and not zlib:
raise RuntimeError, \
"Compression requires the (missing) zlib module"
raise RuntimeError(
"Compression requires the (missing) zlib module")
if zinfo.compress_type not in (ZIP_STORED, ZIP_DEFLATED):
raise RuntimeError, \
"That compression method is not supported"
raise RuntimeError("That compression method is not supported")
if zinfo.file_size > ZIP64_LIMIT:
if not self._allowZip64:
raise LargeZipFile("Filesize would require ZIP64 extensions")
if zinfo.header_offset > ZIP64_LIMIT:
if not self._allowZip64:
raise LargeZipFile("Zipfile size would require ZIP64 extensions")
raise LargeZipFile(
"Zipfile size would require ZIP64 extensions")
def write(self, filename, arcname=None, compress_type=None):
"""Put the bytes from filename into the archive under the name
@ -1103,8 +1103,8 @@ class PyZipFile(ZipFile):
self.write(fname, arcname)
else:
if pathname[-3:] != ".py":
raise RuntimeError, \
'Files added with writepy() must end with ".py"'
raise RuntimeError(
'Files added with writepy() must end with ".py"')
fname, arcname = self._get_codename(pathname[0:-3], basename)
if self.debug:
print("Adding file", arcname)