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
while 1:
while True:
#
# process chunks

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -218,8 +218,7 @@ def _conv_type_shape(im):
return shape+(extra,), typ
MODES = list(_MODEINFO.keys())
MODES.sort()
MODES = sorted(_MODEINFO.keys())
# raw modes that may be memory mapped. NOTE: if you change this, you
# 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
data = []
while 1:
while True:
l, s, d = e.encode(bufsize)
data.append(d)
if s:

View File

@ -124,7 +124,7 @@ FLAGS = {
_MAX_FLAG = 0
for flag in FLAGS.values():
if isinstance(flag, type(0)):
if isinstance(flag, int):
_MAX_FLAG = _MAX_FLAG | flag
# --------------------------------------------------------------------.
@ -290,10 +290,10 @@ def profileToProfile(im, inputProfile, outputProfile, renderingIntent=INTENT_PER
if outputMode is None:
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")
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)
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")
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)
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")
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)
try:
@ -597,9 +597,9 @@ def createProfile(colorSpace, colorTemp=-1):
raise PyCMSError("Color space not supported for on-the-fly profile creation (%s)" % colorSpace)
if colorSpace == "LAB":
if type(colorTemp) == type(5000.0):
if isinstance(colorTemp, float):
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)
try:

View File

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

View File

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

View File

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

View File

@ -33,7 +33,7 @@ from functools import reduce
# helpers
def _border(border):
if type(border) is type(()):
if isinstance(border, tuple):
if len(border) == 2:
left, top = right, bottom = border
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
# ensure inputs are valid
if type(centering) != type([]):
if not isinstance(centering, list):
centering = [centering[0], centering[1]]
if centering[0] > 1.0 or centering[0] < 0.0:

View File

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

View File

@ -53,7 +53,7 @@ class Stat:
self.h = image_or_list.histogram()
except AttributeError:
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")
self.bands = list(range(len(self.h) // 256))

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -55,7 +55,7 @@ class Option:
def f(x):
if x=='-': return '_'
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))
def is_active(self):
@ -174,7 +174,7 @@ class SaneDev:
raise AttributeError('Inactive option: '+key)
if not _sane.OPTION_IS_SETTABLE(opt.cap):
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:
value = float(value)
self.last_opt = dev.set_option(opt.index, value)

View File

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

View File

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

View File

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

View File

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

View File

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