Permalink
Browse files

Merge haskey-removal-5688

Author: vperic
Reviewer: itamar
Fixes: #5688

The "dict.has_key(k)" syntax is deprecated in Python 3, use the new
"k in dict" syntax instead. This change only covers the uses of has_key
covered by the tests.

In one case, the has_key function itself was being passed; pass the
internal __contains__ function instead.

git-svn-id: svn://svn.twistedmatrix.com/svn/Twisted/trunk@34521 bbbe8e31-12d6-0310-92fd-ac37d47ddeeb
  • Loading branch information...
1 parent 90b664c commit 7ae6c015073f483ff7ed8ccda439e961c3108fb3 vperic committed Jun 7, 2012
@@ -169,7 +169,7 @@ class Service:
def __getstate__(self):
dict = self.__dict__.copy()
- if dict.has_key("running"):
+ if "running" in dict:
del dict['running']
return dict
@@ -298,7 +298,7 @@ def __iter__(self):
def addService(self, service):
if service.name is not None:
- if self.namedServices.has_key(service.name):
+ if service.name in self.namedServices:
raise RuntimeError("cannot have two services with same name"
" '%s'" % service.name)
self.namedServices[service.name] = service
View
@@ -303,11 +303,11 @@ def _setAttrs(self, path, attrs):
NOTE: this function assumes it runs as the logged-in user:
i.e. under _runAsUser()
"""
- if attrs.has_key("uid") and attrs.has_key("gid"):
+ if "uid" in attrs and "gid" in attrs:
os.chown(path, attrs["uid"], attrs["gid"])
- if attrs.has_key("permissions"):
+ if "permissions" in attrs:
os.chmod(path, attrs["permissions"])
- if attrs.has_key("atime") and attrs.has_key("mtime"):
+ if "atime" in attrs and "mtime" in attrs:
os.utime(path, (attrs["atime"], attrs["mtime"]))
def _getAttrs(self, s):
@@ -399,7 +399,7 @@ def __init__(self, server, filename, flags, attrs):
openFlags |= os.O_TRUNC
if flags & FXF_EXCL == FXF_EXCL:
openFlags |= os.O_EXCL
- if attrs.has_key("permissions"):
+ if "permissions" in attrs:
mode = attrs["permissions"]
del attrs["permissions"]
else:
@@ -218,7 +218,7 @@ def __init__(self, dbapiName, *connargs, **connkw):
for arg in self.CP_ARGS:
cp_arg = 'cp_%s' % arg
- if connkw.has_key(cp_arg):
+ if cp_arg in connkw:
setattr(self, arg, connkw[cp_arg])
del connkw[cp_arg]
View
@@ -12,7 +12,7 @@ def getIndexFilename():
def addEntry(filename, anchor, text, reference):
global entries
- if not entries.has_key(text):
+ if text not in entries:
entries[text] = []
entries[text].append((filename, anchor, reference))
View
@@ -196,7 +196,7 @@ def list2dict(l):
'ol': lambda x: x=='toc', 'li': lambda x: x=='ignoretoc'}
def getDefaultChecker():
- return DefaultTagChecker(tags.has_key, allowed)
+ return DefaultTagChecker(tags.__contains__, allowed)
def doFile(file, checker):
doc = tree.parseFileAndReport(file)
View
@@ -4665,7 +4665,7 @@ def allocateID(self):
##
def addMailbox(self, name, mbox = None):
name = name.upper()
- if self.mailboxes.has_key(name):
+ if name in self.mailboxes:
raise MailboxCollision, name
if mbox is None:
mbox = self._emptyMailbox(name, self.allocateID())
@@ -4715,14 +4715,14 @@ def delete(self, name):
def rename(self, oldname, newname):
oldname = oldname.upper()
newname = newname.upper()
- if not self.mailboxes.has_key(oldname):
+ if oldname not in self.mailboxes:
raise NoSuchMailbox, oldname
inferiors = self._inferiorNames(oldname)
inferiors = [(o, o.replace(oldname, newname, 1)) for o in inferiors]
for (old, new) in inferiors:
- if self.mailboxes.has_key(new):
+ if new in self.mailboxes:
raise MailboxCollision, new
for (old, new) in inferiors:
@@ -29,7 +29,7 @@
class Pool(UserDict.UserDict):
def getExplorer(self, object, identifier):
oid = id(object)
- if self.data.has_key(oid):
+ if oid in self.data:
# XXX: This potentially returns something with
# 'identifier' set to a different value.
return self.data[oid]
@@ -255,7 +255,7 @@ def console(self, message):
compatMessage = None
for client in clients:
try:
- if not client.capabilities.has_key("Failure"):
+ if "Failure" not in client.capabilities:
if compatMessage is None:
compatMessage = origMessage[:]
for i in xrange(len(message)):
View
@@ -97,7 +97,7 @@ def cacheResult(self, query, payload, cacheTime=None):
self.cache[query] = (cacheTime or self._reactor.seconds(), payload)
- if self.cancel.has_key(query):
+ if query in self.cancel:
self.cancel[query].cancel()
s = list(payload[0]) + list(payload[1]) + list(payload[2])
View
@@ -63,7 +63,7 @@ def __init__(self, head, body):
def getHeader(self, header):
h = header.lower()
- if self.headers.has_key(h):
+ if h in self.headers:
return self.headers[h][1]
else:
return ''
@@ -350,7 +350,7 @@ def postRequest(self, message):
return self.notifyModerators(moderators, a)
for group in groups:
- if self.db.has_key(group):
+ if group in self.db:
if len(self.db[group].keys()):
index = max(self.db[group].keys()) + 1
else:
@@ -469,7 +469,7 @@ def flush(self):
def load(self, filename, groups = None, moderators = ()):
- if PickleStorage.sharedDBs.has_key(filename):
+ if filename in PickleStorage.sharedDBs:
self.db = PickleStorage.sharedDBs[filename]
else:
try:
@@ -646,7 +646,7 @@ def xhdrRequest(self, group, low, high, header):
high = self.dbm['groups'][group].maxArticle
r = []
for i in range(low, high + 1):
- if self.dbm['groups'][group].articles.has_key(i):
+ if i in self.dbm['groups'][group].articles:
r.append((i, self.dbm['groups'][group].articles[i].getHeader(header)))
return defer.succeed(r)
View
@@ -260,7 +260,7 @@ def unjellyFromSource(stringOrFile):
else:
exec stringOrFile in ns
- if ns.has_key('app'):
+ if 'app' in ns:
return unjellyFromAOT(ns['app'])
else:
raise ValueError("%s needs to define an 'app', it didn't!" % stringOrFile)
@@ -504,7 +504,7 @@ def jellyToAO(self, obj):
#mutable inside one. The Ref() class will only print the "Ref(..)" around an
#object if it has a Reference explicitly attached.
- if self.prepared.has_key(id(obj)):
+ if id(obj) in self.prepared:
oldRef = self.prepared[id(obj)]
if oldRef.refnum:
# it's been referenced already
@@ -538,7 +538,7 @@ def jellyToAO(self, obj):
state = self.jellyToAO(obj.__dict__)
retval.setObj(Instance(reflect.qual(obj.__class__), state))
- elif copy_reg.dispatch_table.has_key(objType):
+ elif objType in copy_reg.dispatch_table:
unpickleFunc, state = copy_reg.dispatch_table[objType](obj)
retval.setObj(Copyreg( reflect.fullFuncName(unpickleFunc),
@@ -68,7 +68,7 @@ def pickleModule(module):
def unpickleModule(name):
'support function for copy_reg to unpickle module refs'
- if oldModules.has_key(name):
+ if name in oldModules:
log.msg("Module has moved: %s" % name)
name = oldModules[name]
log.msg(name)
@@ -202,11 +202,11 @@ def __getstate__(self, dict=None):
bases.reverse()
bases.append(self.__class__) # don't forget me!!
for base in bases:
- if base.__dict__.has_key('persistenceForgets'):
+ if 'persistenceForgets' in base.__dict__:
for slot in base.persistenceForgets:
- if dct.has_key(slot):
+ if slot in dct:
del dct[slot]
- if base.__dict__.has_key('persistenceVersion'):
+ if 'persistenceVersion' in base.__dict__:
dct['%s.persistenceVersion' % reflect.qual(base)] = base.persistenceVersion
return dct
@@ -219,7 +219,7 @@ def versionUpgrade(self):
bases.reverse()
bases.append(self.__class__) # don't forget me!!
# first let's look for old-skool versioned's
- if self.__dict__.has_key("persistenceVersion"):
+ if "persistenceVersion" in self.__dict__:
# Hacky heuristic: if more than one class subclasses Versioned,
# we'll assume that the higher version number wins for the older
@@ -244,7 +244,7 @@ def versionUpgrade(self):
for base in bases:
# ugly hack, but it's what the user expects, really
if (Versioned not in base.__bases__ and
- not base.__dict__.has_key('persistenceVersion')):
+ 'persistenceVersion' not in base.__dict__):
continue
currentVers = base.persistenceVersion
pverName = '%s.persistenceVersion' % reflect.qual(base)
View
@@ -1302,7 +1302,7 @@ def __init__(self, domain):
def getAddress(self, userURI):
if userURI.host != self.domain:
return defer.fail(LookupError("unknown domain"))
- if self.users.has_key(userURI.username):
+ if userURI.username in self.users:
dc, url = self.users[userURI.username]
return defer.succeed(url)
else:
@@ -1334,7 +1334,7 @@ def registerAddress(self, domainURL, logicalURL, physicalURL):
if logicalURL.host != self.domain:
log.msg("Registration for domain we don't handle.")
return defer.fail(RegistrationError(404))
- if self.users.has_key(logicalURL.username):
+ if logicalURL.username in self.users:
dc, old = self.users[logicalURL.username]
dc.reset(3600)
else:
@@ -282,7 +282,7 @@ def getComponent(self, interface, default=None):
True on your adapter class.
"""
k = reflect.qual(interface)
- if self._adapterCache.has_key(k):
+ if k in self._adapterCache:
return self._adapterCache[k]
else:
adapter = interface.__adapt__(self)
@@ -632,7 +632,7 @@ def __getstate__(self):
returning everything else.
"""
d = self.__dict__.copy()
- if d.has_key('statinfo'):
+ if 'statinfo' in d:
del d['statinfo']
return d
@@ -176,7 +176,7 @@ def rebuild(module, doLog=1):
values.update(classes)
values.update(functions)
- fromOldModule = values.has_key
+ fromOldModule = values.__contains__
newclasses = newclasses.keys()
classes = classes.keys()
functions = functions.keys()
View
@@ -59,7 +59,8 @@ def __setitem__(self, key, value):
def has_key(self, key):
"""Case insensitive test whether 'key' exists."""
k = self._lowerOrReturn(key)
- return self.data.has_key(k)
+ return k in self.data
+
__contains__=has_key
def _doPreserve(self, key):
@@ -210,7 +211,8 @@ def uniquify(lst):
dct = {}
result = []
for k in lst:
- if not dct.has_key(k): result.append(k)
+ if k not in dct:
+ result.append(k)
dct[k] = 1
return result
View
@@ -844,13 +844,13 @@ def _sendMessage(self, prefix, perspective, objectID, message, args, kw):
pbc = None
pbe = None
answerRequired = 1
- if kw.has_key('pbcallback'):
+ if 'pbcallback' in kw:
pbc = kw['pbcallback']
del kw['pbcallback']
- if kw.has_key('pberrback'):
+ if 'pberrback' in kw:
pbe = kw['pberrback']
del kw['pberrback']
- if kw.has_key('pbanswer'):
+ if 'pbanswer' in kw:
assert (not pbe) and (not pbc), "You can't specify a no-answer requirement."
answerRequired = kw['pbanswer']
del kw['pbanswer']
View
@@ -36,7 +36,7 @@ def testObservation(self):
i = catcher.pop()
self.assertEqual(i["message"][0], "test")
self.assertEqual(i["testShouldCatch"], True)
- self.failUnless(i.has_key("time"))
+ self.assertIn("time", i)
self.assertEqual(len(catcher), 0)
@@ -71,7 +71,7 @@ def __init__(self):
self.avatars = {}
def requestAvatar(self, avatarId, mind, *interfaces):
- if self.avatars.has_key(avatarId):
+ if avatarId in self.avatars:
avatar = self.avatars[avatarId]
else:
avatar = TestAvatar(avatarId)
@@ -0,0 +1 @@
+
View
@@ -381,7 +381,7 @@ def _cancelTimeout(self, result, timeoutCall):
def gotHeaders(self, headers):
self.response_headers = headers
- if headers.has_key('set-cookie'):
+ if 'set-cookie' in headers:
for cookie in headers['set-cookie']:
cookparts = cookie.split(';')
cook = cookparts[0]
View
@@ -827,7 +827,7 @@ def gotTagStart(self, name, attributes):
ksplit = k.split(':', 1)
if len(ksplit) == 2:
pfx, tv = ksplit
- if pfx != 'xml' and namespaces.has_key(pfx):
+ if pfx != 'xml' and pfx in namespaces:
attributes[namespaces[pfx], tv] = v
del attributes[k]
el = Element(name, attributes, parent,
View
@@ -138,7 +138,7 @@ def loadMimeTypes(mimetype_locations=['/etc/mime.types']):
def getTypeAndEncoding(filename, types, encodings, defaultType):
p, ext = os.path.splitext(filename)
ext = ext.lower()
- if encodings.has_key(ext):
+ if ext in encodings:
enc = encodings[ext]
ext = os.path.splitext(p)[1].lower()
else:
View
@@ -132,8 +132,7 @@ def maybeBodyData(self):
# lenient behavior, because those may not have </script>
# -radix
- if (self.tagName == 'script'
- and not self.tagAttributes.has_key('src')):
+ if (self.tagName == 'script' and 'src' not in self.tagAttributes):
# we do this ourselves rather than having begin_waitforendscript
# becuase that can get called multiple times and we don't want
# bodydata to get reset other than the first time.
View
@@ -118,7 +118,7 @@ def render(self, request):
env[envname] = header
# Propogate our environment
for key, value in os.environ.items():
- if not env.has_key(key):
+ if key not in env:
env[key] = value
# And they're off!
self.runProcess(env, request, qargs)
@@ -93,7 +93,7 @@ def contactChangedNick(self, person, newnick):
@type newnick: C{str}
"""
oldname = person.name
- if self.contacts.has_key(oldname):
+ if oldname in self.contacts:
del self.contacts[oldname]
person.name = newnick
self.contacts[newnick] = person
@@ -502,7 +502,7 @@ def contactChangedNick(self, person, newnick):
@param newnick: The new C{name} C{person} will take.
"""
oldnick = person.name
- if self.persons.has_key((oldnick, person.account)):
+ if (oldnick, person.account) in self.persons:
conv = self.conversations.get(person)
if conv:
conv.contactChangedNick(person, newnick)
Oops, something went wrong.

0 comments on commit 7ae6c01

Please sign in to comment.