replace has_key with 'in' operator

This commit is contained in:
Benjamin Peterson 2009-10-09 22:15:50 +00:00
parent de0559998f
commit 6e3dbbdf39
29 changed files with 71 additions and 71 deletions

View File

@ -257,7 +257,7 @@ class Bdb:
# pair, then remove the breaks entry
for bp in Breakpoint.bplist[filename, lineno][:]:
bp.deleteMe()
if not Breakpoint.bplist.has_key((filename, lineno)):
if (filename, lineno) not in Breakpoint.bplist:
self.breaks[filename].remove(lineno)
if not self.breaks[filename]:
del self.breaks[filename]
@ -464,7 +464,7 @@ class Breakpoint:
Breakpoint.next = Breakpoint.next + 1
# Build the two lists
self.bpbynumber.append(self)
if self.bplist.has_key((file, line)):
if (file, line) in self.bplist:
self.bplist[file, line].append(self)
else:
self.bplist[file, line] = [self]

View File

@ -182,7 +182,7 @@ if __name__ == '__main__':
L = []
_curses.initscr()
for key in _capability_names.keys():
system = _curses.has_key(key)
system = key in _curses
python = has_key(key)
if system != python:
L.append( 'Mismatch for key %s, system=%i, Python=%i'

View File

@ -249,16 +249,16 @@ class Message:
# BAW: should we accept strings that can serve as arguments to the
# Charset constructor?
self._charset = charset
if not self.has_key('MIME-Version'):
if 'MIME-Version' not in self:
self.add_header('MIME-Version', '1.0')
if not self.has_key('Content-Type'):
if 'Content-Type' not in self:
self.add_header('Content-Type', 'text/plain',
charset=charset.get_output_charset())
else:
self.set_param('charset', charset.get_output_charset())
if str(charset) != charset.get_output_charset():
self._payload = charset.body_encode(self._payload)
if not self.has_key('Content-Transfer-Encoding'):
if 'Content-Transfer-Encoding' not in self:
cte = charset.get_body_encoding()
try:
cte(self)
@ -551,7 +551,7 @@ class Message:
VALUE item in the 3-tuple) is always unquoted, unless unquote is set
to False.
"""
if not self.has_key(header):
if header not in self:
return failobj
for k, v in self._get_params_preserve(failobj, header):
if k.lower() == param.lower():
@ -582,7 +582,7 @@ class Message:
if not isinstance(value, tuple) and charset:
value = (charset, language, value)
if not self.has_key(header) and header.lower() == 'content-type':
if header not in self and header.lower() == 'content-type':
ctype = 'text/plain'
else:
ctype = self.get(header)
@ -617,7 +617,7 @@ class Message:
False. Optional header specifies an alternative to the Content-Type
header.
"""
if not self.has_key(header):
if header not in self:
return
new_ctype = ''
for p, v in self.get_params(header=header, unquote=requote):
@ -653,7 +653,7 @@ class Message:
if header.lower() == 'content-type':
del self['mime-version']
self['MIME-Version'] = '1.0'
if not self.has_key(header):
if header not in self:
self[header] = type
return
params = self.get_params(header=header, unquote=requote)

View File

@ -147,7 +147,7 @@ def search_function(encoding):
pass
else:
for alias in codecaliases:
if not _aliases.has_key(alias):
if alias not in _aliases:
_aliases[alias] = modname
# Return the registry entry

View File

@ -30,7 +30,7 @@ class LogReader:
self._reader = _hotshot.logreader(logfn)
self._nextitem = self._reader.next
self._info = self._reader.info
if self._info.has_key('current-directory'):
if 'current-directory' in self._info:
self.cwd = self._info['current-directory']
else:
self.cwd = None

View File

@ -705,8 +705,8 @@ class EditorWindow(object):
if accel:
itemName = menu.entrycget(index, 'label')
event = ''
if menuEventDict.has_key(menubarItem):
if menuEventDict[menubarItem].has_key(itemName):
if menubarItem in menuEventDict:
if itemName in menuEventDict[menubarItem]:
event = menuEventDict[menubarItem][itemName]
if event:
accel = get_accelerator(keydefs, event)

View File

@ -25,7 +25,7 @@ class FileList:
master=self.root)
return None
key = os.path.normcase(filename)
if self.dict.has_key(key):
if key in self.dict:
edit = self.dict[key]
edit.top.wakeup()
return edit
@ -79,7 +79,7 @@ class FileList:
newkey = os.path.normcase(filename)
if newkey == key:
return
if self.dict.has_key(newkey):
if newkey in self.dict:
conflict = self.dict[newkey]
self.inversedict[conflict] = None
tkMessageBox.showerror(

View File

@ -185,7 +185,7 @@ class _ComplexBinder:
seq, handler)))
def bind(self, triplet, func):
if not self.bindedfuncs.has_key(triplet[2]):
if triplet[2] not in self.bindedfuncs:
self.bindedfuncs[triplet[2]] = [[] for s in _states]
for s in _states:
lists = [ self.bindedfuncs[detail][i]

View File

@ -9,7 +9,7 @@ class MultiStatusBar(Frame):
self.labels = {}
def set_label(self, name, text='', side=LEFT):
if not self.labels.has_key(name):
if name not in self.labels:
label = Label(self, bd=1, relief=SUNKEN, anchor=W)
label.pack(side=side)
self.labels[name] = label

View File

@ -126,7 +126,7 @@ dispatch = {
def make_objecttreeitem(labeltext, object, setfunction=None):
t = type(object)
if dispatch.has_key(t):
if t in dispatch:
c = dispatch[t]
else:
c = ObjectTreeItem

View File

@ -78,7 +78,7 @@ class DirBrowserTreeItem(TreeItem):
normed_name = os.path.normcase(name)
if normed_name[i:] == suff:
mod_name = name[:i]
if not modules.has_key(mod_name):
if mod_name not in modules:
modules[mod_name] = None
sorted.append((normed_name, name))
allnames.remove(name)

View File

@ -230,7 +230,7 @@ class FrameProxy:
return self._get_dict_proxy(did)
def _get_dict_proxy(self, did):
if self._dictcache.has_key(did):
if did in self._dictcache:
return self._dictcache[did]
dp = DictProxy(self._conn, self._oid, did)
self._dictcache[did] = dp

View File

@ -409,7 +409,7 @@ class FileTreeItem(TreeItem):
class ScrolledCanvas:
def __init__(self, master, **opts):
if not opts.has_key('yscrollincrement'):
if 'yscrollincrement' not in opts:
opts['yscrollincrement'] = 17
self.master = master
self.frame = Frame(master)

View File

@ -562,7 +562,7 @@ class ConfigDialog(Toplevel):
def AddChangedItem(self,type,section,item,value):
value=str(value) #make sure we use a string
if not self.changedItems[type].has_key(section):
if section not in self.changedItems[type]:
self.changedItems[type][section]={}
self.changedItems[type][section][item]=value
@ -709,7 +709,7 @@ class ConfigDialog(Toplevel):
return
#remove key set from config
idleConf.userCfg['keys'].remove_section(keySetName)
if self.changedItems['keys'].has_key(keySetName):
if keySetName in self.changedItems['keys']:
del(self.changedItems['keys'][keySetName])
#write changes
idleConf.userCfg['keys'].Save()
@ -736,7 +736,7 @@ class ConfigDialog(Toplevel):
return
#remove theme from config
idleConf.userCfg['highlight'].remove_section(themeName)
if self.changedItems['highlight'].has_key(themeName):
if themeName in self.changedItems['highlight']:
del(self.changedItems['highlight'][themeName])
#write changes
idleConf.userCfg['highlight'].Save()
@ -871,9 +871,9 @@ class ConfigDialog(Toplevel):
#handle any unsaved changes to this theme
if theme in self.changedItems['highlight'].keys():
themeDict=self.changedItems['highlight'][theme]
if themeDict.has_key(element+'-foreground'):
if element+'-foreground' in themeDict:
colours['foreground']=themeDict[element+'-foreground']
if themeDict.has_key(element+'-background'):
if element+'-background' in themeDict:
colours['background']=themeDict[element+'-background']
self.textHighlightSample.tag_config(element, **colours)
self.SetColourSample()

View File

@ -169,7 +169,7 @@ class SocketIO(object):
how, (oid, methodname, args, kwargs) = request
except TypeError:
return ("ERROR", "Bad request format")
if not self.objtable.has_key(oid):
if oid not in self.objtable:
return ("ERROR", "Unknown object id: %r" % (oid,))
obj = self.objtable[oid]
if methodname == "__methods__":
@ -304,7 +304,7 @@ class SocketIO(object):
# wait for notification from socket handling thread
cvar = self.cvars[myseq]
cvar.acquire()
while not self.responses.has_key(myseq):
while myseq not in self.responses:
cvar.wait()
response = self.responses[myseq]
self.debug("_getresponse:%s: thread woke up: response: %s" %
@ -550,7 +550,7 @@ class RPCProxy(object):
return MethodProxy(self.sockio, self.oid, name)
if self.__attributes is None:
self.__getattributes()
if self.__attributes.has_key(name):
if name in self.__attributes:
value = self.sockio.remotecall(self.oid, '__getattribute__',
(name,), {})
return value

View File

@ -107,7 +107,7 @@ class FileDialog:
self.top.bind('<Alt-W>', self.cancel_command)
def go(self, dir_or_file=os.curdir, pattern="*", default="", key=None):
if key and dialogstates.has_key(key):
if key and key in dialogstates:
self.directory, pattern = dialogstates[key]
else:
dir_or_file = os.path.expanduser(dir_or_file)

View File

@ -52,7 +52,7 @@ if not os.path.exists(prefix):
# if this does not exist, no further search is needed
if os.path.exists(prefix):
prefix = convert_path(prefix)
if not os.environ.has_key("TCL_LIBRARY"):
if "TCL_LIBRARY" not in os.environ:
for name in os.listdir(prefix):
if name.startswith("tcl"):
tcldir = os.path.join(prefix,name)
@ -62,13 +62,13 @@ if os.path.exists(prefix):
# as Tcl
import _tkinter
ver = str(_tkinter.TCL_VERSION)
if not os.environ.has_key("TK_LIBRARY"):
if "TK_LIBRARY" not in os.environ:
v = os.path.join(prefix, 'tk'+ver)
if os.path.exists(os.path.join(v, "tclIndex")):
os.environ['TK_LIBRARY'] = v
# We don't know the Tix version, so we must search the entire
# directory
if not os.environ.has_key("TIX_LIBRARY"):
if "TIX_LIBRARY" not in os.environ:
for name in os.listdir(prefix):
if name.startswith("tix"):
tixdir = os.path.join(prefix,name)

View File

@ -336,7 +336,7 @@ class TixWidget(Tkinter.Widget):
# We can even do w.ok.invoke() because w.ok is subclassed from the
# Button class if you go through the proper constructors
def __getattr__(self, name):
if self.subwidget_list.has_key(name):
if name in self.subwidget_list:
return self.subwidget_list[name]
raise AttributeError, name
@ -464,9 +464,9 @@ class TixSubWidget(TixWidget):
# also destroys the parent NoteBook thus leading to an exception
# in Tkinter when it finally calls Tcl to destroy the NoteBook
for c in self.children.values(): c.destroy()
if self.master.children.has_key(self._name):
if self._name in self.master.children:
del self.master.children[self._name]
if self.master.subwidget_list.has_key(self._name):
if self._name in self.master.subwidget_list:
del self.master.subwidget_list[self._name]
if self.destroy_physically:
# This is bypassed only for a few widgets
@ -488,8 +488,8 @@ class DisplayStyle:
def __init__(self, itemtype, cnf={}, **kw):
master = _default_root # global from Tkinter
if not master and cnf.has_key('refwindow'): master=cnf['refwindow']
elif not master and kw.has_key('refwindow'): master= kw['refwindow']
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"
self.tk = master.tk
self.stylename = self.tk.call('tixDisplayStyle', itemtype,
@ -571,7 +571,7 @@ class ButtonBox(TixWidget):
return btn
def invoke(self, name):
if self.subwidget_list.has_key(name):
if name in self.subwidget_list:
self.tk.call(self._w, 'invoke', name)
class ComboBox(TixWidget):
@ -1433,7 +1433,7 @@ class StdButtonBox(TixWidget):
self.subwidget_list['help'] = _dummyButton(self, 'help')
def invoke(self, name):
if self.subwidget_list.has_key(name):
if name in self.subwidget_list:
self.tk.call(self._w, 'invoke', name)
class TList(TixWidget, XView, YView):

View File

@ -547,7 +547,7 @@ class Misc:
A widget specified for the optional displayof keyword
argument specifies the target display."""
if not kw.has_key('displayof'): kw['displayof'] = self._w
if 'displayof' not in kw: kw['displayof'] = self._w
self.tk.call(('clipboard', 'clear') + self._options(kw))
def clipboard_append(self, string, **kw):
"""Append STRING to the Tk clipboard.
@ -555,7 +555,7 @@ class Misc:
A widget specified at the optional displayof keyword
argument specifies the target display. The clipboard
can be retrieved with selection_get."""
if not kw.has_key('displayof'): kw['displayof'] = self._w
if 'displayof' not in kw: kw['displayof'] = self._w
self.tk.call(('clipboard', 'append') + self._options(kw)
+ ('--', string))
# XXX grab current w/o window argument
@ -613,7 +613,7 @@ class Misc:
self.tk.call('option', 'readfile', fileName, priority)
def selection_clear(self, **kw):
"""Clear the current X selection."""
if not kw.has_key('displayof'): kw['displayof'] = self._w
if 'displayof' not in kw: kw['displayof'] = self._w
self.tk.call(('selection', 'clear') + self._options(kw))
def selection_get(self, **kw):
"""Return the contents of the current X selection.
@ -622,7 +622,7 @@ class Misc:
the selection and defaults to PRIMARY. A keyword
parameter displayof specifies a widget on the display
to use."""
if not kw.has_key('displayof'): kw['displayof'] = self._w
if 'displayof' not in kw: kw['displayof'] = self._w
return self.tk.call(('selection', 'get') + self._options(kw))
def selection_handle(self, command, **kw):
"""Specify a function COMMAND to call if the X
@ -653,7 +653,7 @@ class Misc:
be provided:
selection - name of the selection (default PRIMARY),
type - type of the selection (e.g. STRING, FILE_NAME)."""
if not kw.has_key('displayof'): kw['displayof'] = self._w
if 'displayof' not in kw: kw['displayof'] = self._w
name = self.tk.call(('selection', 'own') + self._options(kw))
if not name: return None
return self._nametowidget(name)
@ -1735,7 +1735,7 @@ class Tk(Misc, Wm):
the Tcl Interpreter and calls execfile on BASENAME.py and CLASSNAME.py if
such a file exists in the home directory."""
import os
if os.environ.has_key('HOME'): home = os.environ['HOME']
if 'HOME' in os.environ: home = os.environ['HOME']
else: home = os.curdir
class_tcl = os.path.join(home, '.%s.tcl' % className)
class_py = os.path.join(home, '.%s.py' % className)
@ -1942,7 +1942,7 @@ class BaseWidget(Misc):
self.master = master
self.tk = master.tk
name = None
if cnf.has_key('name'):
if 'name' in cnf:
name = cnf['name']
del cnf['name']
if not name:
@ -1953,7 +1953,7 @@ class BaseWidget(Misc):
else:
self._w = master._w + '.' + name
self.children = {}
if self.master.children.has_key(self._name):
if self._name in self.master.children:
self.master.children[self._name].destroy()
self.master.children[self._name] = self
def __init__(self, master, widgetName, cnf={}, kw={}, extra=()):
@ -1978,7 +1978,7 @@ class BaseWidget(Misc):
"""Destroy this and all descendants widgets."""
for c in self.children.values(): c.destroy()
self.tk.call('destroy', self._w)
if self.master.children.has_key(self._name):
if self._name in self.master.children:
del self.master.children[self._name]
Misc.destroy(self)
def _do(self, name, args=()):
@ -2006,7 +2006,7 @@ class Toplevel(BaseWidget, Wm):
extra = ()
for wmkey in ['screen', 'class_', 'class', 'visual',
'colormap']:
if cnf.has_key(wmkey):
if wmkey in cnf:
val = cnf[wmkey]
# TBD: a hack needed because some keys
# are not valid as keyword arguments
@ -2444,10 +2444,10 @@ class Frame(Widget):
highlightcolor, highlightthickness, relief, takefocus, visual, width."""
cnf = _cnfmerge((cnf, kw))
extra = ()
if cnf.has_key('class_'):
if 'class_' in cnf:
extra = ('-class', cnf['class_'])
del cnf['class_']
elif cnf.has_key('class'):
elif 'class' in cnf:
extra = ('-class', cnf['class'])
del cnf['class']
Widget.__init__(self, master, 'frame', cnf, {}, extra)
@ -3153,7 +3153,7 @@ class OptionMenu(Menubutton):
self.menuname = menu._w
# 'command' is the only supported keyword
callback = kwargs.get('command')
if kwargs.has_key('command'):
if 'command' in kwargs:
del kwargs['command']
if kwargs:
raise TclError, 'unknown option -'+kwargs.keys()[0]

View File

@ -283,7 +283,7 @@ def askfloat(title, prompt, **kw):
class _QueryString(_QueryDialog):
def __init__(self, *args, **kw):
if kw.has_key("show"):
if "show" in kw:
self.__show = kw["show"]
del kw["show"]
else:

View File

@ -335,10 +335,10 @@ def __forwardmethods(fromClass, toClass, toPart, exclude = ()):
if ex[:1] == '_' or ex[-1:] == '_':
del _dict[ex]
for ex in exclude:
if _dict.has_key(ex):
if ex in _dict:
del _dict[ex]
for ex in __methods(fromClass):
if _dict.has_key(ex):
if ex in _dict:
del _dict[ex]
for method, func in _dict.items():

View File

@ -330,7 +330,7 @@ class Directory:
file = os.path.basename(file)
absolute = os.path.join(self.absolute, src)
assert not re.search(r'[\?|><:/*]"', file) # restrictions on long names
if self.keyfiles.has_key(file):
if file in self.keyfiles:
logical = self.keyfiles[file]
else:
logical = None

View File

@ -124,7 +124,7 @@ class Ignore:
self._ignore = { '<string>': 1 }
def names(self, filename, modulename):
if self._ignore.has_key(modulename):
if modulename in self._ignore:
return self._ignore[modulename]
# haven't seen this one before, so see if the module name is

View File

@ -160,7 +160,7 @@ class BaseHandler:
Subclasses can extend this to add other defaults.
"""
if not self.headers.has_key('Content-Length'):
if 'Content-Length' not in self.headers:
self.set_content_length()
def start_response(self, status, headers,exc_info=None):
@ -195,11 +195,11 @@ class BaseHandler:
if self.origin_server:
if self.client_is_modern():
self._write('HTTP/%s %s\r\n' % (self.http_version,self.status))
if not self.headers.has_key('Date'):
if 'Date' not in self.headers:
self._write(
'Date: %s\r\n' % format_date_time(time.time())
)
if self.server_software and not self.headers.has_key('Server'):
if self.server_software and 'Server' not in self.headers:
self._write('Server: %s\r\n' % self.server_software)
else:
self._write('Status: %s\r\n' % self.status)

View File

@ -345,7 +345,7 @@ def check_environ(environ):
"Invalid CONTENT_LENGTH: %r" % environ['CONTENT_LENGTH'])
if not environ.get('SCRIPT_NAME'):
assert_(environ.has_key('PATH_INFO'),
assert_('PATH_INFO' in environ,
"One of SCRIPT_NAME or PATH_INFO are required (PATH_INFO "
"should at least be '/' if SCRIPT_NAME is empty)")
assert_(environ.get('SCRIPT_NAME') != '/',

View File

@ -57,7 +57,7 @@ def getDOMImplementation(name = None, features = ()):
return mod.getDOMImplementation()
elif name:
return registered[name]()
elif os.environ.has_key("PYTHON_DOM"):
elif "PYTHON_DOM" in os.environ:
return getDOMImplementation(name = os.environ["PYTHON_DOM"])
# User did not specify a name, try implementations in arbitrary

View File

@ -491,9 +491,9 @@ class NamedNodeMap(object):
def has_key(self, key):
if isinstance(key, StringTypes):
return self._attrs.has_key(key)
return key in self._attrs
else:
return self._attrsNS.has_key(key)
return key in self._attrsNS
def keys(self):
return self._attrs.keys()
@ -775,10 +775,10 @@ class Element(Node):
removeAttributeNodeNS = removeAttributeNode
def hasAttribute(self, name):
return self._attrs.has_key(name)
return name in self._attrs
def hasAttributeNS(self, namespaceURI, localName):
return self._attrsNS.has_key((namespaceURI, localName))
return (namespaceURI, localName) in self._attrsNS
def getElementsByTagName(self, name):
return _get_elements_by_tagName_helper(self, name, NodeList())

View File

@ -91,7 +91,7 @@ class DOMBuilder:
def canSetFeature(self, name, state):
key = (_name_xform(name), state and 1 or 0)
return self._settings.has_key(key)
return key in self._settings
# This dictionary maps from (feature,value) to a list of
# (option,value) pairs that should be set on the Options object.
@ -247,7 +247,7 @@ class DOMEntityResolver(object):
def _guess_media_encoding(self, source):
info = source.byteStream.info()
if info.has_key("Content-Type"):
if "Content-Type" in info:
for param in info.getplist():
if param.startswith("charset="):
return param.split("=", 1)[1].lower()

View File

@ -59,7 +59,7 @@ if _false:
import xml.sax.expatreader
import os, sys
if os.environ.has_key("PY_SAX_PARSER"):
if "PY_SAX_PARSER" in os.environ:
default_parser_list = os.environ["PY_SAX_PARSER"].split(",")
del os