py3k: 2to3's "idiom" filter

This is, I guess, a few things the Python devs were just fed up with.

* "while 1" is now "while True"
* Types are compared with isinstance instead of ==
* Sort a list in one go with sorted()

My own twist is to also replace type('') with str, type(()) with tuple,
type([]) with list, type(1) with int, and type(5000.0) with float.
This commit is contained in:
Brian Crowell 2012-10-16 22:39:56 -05:00 committed by Brian Crowell
parent 48cf699fe6
commit 31c454b925
32 changed files with 64 additions and 69 deletions

View File

@ -458,7 +458,7 @@ class ArgImageFile(ImageFile.ImageFile):
self.fp = self.arg.fp self.fp = self.arg.fp
while 1: while True:
# #
# process chunks # process chunks

View File

@ -43,7 +43,7 @@ bdf_spacing = {
def bdf_char(f): def bdf_char(f):
# skip to STARTCHAR # skip to STARTCHAR
while 1: while True:
s = f.readline() s = f.readline()
if not s: if not s:
return None return None
@ -53,7 +53,7 @@ def bdf_char(f):
# load symbol properties # load symbol properties
props = {} props = {}
while 1: while True:
s = f.readline() s = f.readline()
if not s or s[:6] == "BITMAP": if not s or s[:6] == "BITMAP":
break break
@ -62,7 +62,7 @@ def bdf_char(f):
# load bitmap # load bitmap
bitmap = [] bitmap = []
while 1: while True:
s = f.readline() s = f.readline()
if not s or s[:7] == "ENDCHAR": if not s or s[:7] == "ENDCHAR":
break break
@ -98,7 +98,7 @@ class BdfFontFile(FontFile.FontFile):
props = {} props = {}
comments = [] comments = []
while 1: while True:
s = fp.readline() s = fp.readline()
if not s or s[:13] == "ENDPROPERTIES": if not s or s[:13] == "ENDPROPERTIES":
break break
@ -123,7 +123,7 @@ class BdfFontFile(FontFile.FontFile):
# print "#", i # print "#", i
font = [] font = []
while 1: while True:
c = bdf_char(fp) c = bdf_char(fp)
if not c: if not c:
break break

View File

@ -92,7 +92,7 @@ class ContainerIO:
def readline(self): def readline(self):
s = "" s = ""
while 1: while True:
c = self.read(1) c = self.read(1)
if not c: if not c:
break break
@ -108,7 +108,7 @@ class ContainerIO:
def readlines(self): def readlines(self):
l = [] l = []
while 1: while True:
s = self.readline() s = self.readline()
if not s: if not s:
break break

View File

@ -261,7 +261,7 @@ class EpsImageFile(ImageFile.ImageFile):
id = id[1:-1] id = id[1:-1]
# Scan forward to the actual image data # Scan forward to the actual image data
while 1: while True:
s = fp.readline() s = fp.readline()
if not s: if not s:
break break

View File

@ -78,7 +78,7 @@ def open(fp, mode = "r"):
if mode != "r": if mode != "r":
raise ValueError("bad mode") raise ValueError("bad mode")
if type(fp) == type(""): if isinstance(fp, str):
filename = fp filename = fp
fp = builtins.open(fp, "rb") fp = builtins.open(fp, "rb")
else: else:

View File

@ -125,7 +125,7 @@ class GifImageFile(ImageFile.ImageFile):
self.palette = self.global_palette self.palette = self.global_palette
while 1: while True:
s = self.fp.read(1) s = self.fp.read(1)
if not s or s == ";": if not s or s == ";":

View File

@ -125,7 +125,7 @@ class ImImageFile(ImageFile.ImageFile):
self.rawmode = "L" self.rawmode = "L"
while 1: while True:
s = self.fp.read(1) s = self.fp.read(1)

View File

@ -218,8 +218,7 @@ def _conv_type_shape(im):
return shape+(extra,), typ return shape+(extra,), typ
MODES = list(_MODEINFO.keys()) MODES = sorted(_MODEINFO.keys())
MODES.sort()
# raw modes that may be memory mapped. NOTE: if you change this, you # raw modes that may be memory mapped. NOTE: if you change this, you
# may have to modify the stride calculation in map.c too! # may have to modify the stride calculation in map.c too!
@ -532,7 +531,7 @@ class Image:
bufsize = max(65536, self.size[0] * 4) # see RawEncode.c bufsize = max(65536, self.size[0] * 4) # see RawEncode.c
data = [] data = []
while 1: while True:
l, s, d = e.encode(bufsize) l, s, d = e.encode(bufsize)
data.append(d) data.append(d)
if s: if s:

View File

@ -124,7 +124,7 @@ FLAGS = {
_MAX_FLAG = 0 _MAX_FLAG = 0
for flag in FLAGS.values(): for flag in FLAGS.values():
if isinstance(flag, type(0)): if isinstance(flag, int):
_MAX_FLAG = _MAX_FLAG | flag _MAX_FLAG = _MAX_FLAG | flag
# --------------------------------------------------------------------. # --------------------------------------------------------------------.
@ -290,10 +290,10 @@ def profileToProfile(im, inputProfile, outputProfile, renderingIntent=INTENT_PER
if outputMode is None: if outputMode is None:
outputMode = im.mode outputMode = im.mode
if type(renderingIntent) != type(1) or not (0 <= renderingIntent <=3): if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <=3):
raise PyCMSError("renderingIntent must be an integer between 0 and 3") raise PyCMSError("renderingIntent must be an integer between 0 and 3")
if type(flags) != type(1) or not (0 <= flags <= _MAX_FLAG): if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
raise PyCMSError("flags must be an integer between 0 and %s" + _MAX_FLAG) raise PyCMSError("flags must be an integer between 0 and %s" + _MAX_FLAG)
try: try:
@ -398,10 +398,10 @@ def buildTransform(inputProfile, outputProfile, inMode, outMode, renderingIntent
""" """
if type(renderingIntent) != type(1) or not (0 <= renderingIntent <=3): if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <=3):
raise PyCMSError("renderingIntent must be an integer between 0 and 3") raise PyCMSError("renderingIntent must be an integer between 0 and 3")
if type(flags) != type(1) or not (0 <= flags <= _MAX_FLAG): if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
raise PyCMSError("flags must be an integer between 0 and %s" + _MAX_FLAG) raise PyCMSError("flags must be an integer between 0 and %s" + _MAX_FLAG)
try: try:
@ -489,10 +489,10 @@ def buildProofTransform(inputProfile, outputProfile, proofProfile, inMode, outMo
""" """
if type(renderingIntent) != type(1) or not (0 <= renderingIntent <=3): if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <=3):
raise PyCMSError("renderingIntent must be an integer between 0 and 3") raise PyCMSError("renderingIntent must be an integer between 0 and 3")
if type(flags) != type(1) or not (0 <= flags <= _MAX_FLAG): if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
raise PyCMSError("flags must be an integer between 0 and %s" + _MAX_FLAG) raise PyCMSError("flags must be an integer between 0 and %s" + _MAX_FLAG)
try: try:
@ -597,9 +597,9 @@ def createProfile(colorSpace, colorTemp=-1):
raise PyCMSError("Color space not supported for on-the-fly profile creation (%s)" % colorSpace) raise PyCMSError("Color space not supported for on-the-fly profile creation (%s)" % colorSpace)
if colorSpace == "LAB": if colorSpace == "LAB":
if type(colorTemp) == type(5000.0): if isinstance(colorTemp, float):
colorTemp = int(colorTemp + 0.5) colorTemp = int(colorTemp + 0.5)
if type (colorTemp) != type (5000): if not isinstance(colorTemp, int):
raise PyCMSError("Color temperature must be a positive integer, \"%s\" not valid" % colorTemp) raise PyCMSError("Color temperature must be a positive integer, \"%s\" not valid" % colorTemp)
try: try:

View File

@ -41,7 +41,7 @@ def getrgb(color):
rgb = None rgb = None
# found color in cache # found color in cache
if rgb: if rgb:
if isinstance(rgb, type(())): if isinstance(rgb, tuple):
return rgb return rgb
colormap[color] = rgb = getrgb(rgb) colormap[color] = rgb = getrgb(rgb)
return rgb return rgb

View File

@ -195,7 +195,7 @@ class ImageFile(Image.Image):
continue continue
b = prefix b = prefix
t = len(b) t = len(b)
while 1: while True:
s = read(self.decodermaxblock) s = read(self.decodermaxblock)
if not s: if not s:
self.tile = [] self.tile = []
@ -315,7 +315,7 @@ class _ParserFile:
def readline(self): def readline(self):
# FIXME: this is slow! # FIXME: this is slow!
s = "" s = ""
while 1: while True:
c = self.read(1) c = self.read(1)
if not c: if not c:
break break
@ -483,7 +483,7 @@ def _save(im, fp, tile):
if o > 0: if o > 0:
fp.seek(o, 0) fp.seek(o, 0)
e.setimage(im.im, b) e.setimage(im.im, b)
while 1: while True:
l, s, d = e.encode(bufsize) l, s, d = e.encode(bufsize)
fp.write(d) fp.write(d)
if s: if s:

View File

@ -28,7 +28,7 @@ except ImportError:
VERBOSE = 0 VERBOSE = 0
def _isconstant(v): def _isconstant(v):
return isinstance(v, type(0)) or isinstance(v, type(0.0)) return isinstance(v, int) or isinstance(v, float)
class _Operand: class _Operand:
# wraps an image operand, providing standard operators # wraps an image operand, providing standard operators

View File

@ -33,7 +33,7 @@ from functools import reduce
# helpers # helpers
def _border(border): def _border(border):
if type(border) is type(()): if isinstance(border, tuple):
if len(border) == 2: if len(border) == 2:
left, top = right, bottom = border left, top = right, bottom = border
elif len(border) == 4: elif len(border) == 4:
@ -275,7 +275,7 @@ def fit(image, size, method=Image.NEAREST, bleed=0.0, centering=(0.5, 0.5)):
# http://www.cazabon.com # http://www.cazabon.com
# ensure inputs are valid # ensure inputs are valid
if type(centering) != type([]): if not isinstance(centering, list):
centering = [centering[0], centering[1]] centering = [centering[0], centering[1]]
if centering[0] > 1.0 or centering[0] < 0.0: if centering[0] > 1.0 or centering[0] < 0.0:

View File

@ -76,7 +76,7 @@ class ImagePalette:
# (experimental) save palette to text file # (experimental) save palette to text file
if self.rawmode: if self.rawmode:
raise ValueError("palette contains raw palette data") raise ValueError("palette contains raw palette data")
if type(fp) == type(""): if isinstance(fp, str):
fp = open(fp, "w") fp = open(fp, "w")
fp.write("# Palette\n") fp.write("# Palette\n")
fp.write("# Mode: %s\n" % self.mode) fp.write("# Mode: %s\n" % self.mode)

View File

@ -53,7 +53,7 @@ class Stat:
self.h = image_or_list.histogram() self.h = image_or_list.histogram()
except AttributeError: except AttributeError:
self.h = image_or_list # assume it to be a histogram list self.h = image_or_list # assume it to be a histogram list
if type(self.h) != type([]): if not isinstance(self.h, list):
raise TypeError("first argument must be image or list") raise TypeError("first argument must be image or list")
self.bands = list(range(len(self.h) // 256)) self.bands = list(range(len(self.h) // 256))

View File

@ -45,7 +45,7 @@ class ImtImageFile(ImageFile.ImageFile):
xsize = ysize = 0 xsize = ysize = 0
while 1: while True:
s = self.fp.read(1) s = self.fp.read(1)
if not s: if not s:

View File

@ -98,7 +98,7 @@ class IptcImageFile(ImageFile.ImageFile):
if sz != size[0]: if sz != size[0]:
return 0 return 0
y = 1 y = 1
while 1: while True:
self.fp.seek(sz, 1) self.fp.seek(sz, 1)
t, s = self.field() t, s = self.field()
if t != (8, 10): if t != (8, 10):
@ -111,7 +111,7 @@ class IptcImageFile(ImageFile.ImageFile):
def _open(self): def _open(self):
# load descriptive fields # load descriptive fields
while 1: while True:
offset = self.fp.tell() offset = self.fp.tell()
tag, size = self.field() tag, size = self.field()
if not tag or tag == (8,10): if not tag or tag == (8,10):
@ -180,7 +180,7 @@ class IptcImageFile(ImageFile.ImageFile):
# To simplify access to the extracted file, # To simplify access to the extracted file,
# prepend a PPM header # prepend a PPM header
o.write("P5\n%d %d\n255\n" % self.size) o.write("P5\n%d %d\n255\n" % self.size)
while 1: while True:
type, size = self.field() type, size = self.field()
if type != (8, 10): if type != (8, 10):
break break

View File

@ -287,7 +287,7 @@ class JpegImageFile(ImageFile.ImageFile):
self.applist = [] self.applist = []
self.icclist = [] self.icclist = []
while 1: while True:
s = s + self.fp.read(1) s = s + self.fp.read(1)

View File

@ -175,7 +175,7 @@ class _OleDirectoryEntry:
if right != -1: # 0xFFFFFFFFL: if right != -1: # 0xFFFFFFFFL:
# and then back to the left # and then back to the left
sid = right sid = right
while 1: while True:
left, right, child = sidlist[sid][4] left, right, child = sidlist[sid][4]
if left == -1: # 0xFFFFFFFFL: if left == -1: # 0xFFFFFFFFL:
break break
@ -183,7 +183,7 @@ class _OleDirectoryEntry:
sid = left sid = left
else: else:
# couldn't move right; move up instead # couldn't move right; move up instead
while 1: while True:
ptr = stack[-1] ptr = stack[-1]
del stack[-1] del stack[-1]
left, right, child = sidlist[ptr][4] left, right, child = sidlist[ptr][4]
@ -267,7 +267,7 @@ class OleFileIO:
def open(self, filename): def open(self, filename):
"""Open an OLE2 file""" """Open an OLE2 file"""
if type(filename) == type(""): if isinstance(filename, str):
self.fp = open(filename, "rb") self.fp = open(filename, "rb")
else: else:
self.fp = filename self.fp = filename
@ -345,7 +345,7 @@ class OleFileIO:
# create list of sid entries # create list of sid entries
self.sidlist = [] self.sidlist = []
while 1: while True:
entry = fp.read(128) entry = fp.read(128)
if not entry: if not entry:
break break
@ -525,8 +525,7 @@ if __name__ == "__main__":
if file[-1][0] == "\005": if file[-1][0] == "\005":
print(file) print(file)
props = ole.getproperties(file) props = ole.getproperties(file)
props = list(props.items()) props = sorted(props.items())
props.sort()
for k, v in props: for k, v in props:
print(" ", k, v) print(" ", k, v)
except IOError as v: except IOError as v:

View File

@ -24,7 +24,7 @@ class PaletteFile:
self.palette = [(i, i, i) for i in range(256)] self.palette = [(i, i, i) for i in range(256)]
while 1: while True:
s = fp.readline() s = fp.readline()

View File

@ -138,7 +138,7 @@ class ChunkStream:
cids = [] cids = []
while 1: while True:
cid, pos, len = self.read() cid, pos, len = self.read()
if cid == endchunk: if cid == endchunk:
break break
@ -323,7 +323,7 @@ class PngImageFile(ImageFile.ImageFile):
self.png = PngStream(self.fp) self.png = PngStream(self.fp)
while 1: while True:
# #
# get next chunk # get next chunk

View File

@ -49,7 +49,7 @@ class PpmImageFile(ImageFile.ImageFile):
format_description = "Pbmplus image" format_description = "Pbmplus image"
def _token(self, s = ""): def _token(self, s = ""):
while 1: # read until next whitespace while True: # read until next whitespace
c = self.fp.read(1) c = self.fp.read(1)
if not c or c in string.whitespace: if not c or c in string.whitespace:
break break
@ -71,8 +71,8 @@ class PpmImageFile(ImageFile.ImageFile):
self.mode = rawmode = mode self.mode = rawmode = mode
for ix in range(3): for ix in range(3):
while 1: while True:
while 1: while True:
s = self.fp.read(1) s = self.fp.read(1)
if s not in string.whitespace: if s not in string.whitespace:
break break

View File

@ -32,7 +32,7 @@ class TarIO(ContainerIO.ContainerIO):
fh = open(tarfile, "rb") fh = open(tarfile, "rb")
while 1: while True:
s = fh.read(512) s = fh.read(512)
if len(s) != 512: if len(s) != 512:

View File

@ -401,8 +401,7 @@ class ImageFileDirectory(collections.MutableMapping):
fp.write(o16(len(self.tags))) fp.write(o16(len(self.tags)))
# always write in ascending tag order # always write in ascending tag order
tags = list(self.tags.items()) tags = sorted(self.tags.items())
tags.sort()
directory = [] directory = []
append = directory.append append = directory.append
@ -425,7 +424,7 @@ class ImageFileDirectory(collections.MutableMapping):
elif typ == 7: elif typ == 7:
# untyped data # untyped data
data = value = "".join(value) data = value = "".join(value)
elif type(value[0]) is type(""): elif isinstance(value[0], str):
# string data # string data
typ = 2 typ = 2
data = value = "\0".join(value) + "\0" data = value = "\0".join(value) + "\0"
@ -737,10 +736,10 @@ SAVE_INFO = {
def _cvt_res(value): def _cvt_res(value):
# convert value to TIFF rational number -- (numerator, denominator) # convert value to TIFF rational number -- (numerator, denominator)
if type(value) in (type([]), type(())): if isinstance(value, collections.Sequence):
assert(len(value) % 2 == 0) assert(len(value) % 2 == 0)
return value return value
if type(value) == type(1): if isinstance(value, int):
return (value, 1) return (value, 1)
value = float(value) value = float(value)
return (int(value * 65536), 65536) return (int(value * 65536), 65536)

View File

@ -47,7 +47,7 @@ class XVThumbImageFile(ImageFile.ImageFile):
self.fp.readline() self.fp.readline()
# skip info comments # skip info comments
while 1: while True:
s = self.fp.readline() s = self.fp.readline()
if not s: if not s:
raise SyntaxError("Unexpected EOF reading XV thumbnail file") raise SyntaxError("Unexpected EOF reading XV thumbnail file")

View File

@ -42,7 +42,7 @@ class XpmImageFile(ImageFile.ImageFile):
raise SyntaxError("not an XPM file") raise SyntaxError("not an XPM file")
# skip forward to next string # skip forward to next string
while 1: while True:
s = self.fp.readline() s = self.fp.readline()
if not s: if not s:
raise SyntaxError("broken XPM file") raise SyntaxError("broken XPM file")

View File

@ -55,7 +55,7 @@ class Option:
def f(x): def f(x):
if x=='-': return '_' if x=='-': return '_'
else: return x else: return x
if type(self.name)!=type(''): self.py_name=str(self.name) if not isinstance(self.name, str): self.py_name=str(self.name)
else: self.py_name=''.join(map(f, self.name)) else: self.py_name=''.join(map(f, self.name))
def is_active(self): def is_active(self):
@ -174,7 +174,7 @@ class SaneDev:
raise AttributeError('Inactive option: '+key) raise AttributeError('Inactive option: '+key)
if not _sane.OPTION_IS_SETTABLE(opt.cap): if not _sane.OPTION_IS_SETTABLE(opt.cap):
raise AttributeError("Option can't be set by software: "+key) raise AttributeError("Option can't be set by software: "+key)
if type(value) == int and opt.type == TYPE_FIXED: if isinstance(value, int) and opt.type == TYPE_FIXED:
# avoid annoying errors of backend if int is given instead float: # avoid annoying errors of backend if int is given instead float:
value = float(value) value = float(value)
self.last_opt = dev.set_option(opt.index, value) self.last_opt = dev.set_option(opt.index, value)

View File

@ -89,7 +89,7 @@ if html:
html = open(file+".html", "w") html = open(file+".html", "w")
html.write("<html>\n<body>\n") html.write("<html>\n<body>\n")
while 1: while True:
if frames[ix]: if frames[ix]:
im.save(outfile % ix) im.save(outfile % ix)

View File

@ -56,8 +56,7 @@ for o, a in opt:
if o == "-f": if o == "-f":
Image.init() Image.init()
id = Image.ID[:] id = sorted(Image.ID)
id.sort()
print("Supported formats (* indicates output format):") print("Supported formats (* indicates output format):")
for i in id: for i in id:
if i in Image.SAVE: if i in Image.SAVE:

View File

@ -485,7 +485,7 @@ class PILDriver:
if self.verbose: if self.verbose:
print("Stack: " + repr(self.stack)) print("Stack: " + repr(self.stack))
top = self.top() top = self.top()
if type(top) != type(""): if not isinstance(top, str):
continue; continue;
funcname = "do_" + top funcname = "do_" + top
if not hasattr(self, funcname): if not hasattr(self, funcname):
@ -510,7 +510,7 @@ if __name__ == '__main__':
driver.execute(sys.argv[1:]) driver.execute(sys.argv[1:])
else: else:
print("PILDriver says hello.") print("PILDriver says hello.")
while 1: while True:
try: try:
line = raw_input('pildriver> '); line = raw_input('pildriver> ');
except EOFError: except EOFError:

View File

@ -45,8 +45,7 @@ verbose = quiet = verify = 0
for o, a in opt: for o, a in opt:
if o == "-f": if o == "-f":
Image.init() Image.init()
id = Image.ID[:] id = sorted(Image.ID)
id.sort()
print("Supported formats:") print("Supported formats:")
for i in id: for i in id:
print(i, end=' ') print(i, end=' ')

View File

@ -42,7 +42,7 @@ class AppletDisplay:
class UI(Label): class UI(Label):
def __init__(self, master, im): def __init__(self, master, im):
if type(im) == type([]): if isinstance(im, list):
# list of images # list of images
self.im = im[1:] self.im = im[1:]
im = self.im[0] im = self.im[0]
@ -71,7 +71,7 @@ class UI(Label):
def next(self): def next(self):
if type(self.im) == type([]): if isinstance(self.im, list):
try: try:
im = self.im[0] im = self.im[0]