py3k: Fix up uses of dictionary views, ranges, and has_key()

y.has_key(x) is gone (use x in y), and keys(), values(), items(), and
range() all return views.

Some iterables needed to be packed into lists, either because the code
expected a list (such as "range(256) * 3") or because the original
collection was being modified (automatic global declarations).

The Tiff ImageFileDictionary is a special case and will be dealt with in
another commit.
This commit is contained in:
Brian Crowell 2012-10-15 16:18:27 -05:00 committed by Brian Crowell
parent b386ed14dd
commit 09f1081c95
19 changed files with 64 additions and 64 deletions

View File

@ -131,7 +131,7 @@ class BmpImageFile(ImageFile.ImageFile):
if colors == 2:
indices = (0, 255)
else:
indices = range(colors)
indices = list(range(colors))
for i in indices:
rgb = read(lutsize)[:3]
if rgb != chr(i)*3:

View File

@ -108,7 +108,7 @@ class FpxImageFile(ImageFile.ImageFile):
self.jpeg = {}
for i in range(256):
id = 0x3000001|(i << 16)
if prop.has_key(id):
if id in prop:
self.jpeg[i] = prop[id]
# print len(self.jpeg), "tables loaded"

View File

@ -125,7 +125,7 @@ class IcnsFile:
sizes = []
for size, fmts in self.SIZES.items():
for (fmt, reader) in fmts:
if self.dct.has_key(fmt):
if fmt in self.dct:
sizes.append(size)
break
return sizes

View File

@ -162,20 +162,20 @@ class ImImageFile(ImageFile.ImageFile):
v = tuple(map(number, v.split(",")))
if len(v) == 1:
v = v[0]
elif k == MODE and OPEN.has_key(v):
elif k == MODE and v in OPEN:
v, self.rawmode = OPEN[v]
# Add to dictionary. Note that COMMENT tags are
# combined into a list of strings.
if k == COMMENT:
if self.info.has_key(k):
if k in self.info:
self.info[k].append(v)
else:
self.info[k] = [v]
else:
self.info[k] = v
if TAGS.has_key(k):
if k in TAGS:
n = n + 1
else:
@ -195,7 +195,7 @@ class ImImageFile(ImageFile.ImageFile):
if not s:
raise SyntaxError("File truncated")
if self.info.has_key(LUT):
if LUT in self.info:
# convert lookup table to palette or lut attribute
palette = self.fp.read(768)
greyscale = 1 # greyscale palette

View File

@ -224,7 +224,7 @@ def _conv_type_shape(im):
return shape+(extra,), typ
MODES = _MODEINFO.keys()
MODES = list(_MODEINFO.keys())
MODES.sort()
# raw modes that may be memory mapped. NOTE: if you change this, you
@ -343,7 +343,7 @@ def init():
# only check directories (including current, if present in the path)
for directory in filter(isDirectory, directories):
fullpath = os.path.abspath(directory)
if visited.has_key(fullpath):
if fullpath in visited:
continue
for file in os.listdir(directory):
if file[-14:] == "ImagePlugin.py":
@ -610,7 +610,7 @@ class Image:
self.palette.dirty = 0
self.palette.mode = "RGB"
self.palette.rawmode = None
if self.info.has_key("transparency"):
if "transparency" in self.info:
self.im.putpalettealpha(self.info["transparency"], 0)
self.palette.mode = "RGBA"
if self.im:

View File

@ -175,7 +175,7 @@ def imagemath_convert(self, mode):
return _Operand(self.im.convert(mode))
ops = {}
for k, v in globals().items():
for k, v in list(globals().items()):
if k[:10] == "imagemath_":
ops[k[10:]] = v
@ -195,7 +195,7 @@ def eval(expression, _dict={}, **kw):
args = ops.copy()
args.update(_dict)
args.update(kw)
for k, v in args.items():
for k, v in list(args.items()):
if hasattr(v, "im"):
args[k] = _Operand(v)

View File

@ -28,7 +28,7 @@ class ImagePalette:
def __init__(self, mode = "RGB", palette = None):
self.mode = mode
self.rawmode = None # if set, palette contains raw data
self.palette = palette or range(256)*len(self.mode)
self.palette = palette or list(range(256))*len(self.mode)
self.colors = {}
self.dirty = None
if len(self.mode)*256 != len(self.palette):
@ -119,7 +119,7 @@ def new(mode, data):
return Image.core.new_palette(mode, data)
def negative(mode="RGB"):
palette = range(256)
palette = list(range(256))
palette.reverse()
return ImagePalette(mode, palette * len(mode))
@ -138,7 +138,7 @@ def sepia(white="#fff0c0"):
return ImagePalette("RGB", r + g + b)
def wedge(mode="RGB"):
return ImagePalette(mode, range(256) * len(mode))
return ImagePalette(mode, list(range(256)) * len(mode))
def load(filename):

View File

@ -54,7 +54,7 @@ class Stat:
self.h = image_or_list # assume it to be a histogram list
if type(self.h) != type([]):
raise TypeError("first argument must be image or list")
self.bands = range(len(self.h) / 256)
self.bands = list(range(len(self.h) // 256))
def __getattr__(self, id):
"Calculate missing attribute"

View File

@ -81,10 +81,10 @@ class PhotoImage:
# Tk compatibility: file or data
if image is None:
if kw.has_key("file"):
if "file" in kw:
image = Image.open(kw["file"])
del kw["file"]
elif kw.has_key("data"):
elif "data" in kw:
from StringIO import StringIO
image = Image.open(StringIO(kw["data"]))
del kw["data"]
@ -213,10 +213,10 @@ class BitmapImage:
# Tk compatibility: file or data
if image is None:
if kw.has_key("file"):
if "file" in kw:
image = Image.open(kw["file"])
del kw["file"]
elif kw.has_key("data"):
elif "data" in kw:
from StringIO import StringIO
image = Image.open(StringIO(kw["data"]))
del kw["data"]

View File

@ -119,7 +119,7 @@ class IptcImageFile(ImageFile.ImageFile):
tagdata = self.fp.read(size)
else:
tagdata = None
if tag in self.info.keys():
if tag in list(self.info.keys()):
if isinstance(self.info[tag], list):
self.info[tag].append(tagdata)
else:
@ -132,7 +132,7 @@ class IptcImageFile(ImageFile.ImageFile):
# mode
layers = ord(self.info[(3,60)][0])
component = ord(self.info[(3,60)][1])
if self.info.has_key((3,65)):
if (3,65) in self.info:
id = ord(self.info[(3,65)][0])-1
else:
id = 0

View File

@ -293,7 +293,7 @@ class JpegImageFile(ImageFile.ImageFile):
i = i16(s)
if MARKER.has_key(i):
if i in MARKER:
name, description, handler = MARKER[i]
# print hex(i), name, description
if handler is not None:
@ -458,9 +458,9 @@ def _save(im, fp, filename):
# "progressive" is the official name, but older documentation
# says "progression"
# FIXME: issue a warning if the wrong form is used (post-1.1.7)
info.has_key("progressive") or info.has_key("progression"),
"progressive" in info or "progression" in info,
info.get("smooth", 0),
info.has_key("optimize"),
"optimize" in info,
info.get("streamtype", 0),
dpi[0], dpi[1],
subsampling,

View File

@ -65,7 +65,7 @@ VT_VECTOR=0x1000;
# map property id to name (for debugging purposes)
VT = {}
for k, v in vars().items():
for k, v in list(vars().items()):
if k[:3] == "VT_":
VT[v] = k
@ -520,7 +520,7 @@ if __name__ == "__main__":
if file[-1][0] == "\005":
print file
props = ole.getproperties(file)
props = props.items()
props = list(props.items())
props.sort()
for k, v in props:
print " ", k, v

View File

@ -51,7 +51,7 @@ class PSDraw:
self.fp.flush()
def setfont(self, font, size):
if not self.isofont.has_key(font):
if font not in self.isofont:
# reencode font
self.fp.write("/PSDraw-%s ISOLatin1Encoding /%s E\n" %\
(font, font))

View File

@ -80,7 +80,7 @@ _Palm8BitColormapValues = (
# so build a prototype image to be used for palette resampling
def build_prototype_image():
image = Image.new("L", (1,len(_Palm8BitColormapValues),))
image.putdata(range(len(_Palm8BitColormapValues)))
image.putdata(list(range(len(_Palm8BitColormapValues))))
palettedata = ()
for i in range(len(_Palm8BitColormapValues)):
palettedata = palettedata + _Palm8BitColormapValues[i]
@ -127,7 +127,7 @@ def _save(im, fp, filename, check=0):
bpp = 8
version = 1
elif im.mode == "L" and im.encoderinfo.has_key("bpp") and im.encoderinfo["bpp"] in (1, 2, 4):
elif im.mode == "L" and "bpp" in im.encoderinfo and im.encoderinfo["bpp"] in (1, 2, 4):
# this is 8-bit grayscale, so we shift it to get the high-order bits, and invert it because
# Palm does greyscale from white (0) to black (1)
@ -138,7 +138,7 @@ def _save(im, fp, filename, check=0):
rawmode = "P;" + str(bpp)
version = 1
elif im.mode == "L" and im.info.has_key("bpp") and im.info["bpp"] in (1, 2, 4):
elif im.mode == "L" and "bpp" in im.info and im.info["bpp"] in (1, 2, 4):
# here we assume that even though the inherent mode is 8-bit grayscale, only
# the lower bpp bits are significant. We invert them to match the Palm.
@ -177,7 +177,7 @@ def _save(im, fp, filename, check=0):
compression_type = _COMPRESSION_TYPES["none"]
flags = 0;
if im.mode == "P" and im.info.has_key("custom-colormap"):
if im.mode == "P" and "custom-colormap" in im.info:
flags = flags & _FLAGS["custom-colormap"]
colormapsize = 4 * 256 + 2;
colormapmode = im.palette.mode
@ -185,7 +185,7 @@ def _save(im, fp, filename, check=0):
else:
colormapsize = 0
if im.info.has_key("offset"):
if "offset" in im.info:
offset = (rowbytes * rows + 16 + 3 + colormapsize) / 4;
else:
offset = 0

View File

@ -469,7 +469,7 @@ def _save(im, fp, filename, chunk=putchunk, check=0):
#
# attempt to minimize storage requirements for palette images
if im.encoderinfo.has_key("bits"):
if "bits" in im.encoderinfo:
# number of bits specified by user
n = 1 << im.encoderinfo["bits"]
@ -492,12 +492,12 @@ def _save(im, fp, filename, chunk=putchunk, check=0):
mode = "%s;%d" % (mode, bits)
# encoder options
if im.encoderinfo.has_key("dictionary"):
if "dictionary" in im.encoderinfo:
dictionary = im.encoderinfo["dictionary"]
else:
dictionary = ""
im.encoderconfig = (im.encoderinfo.has_key("optimize"), dictionary)
im.encoderconfig = ("optimize" in im.encoderinfo, dictionary)
# get the corresponding PNG mode
try:
@ -523,7 +523,7 @@ def _save(im, fp, filename, chunk=putchunk, check=0):
if im.mode == "P":
chunk(fp, "PLTE", im.im.getpalette("RGB"))
if im.encoderinfo.has_key("transparency"):
if "transparency" in im.encoderinfo:
if im.mode == "P":
transparency = max(0, min(255, im.encoderinfo["transparency"]))
chunk(fp, "tRNS", chr(255) * transparency + chr(0))
@ -553,7 +553,7 @@ def _save(im, fp, filename, chunk=putchunk, check=0):
chunk(fp, cid, data)
# ICC profile writing support -- 2008-06-06 Florian Hoech
if im.info.has_key("icc_profile"):
if "icc_profile" in im.info:
# ICC profile
# according to PNG spec, the iCCP chunk contains:
# Profile name 1-79 bytes (character string)

View File

@ -174,7 +174,7 @@ def _layerinfo(file):
# image info
info = []
mode = []
types = range(i16(read(2)))
types = list(range(i16(read(2))))
if len(types) > 4:
continue

View File

@ -402,7 +402,7 @@ class ImageFileDirectory:
fp.write(o16(len(self.tags)))
# always write in ascending tag order
tags = self.tags.items()
tags = list(self.tags.items())
tags.sort()
directory = []
@ -417,7 +417,7 @@ class ImageFileDirectory:
typ = None
if self.tagtype.has_key(tag):
if tag in self.tagtype:
typ = self.tagtype[tag]
if typ == 1:
@ -569,18 +569,18 @@ class TiffImageFile(ImageFile.ImageFile):
args = (rawmode, 0, 1)
elif compression == "jpeg":
args = rawmode, ""
if self.tag.has_key(JPEGTABLES):
if JPEGTABLES in self.tag:
# Hack to handle abbreviated JPEG headers
self.tile_prefix = self.tag[JPEGTABLES]
elif compression == "packbits":
args = rawmode
elif compression == "tiff_lzw":
args = rawmode
if self.tag.has_key(317):
if 317 in self.tag:
# Section 14: Differencing Predictor
self.decoderconfig = (self.tag[PREDICTOR][0],)
if self.tag.has_key(ICCPROFILE):
if ICCPROFILE in self.tag:
self.info['icc_profile'] = self.tag[ICCPROFILE]
return args
@ -588,7 +588,7 @@ class TiffImageFile(ImageFile.ImageFile):
def _setup(self):
"Setup this image object based on current tags"
if self.tag.has_key(0xBC01):
if 0xBC01 in self.tag:
raise IOError("Windows Media Photo files not yet supported")
getscalar = self.tag.getscalar
@ -658,7 +658,7 @@ class TiffImageFile(ImageFile.ImageFile):
# build tile descriptors
x = y = l = 0
self.tile = []
if self.tag.has_key(STRIPOFFSETS):
if STRIPOFFSETS in self.tag:
# striped image
h = getscalar(ROWSPERSTRIP, ysize)
w = self.size[0]
@ -675,7 +675,7 @@ class TiffImageFile(ImageFile.ImageFile):
x = y = 0
l = l + 1
a = None
elif self.tag.has_key(TILEOFFSETS):
elif TILEOFFSETS in self.tag:
# tiled image
w = getscalar(322)
h = getscalar(323)
@ -769,28 +769,28 @@ def _save(im, fp, filename):
if hasattr(im, 'tag'):
# preserve tags from original TIFF image file
for key in (RESOLUTION_UNIT, X_RESOLUTION, Y_RESOLUTION):
if im.tag.tagdata.has_key(key):
if key in im.tag.tagdata:
ifd[key] = im.tag.tagdata.get(key)
# preserve some more tags from original TIFF image file
# -- 2008-06-06 Florian Hoech
ifd.tagtype = im.tag.tagtype
for key in (IPTC_NAA_CHUNK, PHOTOSHOP_CHUNK, XMP):
if im.tag.has_key(key):
if key in im.tag:
ifd[key] = im.tag[key]
# preserve ICC profile (should also work when saving other formats
# which support profiles as TIFF) -- 2008-06-06 Florian Hoech
if im.info.has_key("icc_profile"):
if "icc_profile" in im.info:
ifd[ICCPROFILE] = im.info["icc_profile"]
if im.encoderinfo.has_key("description"):
if "description" in im.encoderinfo:
ifd[IMAGEDESCRIPTION] = im.encoderinfo["description"]
if im.encoderinfo.has_key("resolution"):
if "resolution" in im.encoderinfo:
ifd[X_RESOLUTION] = ifd[Y_RESOLUTION] \
= _cvt_res(im.encoderinfo["resolution"])
if im.encoderinfo.has_key("x resolution"):
if "x resolution" in im.encoderinfo:
ifd[X_RESOLUTION] = _cvt_res(im.encoderinfo["x resolution"])
if im.encoderinfo.has_key("y resolution"):
if "y resolution" in im.encoderinfo:
ifd[Y_RESOLUTION] = _cvt_res(im.encoderinfo["y resolution"])
if im.encoderinfo.has_key("resolution unit"):
if "resolution unit" in im.encoderinfo:
unit = im.encoderinfo["resolution unit"]
if unit == "inch":
ifd[RESOLUTION_UNIT] = 2
@ -798,13 +798,13 @@ def _save(im, fp, filename):
ifd[RESOLUTION_UNIT] = 3
else:
ifd[RESOLUTION_UNIT] = 1
if im.encoderinfo.has_key("software"):
if "software" in im.encoderinfo:
ifd[SOFTWARE] = im.encoderinfo["software"]
if im.encoderinfo.has_key("date time"):
if "date time" in im.encoderinfo:
ifd[DATE_TIME] = im.encoderinfo["date time"]
if im.encoderinfo.has_key("artist"):
if "artist" in im.encoderinfo:
ifd[ARTIST] = im.encoderinfo["artist"]
if im.encoderinfo.has_key("copyright"):
if "copyright" in im.encoderinfo:
ifd[COPYRIGHT] = im.encoderinfo["copyright"]
dpi = im.encoderinfo.get("dpi")
@ -843,7 +843,7 @@ def _save(im, fp, filename):
# -- helper for multi-page save --
if im.encoderinfo.has_key("_debug_multipage"):
if "_debug_multipage" in im.encoderinfo:
#just to access o32 and o16 (using correct byte order)
im._debug_multipage = ifd

View File

@ -165,7 +165,7 @@ class SaneDev:
def __setattr__(self, key, value):
dev=self.__dict__['dev']
optdict=self.__dict__['opt']
if not optdict.has_key(key):
if key not in optdict:
self.__dict__[key]=value ; return
opt=optdict[key]
if opt.type==TYPE_GROUP:
@ -186,10 +186,10 @@ class SaneDev:
dev=self.__dict__['dev']
optdict=self.__dict__['opt']
if key=='optlist':
return self.opt.keys()
return list(self.opt.keys())
if key=='area':
return (self.tl_x, self.tl_y),(self.br_x, self.br_y)
if not optdict.has_key(key):
if key not in optdict:
raise AttributeError('No such attribute: '+key)
opt=optdict[key]
if opt.type==TYPE_BUTTON:

View File

@ -58,7 +58,7 @@ for o, a in opt:
id.sort()
print "Supported formats (* indicates output format):"
for i in id:
if Image.SAVE.has_key(i):
if i in Image.SAVE:
print i+"*",
else:
print i,