summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorelie <elie>2011-01-20 17:11:43 +0000
committerelie <elie>2011-01-20 17:11:43 +0000
commitb009e5c04a5c462163fe7a1b0968bf752466f6b1 (patch)
tree65143c102be5321e894adb49572a6504779cfe75
parent85188ca7493ab60c45b02b4508fb24e71bd4cdeb (diff)
downloadpysnmp-b009e5c04a5c462163fe7a1b0968bf752466f6b1.tar.gz
all dict.has_key() & dict.get() invocations replaced with modern syntax
(this breaks compatibility with Python 2.1 and older).
-rw-r--r--CHANGES3
-rw-r--r--examples/v1arch/agent/cmdrsp.py4
-rw-r--r--examples/v1arch/manager/ntfrcv.py2
-rw-r--r--pysnmp/carrier/asynsock/base.py2
-rw-r--r--pysnmp/carrier/asynsock/dgram/base.py4
-rw-r--r--pysnmp/carrier/base.py20
-rw-r--r--pysnmp/carrier/twisted/dispatch.py5
-rw-r--r--pysnmp/debug.py2
-rw-r--r--pysnmp/entity/config.py4
-rw-r--r--pysnmp/entity/rfc3413/cmdrsp.py6
-rw-r--r--pysnmp/entity/rfc3413/context.py6
-rw-r--r--pysnmp/entity/rfc3413/ntfrcv.py4
-rw-r--r--pysnmp/entity/rfc3413/oneliner/cmdgen.py6
-rw-r--r--pysnmp/entity/rfc3413/oneliner/ntforg.py7
-rw-r--r--pysnmp/proto/error.py2
-rw-r--r--pysnmp/proto/mpmod/base.py30
-rw-r--r--pysnmp/proto/mpmod/rfc2576.py30
-rw-r--r--pysnmp/proto/mpmod/rfc3412.py66
-rw-r--r--pysnmp/proto/proxy/rfc2576.py26
-rw-r--r--pysnmp/proto/rfc3412.py53
-rw-r--r--pysnmp/proto/secmod/base.py5
-rw-r--r--pysnmp/proto/secmod/rfc2576.py6
-rw-r--r--pysnmp/proto/secmod/rfc3414/service.py62
-rw-r--r--pysnmp/smi/builder.py26
-rw-r--r--pysnmp/smi/error.py2
-rw-r--r--pysnmp/smi/indices.py205
-rw-r--r--pysnmp/smi/instrum.py24
-rw-r--r--pysnmp/smi/mibs/SNMPv2-SMI.py48
-rw-r--r--pysnmp/smi/mibs/instances/__SNMPv2-MIB.py2
-rw-r--r--pysnmp/smi/view.py78
30 files changed, 359 insertions, 381 deletions
diff --git a/CHANGES b/CHANGES
index 57ac2bd..9671a9d 100644
--- a/CHANGES
+++ b/CHANGES
@@ -5,6 +5,9 @@ Revision 4.1.16a
protocols implemented.
- The error-indication codes moved from literals to objects for reliability
and clarity
+- changes towards performance improvement:
+ + all dict.has_key() & dict.get() invocations replaced with modern syntax
+ (this breaks compatibility with Python 2.1 and older).
Revision 4.1.15a
----------------
diff --git a/examples/v1arch/agent/cmdrsp.py b/examples/v1arch/agent/cmdrsp.py
index 6c55aa4..9b3f992 100644
--- a/examples/v1arch/agent/cmdrsp.py
+++ b/examples/v1arch/agent/cmdrsp.py
@@ -33,7 +33,7 @@ for mibVar in mibInstr:
def cbFun(transportDispatcher, transportDomain, transportAddress, wholeMsg):
while wholeMsg:
msgVer = api.decodeMessageVersion(wholeMsg)
- if api.protoModules.has_key(msgVer):
+ if msgVer in api.protoModules:
pMod = api.protoModules[msgVer]
else:
print 'Unsupported SNMP version %s' % msgVer
@@ -66,7 +66,7 @@ def cbFun(transportDispatcher, transportDomain, transportAddress, wholeMsg):
)
elif reqPDU.isSameTypeWith(pMod.GetRequestPDU()):
for oid, val in pMod.apiPDU.getVarBinds(reqPDU):
- if mibInstrIdx.has_key(oid):
+ if oid in mibInstrIdx:
varBinds.append((oid, mibInstrIdx[oid](msgVer)))
else:
# No such instance
diff --git a/examples/v1arch/manager/ntfrcv.py b/examples/v1arch/manager/ntfrcv.py
index 0287200..a38c14c 100644
--- a/examples/v1arch/manager/ntfrcv.py
+++ b/examples/v1arch/manager/ntfrcv.py
@@ -7,7 +7,7 @@ from pysnmp.proto import api
def cbFun(transportDispatcher, transportDomain, transportAddress, wholeMsg):
while wholeMsg:
msgVer = int(api.decodeMessageVersion(wholeMsg))
- if api.protoModules.has_key(msgVer):
+ if msgVer in api.protoModules:
pMod = api.protoModules[msgVer]
else:
print 'Unsupported SNMP version %s' % msgVer
diff --git a/pysnmp/carrier/asynsock/base.py b/pysnmp/carrier/asynsock/base.py
index 36e1008..a0525be 100644
--- a/pysnmp/carrier/asynsock/base.py
+++ b/pysnmp/carrier/asynsock/base.py
@@ -49,7 +49,7 @@ class AbstractSocketTransport(asyncore.dispatcher):
def del_channel (self, sockMap=None):
if sockMap is None:
sockMap = asyncore.socket_map
- if sockMap.has_key(self):
+ if self in sockMap:
del sockMap[self]
def registerSocket(self, sockMap=None):
diff --git a/pysnmp/carrier/asynsock/dgram/base.py b/pysnmp/carrier/asynsock/dgram/base.py
index b13d939..c0f7dd8 100644
--- a/pysnmp/carrier/asynsock/dgram/base.py
+++ b/pysnmp/carrier/asynsock/dgram/base.py
@@ -56,7 +56,7 @@ class DgramSocketTransport(AbstractSocketTransport):
try:
self.socket.sendto(outgoingMessage, transportAddress)
except socket.error, why:
- if sockErrors.has_key(why[0]):
+ if why[0] in sockErrors:
debug.logger & debug.flagIO and debug.logger('handle_write: ignoring socket error %s' % (why,))
else:
raise socket.error, why
@@ -73,7 +73,7 @@ class DgramSocketTransport(AbstractSocketTransport):
self._cbFun(self, transportAddress, incomingMessage)
return
except socket.error, why:
- if sockErrors.has_key(why[0]):
+ if why[0] in sockErrors:
debug.logger & debug.flagIO and debug.logger('handle_read: known socket error %s' % (why,))
sockErrors[why[0]] and self.handle_close()
return
diff --git a/pysnmp/carrier/base.py b/pysnmp/carrier/base.py
index 4515be2..3fc8c0f 100644
--- a/pysnmp/carrier/base.py
+++ b/pysnmp/carrier/base.py
@@ -61,7 +61,7 @@ class AbstractTransportDispatcher:
self.__timerCallables.remove(timerCbFun)
def registerTransport(self, tDomain, transport):
- if self.__transports.has_key(tDomain):
+ if tDomain in self.__transports:
raise error.CarrierError(
'Transport %s already registered' % (tDomain,)
)
@@ -69,7 +69,7 @@ class AbstractTransportDispatcher:
self.__transports[tDomain] = transport
def unregisterTransport(self, tDomain):
- if not self.__transports.has_key(tDomain):
+ if tDomain not in self.__transports:
raise error.CarrierError(
'Transport %s not registered' % (tDomain,)
)
@@ -77,24 +77,30 @@ class AbstractTransportDispatcher:
del self.__transports[tDomain]
def getTransport(self, transportDomain):
- return self.__transports.get(transportDomain)
+ if transportDomain in self.__transports:
+ return self.__transports[transportDomain]
def sendMessage(
self, outgoingMessage, transportDomain, transportAddress
):
- transport = self.__transports.get(transportDomain)
- if transport is None:
+ if transportDomain in self.__transports:
+ self.__transports[transportDomain].sendMessage(
+ outgoingMessage, transportAddress
+ )
+ else:
raise error.CarrierError(
'No suitable transport domain for %s' % (transportDomain,)
)
- transport.sendMessage(outgoingMessage, transportAddress)
def handleTimerTick(self, timeNow):
for timerCallable in self.__timerCallables:
timerCallable(timeNow)
def jobStarted(self, jobId):
- self.__jobs[jobId] = self.__jobs.get(jobId, 0) + 1
+ if jobId in self.__jobs:
+ self.__jobs[jobId] = self.__jobs[jobId] + 1
+ else:
+ self.__jobs[jobId] = 1
def jobFinished(self, jobId):
self.__jobs[jobId] = self.__jobs[jobId] - 1
diff --git a/pysnmp/carrier/twisted/dispatch.py b/pysnmp/carrier/twisted/dispatch.py
index 36b4ccc..6bc4554 100644
--- a/pysnmp/carrier/twisted/dispatch.py
+++ b/pysnmp/carrier/twisted/dispatch.py
@@ -18,7 +18,10 @@ class TwistedDispatcher(AbstractTransportDispatcher):
def __init__(self, *args, **kwargs):
AbstractTransportDispatcher.__init__(self)
self.__transportCount = 0
- self.timeout = kwargs.get('timeout', 1.0)
+ if 'timeout' in kwargs:
+ self.timeout = kwargs['timeout']
+ else:
+ self.timeout = 1.0
self.loopingcall = task.LoopingCall(self.handleTimeout)
def handleTimeout(self):
diff --git a/pysnmp/debug.py b/pysnmp/debug.py
index 6f9b2c7..308ea65 100644
--- a/pysnmp/debug.py
+++ b/pysnmp/debug.py
@@ -34,7 +34,7 @@ class Debug:
self._flags = flagNone
self._printer = self.defaultPrinter
for f in flags:
- if not flagMap.has_key(f):
+ if f not in flagMap:
raise error.PySnmpError('bad debug flag %s' % f)
self._flags = self._flags | flagMap[f]
self('debug category %s enabled' % f)
diff --git a/pysnmp/entity/config.py b/pysnmp/entity/config.py
index 1ffb04b..d486e50 100644
--- a/pysnmp/entity/config.py
+++ b/pysnmp/entity/config.py
@@ -137,7 +137,7 @@ def addV3User(snmpEngine, securityName,
)
# Localize keys
- if authServices.has_key(authProtocol):
+ if authProtocol in authServices:
hashedAuthPassphrase = authServices[authProtocol].hashPassphrase(
authKey and authKey or ''
)
@@ -147,7 +147,7 @@ def addV3User(snmpEngine, securityName,
else:
raise error.PySnmpError('Unknown auth protocol %s' % (authProtocol,))
- if privServices.has_key(privProtocol):
+ if privProtocol in privServices:
hashedPrivPassphrase = privServices[privProtocol].hashPassphrase(
authProtocol, privKey and privKey or ''
)
diff --git a/pysnmp/entity/rfc3413/cmdrsp.py b/pysnmp/entity/rfc3413/cmdrsp.py
index a489d69..a820d07 100644
--- a/pysnmp/entity/rfc3413/cmdrsp.py
+++ b/pysnmp/entity/rfc3413/cmdrsp.py
@@ -100,8 +100,8 @@ class CommandResponderBase:
origPdu = None
# 3.2.1
- if not rfc3411.readClassPDUs.has_key(PDU.tagSet) and \
- not rfc3411.writeClassPDUs.has_key(PDU.tagSet):
+ if PDU.tagSet not in rfc3411.readClassPDUs and \
+ PDU.tagSet not in rfc3411.writeClassPDUs:
raise error.ProtocolError('Unexpected PDU class %s' % PDU.tagSet)
# 3.2.2 --> no-op
@@ -144,7 +144,7 @@ class CommandResponderBase:
# SNMPv2 SMI exceptions
except pysnmp.smi.error.GenError, errorIndication:
debug.logger & debug.flagApp and debug.logger('processPdu: stateReference %s, errorIndication %s' % (stateReference, errorIndication))
- if errorIndication.has_key('oid'):
+ if 'oid' in errorIndication:
# Request REPORT generation
statusInformation['oid'] = errorIndication['oid']
statusInformation['val'] = errorIndication['val']
diff --git a/pysnmp/entity/rfc3413/context.py b/pysnmp/entity/rfc3413/context.py
index d94d387..130f84c 100644
--- a/pysnmp/entity/rfc3413/context.py
+++ b/pysnmp/entity/rfc3413/context.py
@@ -15,7 +15,7 @@ class SnmpContext:
}
def registerContextName(self, contextName, mibInstrum=None):
- if self.contextNames.has_key(contextName):
+ if contextName in self.contextNames:
raise error.PySnmpError(
'Duplicate contextName %s' % contextName
)
@@ -26,12 +26,12 @@ class SnmpContext:
self.contextNames[contextName] = mibInstrum
def unregisterContextName(self, contextName):
- if self.contextNames.has_key(contextName):
+ if contextName in self.contextNames:
debug.logger & debug.flagIns and debug.logger('unregisterContextName: unregistered contextName \"%s\"' % contextName)
del self.contextNames[contextName]
def getMibInstrum(self, contextName):
- if not self.contextNames.has_key(contextName):
+ if contextName not in self.contextNames:
debug.logger & debug.flagIns and debug.logger('getMibInstrum: contextName \"%s\" not registered' % contextName)
raise error.PySnmpError(
'Missing contextName %s' % contextName
diff --git a/pysnmp/entity/rfc3413/ntfrcv.py b/pysnmp/entity/rfc3413/ntfrcv.py
index 9fe9e94..e933330 100644
--- a/pysnmp/entity/rfc3413/ntfrcv.py
+++ b/pysnmp/entity/rfc3413/ntfrcv.py
@@ -52,7 +52,7 @@ class NotificationReceiver:
debug.logger & debug.flagApp and debug.logger('processPdu: stateReference %s, varBinds %s' % (stateReference, varBinds))
# 3.4
- if rfc3411.confirmedClassPDUs.has_key(PDU.tagSet):
+ if PDU.tagSet in rfc3411.confirmedClassPDUs:
# 3.4.1 --> no-op
rspPDU = v2c.apiPDU.getResponse(PDU)
@@ -91,7 +91,7 @@ class NotificationReceiver:
snmpSilentDrops, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpSilentDrops')
snmpSilentDrops.syntax = snmpSilentDrops.syntax + 1
- elif rfc3411.unconfirmedClassPDUs.has_key(PDU.tagSet):
+ elif PDU.tagSet in rfc3411.unconfirmedClassPDUs:
pass
else:
raise error.ProtocolError('Unexpected PDU class %s' % PDU.tagSet)
diff --git a/pysnmp/entity/rfc3413/oneliner/cmdgen.py b/pysnmp/entity/rfc3413/oneliner/cmdgen.py
index 1204c67..c662ff1 100644
--- a/pysnmp/entity/rfc3413/oneliner/cmdgen.py
+++ b/pysnmp/entity/rfc3413/oneliner/cmdgen.py
@@ -145,7 +145,7 @@ class AsynCommandGenerator:
def cfgCmdGen(self, authData, transportTarget, tagList=''):
if isinstance(authData, CommunityData):
tagList = '%s %s' % (tagList, authData.securityName)
- if self.__knownAuths.has_key(authData):
+ if authData in self.__knownAuths:
paramsName = self.__knownAuths[authData]
else:
paramsName = 'p%s' % nextID()
@@ -179,7 +179,7 @@ class AsynCommandGenerator:
raise error.PySnmpError('Unsupported authentication object')
self.__knownAuths[authData] = paramsName
- if not self.__knownTransports.has_key(transportTarget.transportDomain):
+ if transportTarget.transportDomain not in self.__knownTransports:
transport = transportTarget.openClientMode()
config.addSocketTransport(
self.snmpEngine,
@@ -189,7 +189,7 @@ class AsynCommandGenerator:
self.__knownTransports[transportTarget.transportDomain] = transport
k = paramsName, transportTarget, tagList
- if self.__knownTransportAddrs.has_key(k):
+ if k in self.__knownTransportAddrs:
addrName = self.__knownTransportAddrs[k]
else:
addrName = 'a%s' % nextID()
diff --git a/pysnmp/entity/rfc3413/oneliner/ntforg.py b/pysnmp/entity/rfc3413/oneliner/ntforg.py
index 3c78b63..834c7c9 100644
--- a/pysnmp/entity/rfc3413/oneliner/ntforg.py
+++ b/pysnmp/entity/rfc3413/oneliner/ntforg.py
@@ -37,7 +37,7 @@ class AsynNotificationOriginator(cmdgen.AsynCommandGenerator):
authData, transportTarget, tagList
)
k = paramsName, tagList, notifyType
- if self.__knownNotifyNames.has_key(k):
+ if k in self.__knownNotifyNames:
notifyName, _ = self.__knownNotifyNames[k]
else:
notifyName = 'n%s' % cmdgen.nextID()
@@ -49,7 +49,7 @@ class AsynNotificationOriginator(cmdgen.AsynCommandGenerator):
notifyType
)
self.__knownNotifyNames[k] = notifyName, paramsName
- if not self.__knownAuths.has_key(authData):
+ if authData not in self.__knownAuths:
subTree = (1,3,6)
config.addTrapUser(
self.snmpEngine,
@@ -131,4 +131,5 @@ class NotificationOriginator(AsynNotificationOriginator):
(__cbFun, appReturn)
)
self.snmpEngine.transportDispatcher.runDispatcher()
- return appReturn.get('errorIndication')
+ if 'errorIndication' in appReturn:
+ return appReturn['errorIndication']
diff --git a/pysnmp/proto/error.py b/pysnmp/proto/error.py
index d1f3731..e9d157b 100644
--- a/pysnmp/proto/error.py
+++ b/pysnmp/proto/error.py
@@ -14,7 +14,7 @@ class StatusInformation(SnmpV3Error):
debug.logger & (debug.flagDsp|debug.flagMP|debug.flagSM|debug.flagACL) and debug.logger('StatusInformation: %s' % kwargs)
def __str__(self): return str(self.__errorIndication)
def __getitem__(self, key): return self.__errorIndication[key]
- def has_key(self, key): return self.__errorIndication.has_key(key)
+ def __contains__(self, key): return key in self.__errorIndication
def get(self, key, defVal=None):
return self.__errorIndication.get(key, defVal)
class CacheExpiredError(SnmpV3Error): pass
diff --git a/pysnmp/proto/mpmod/base.py b/pysnmp/proto/mpmod/base.py
index 666a4c3..7951273 100644
--- a/pysnmp/proto/mpmod/base.py
+++ b/pysnmp/proto/mpmod/base.py
@@ -65,7 +65,7 @@ class AbstractMessageProcessingModel:
# Server mode cache handling
def _cachePushByStateRef(self, stateReference, **msgInfo):
- if self.__stateReferenceIndex.has_key(stateReference):
+ if stateReference in self.__stateReferenceIndex:
raise error.ProtocolError(
'Cache dup for stateReference=%s at %s' %
(stateReference, self)
@@ -74,15 +74,16 @@ class AbstractMessageProcessingModel:
self.__stateReferenceIndex[stateReference] = ( msgInfo, expireAt )
# Schedule to expire
- if not self.__expirationQueue.has_key(expireAt):
+ if expireAt not in self.__expirationQueue:
self.__expirationQueue[expireAt] = {}
- if not self.__expirationQueue[expireAt].has_key('stateReference'):
+ if 'stateReference' not in self.__expirationQueue[expireAt]:
self.__expirationQueue[expireAt]['stateReference'] = {}
self.__expirationQueue[expireAt]['stateReference'][stateReference] = 1
def _cachePopByStateRef(self, stateReference):
- cacheInfo = self.__stateReferenceIndex.get(stateReference)
- if cacheInfo is None:
+ if stateReference in self.__stateReferenceIndex:
+ cacheInfo = self.__stateReferenceIndex[stateReference]
+ else:
raise error.ProtocolError(
'Cache miss for stateReference=%s at %s' %
(stateReference, self)
@@ -101,7 +102,7 @@ class AbstractMessageProcessingModel:
return self.__msgID
def _cachePushByMsgId(self, msgId, **msgInfo):
- if self.__msgIdIndex.has_key(msgId):
+ if msgId in self.__msgIdIndex:
raise error.ProtocolError(
'Cache dup for msgId=%s at %s' % (msgId, self)
)
@@ -111,15 +112,16 @@ class AbstractMessageProcessingModel:
self.__sendPduHandleIdx[msgInfo['sendPduHandle']] = msgId
# Schedule to expire
- if not self.__expirationQueue.has_key(expireAt):
+ if expireAt not in self.__expirationQueue:
self.__expirationQueue[expireAt] = {}
- if not self.__expirationQueue[expireAt].has_key('msgId'):
+ if 'msgId' not in self.__expirationQueue[expireAt]:
self.__expirationQueue[expireAt]['msgId'] = {}
self.__expirationQueue[expireAt]['msgId'][msgId] = 1
def _cachePopByMsgId(self, msgId):
- cacheInfo = self.__msgIdIndex.get(msgId)
- if cacheInfo is None:
+ if msgId in self.__msgIdIndex:
+ cacheInfo = self.__msgIdIndex[msgId]
+ else:
raise error.ProtocolError(
'Cache miss for msgId=%s at %s' % (msgId, self)
)
@@ -131,17 +133,17 @@ class AbstractMessageProcessingModel:
return cacheEntry
def _cachePopBySendPduHandle(self, sendPduHandle):
- if self.__sendPduHandleIdx.has_key(sendPduHandle):
+ if sendPduHandle in self.__sendPduHandleIdx:
self._cachePopByMsgId(self.__sendPduHandleIdx[sendPduHandle])
def __expireCaches(self):
# Uses internal clock to expire pending messages
- if self.__expirationQueue.has_key(self.__expirationTimer):
+ if self.__expirationTimer in self.__expirationQueue:
cacheInfo = self.__expirationQueue[self.__expirationTimer]
- if cacheInfo.has_key('stateReference'):
+ if 'stateReference' in cacheInfo:
for stateReference in cacheInfo['stateReference'].keys():
del self.__stateReferenceIndex[stateReference]
- if cacheInfo.has_key('msgId'):
+ if 'msgId' in cacheInfo:
for msgId in cacheInfo['msgId'].keys():
del self.__msgIdIndex[msgId]
del self.__expirationQueue[self.__expirationTimer]
diff --git a/pysnmp/proto/mpmod/rfc2576.py b/pysnmp/proto/mpmod/rfc2576.py
index fa3334e..393ade4 100644
--- a/pysnmp/proto/mpmod/rfc2576.py
+++ b/pysnmp/proto/mpmod/rfc2576.py
@@ -36,7 +36,7 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel):
snmpEngineID = snmpEngineID.syntax
# rfc3412: 7.1.1b
- if rfc3411.confirmedClassPDUs.has_key(pdu.tagSet):
+ if pdu.tagSet in rfc3411.confirmedClassPDUs:
pdu.setComponentByPosition(1)
msgID = pdu.getComponentByPosition(0)
@@ -63,8 +63,10 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel):
# rfc3412: 7.1.7
globalData = ( msg, )
- smHandler = snmpEngine.securityModels.get(int(securityModel))
- if smHandler is None:
+ k = int(securityModel)
+ if k in snmpEngine.securityModels:
+ smHandler = snmpEngine.securityModels[k]
+ else:
raise error.StatusInformation(
errorIndication = errind.unsupportedSecurityModel
)
@@ -88,7 +90,7 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel):
)
# rfc3412: 7.1.9.c
- if rfc3411.confirmedClassPDUs.has_key(pdu.tagSet):
+ if pdu.tagSet in rfc3411.confirmedClassPDUs:
# XXX rfc bug? why stateReference should be created?
self._cachePushByMsgId(
long(msgID),
@@ -174,8 +176,10 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel):
# rfc3412: 7.1.7
globalData = ( msg, )
- smHandler = snmpEngine.securityModels.get(int(securityModel))
- if smHandler is None:
+ k = int(securityModel)
+ if k in snmpEngine.securityModels:
+ smHandler = snmpEngine.securityModels[k]
+ else:
raise error.StatusInformation(
errorIndication = errind.unsupportedSecurityModel
)
@@ -241,8 +245,10 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel):
# rfc3412: 7.2.4 -- 7.2.5 -> noop
- smHandler = snmpEngine.securityModels.get(int(securityModel))
- if smHandler is None:
+ k = int(securityModel)
+ if k in snmpEngine.securityModels:
+ smHandler = snmpEngine.securityModels[k]
+ else:
raise error.StatusInformation(
errorIndication = errind.unsupportedSecurityModel
)
@@ -281,7 +287,7 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel):
# rfc3412: 7.2.8, 7.2.9 -> noop
# rfc3412: 7.2.10
- if rfc3411.responseClassPDUs.has_key(pduType):
+ if pduType in rfc3411.responseClassPDUs:
# 7.2.10a
try:
cachedReqParams = self._cachePopByMsgId(long(msgID))
@@ -301,7 +307,7 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel):
# rfc3412: 7.2.11 -> noop
# rfc3412: 7.2.12
- if rfc3411.responseClassPDUs.has_key(pduType):
+ if pduType in rfc3411.responseClassPDUs:
# rfc3412: 7.2.12a -> noop
# rfc3412: 7.2.12b
if securityModel != cachedReqParams['securityModel'] or \
@@ -333,7 +339,7 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel):
stateReference )
# rfc3412: 7.2.13
- if rfc3411.confirmedClassPDUs.has_key(pduType):
+ if pduType in rfc3411.confirmedClassPDUs:
# rfc3412: 7.2.13a
snmpEngineID, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID')
if securityEngineID != snmpEngineID.syntax:
@@ -378,7 +384,7 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel):
stateReference )
# rfc3412: 7.2.14
- if rfc3411.unconfirmedClassPDUs.has_key(pduType):
+ if pduType in rfc3411.unconfirmedClassPDUs:
# This is not specified explicitly in RFC
smHandler.releaseStateInformation(securityStateReference)
return ( messageProcessingModel,
diff --git a/pysnmp/proto/mpmod/rfc3412.py b/pysnmp/proto/mpmod/rfc3412.py
index 97afede..950badb 100644
--- a/pysnmp/proto/mpmod/rfc3412.py
+++ b/pysnmp/proto/mpmod/rfc3412.py
@@ -84,10 +84,12 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
msgID = self._newMsgID()
debug.logger & debug.flagMP and debug.logger('prepareOutgoingMessage: new msgID %s' % msgID)
-
- peerSnmpEngineData = self.__engineIDs.get(
- (transportDomain, transportAddress)
- )
+
+ k = (transportDomain, transportAddress)
+ if k in self.__engineIDs:
+ peerSnmpEngineData = self.__engineIDs[k]
+ else:
+ peerSnmpEngineData = None
debug.logger & debug.flagMP and debug.logger('prepareOutgoingMessage: peer SNMP engine data %s for transport %s, address %s' % (peerSnmpEngineData, transportDomain, transportAddress))
@@ -147,7 +149,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
'Unknown securityLevel %s' % securityLevel
)
- if rfc3411.confirmedClassPDUs.has_key(pdu.tagSet):
+ if pdu.tagSet in rfc3411.confirmedClassPDUs:
msgFlags = msgFlags | 0x04
headerData.setComponentByPosition(2, chr(msgFlags))
@@ -158,14 +160,15 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
debug.logger & debug.flagMP and debug.logger('prepareOutgoingMessage: %s' % (msg.prettyPrint(),))
- smHandler = snmpEngine.securityModels.get(securityModel)
- if smHandler is None:
+ if securityModel in snmpEngine.securityModels:
+ smHandler = snmpEngine.securityModels[securityModel]
+ else:
raise error.StatusInformation(
errorIndication = errind.unsupportedSecurityModel
)
# 7.1.9.a
- if rfc3411.unconfirmedClassPDUs.has_key(pdu.tagSet):
+ if pdu.tagSet in rfc3411.unconfirmedClassPDUs:
securityEngineID = snmpEngineID
else:
if peerSnmpEngineData is None:
@@ -212,7 +215,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
raise error.StatusInformation(errorIndication=errind.tooBig)
# 7.1.9.c
- if rfc3411.confirmedClassPDUs.has_key(pdu.tagSet):
+ if pdu.tagSet in rfc3411.confirmedClassPDUs:
# XXX rfc bug? why stateReference should be created?
self._cachePushByMsgId(
msgID,
@@ -267,7 +270,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
debug.logger & debug.flagMP and debug.logger('prepareResponseMessage: stateReference %s' % (stateReference))
# 7.1.3
- if statusInformation is not None and statusInformation.has_key('oid'):
+ if statusInformation is not None and 'oid' in statusInformation:
# 7.1.3a
if pdu is not None:
requestID = pdu.getComponentByPosition(0)
@@ -278,7 +281,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
# 7.1.3b
if pdu is None and not reportableFlag or \
pduType is not None and \
- not rfc3411.confirmedClassPDUs.has_key(pduType):
+ pduType not in rfc3411.confirmedClassPDUs:
raise error.StatusInformation(
errorIndication = errind.loopTerminated
)
@@ -297,19 +300,19 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
pMod.apiPDU.setRequestID(reportPDU, requestID)
# 7.1.3d.1
- if statusInformation.has_key('securityLevel'):
+ if 'securityLevel' in statusInformation:
securityLevel = statusInformation['securityLevel']
else:
securityLevel = 1
# 7.1.3d.2
- if statusInformation.has_key('contextEngineId'):
+ if 'contextEngineId' in statusInformation:
contextEngineId = statusInformation['contextEngineId']
else:
contextEngineId = snmpEngineID
# 7.1.3d.3
- if statusInformation.has_key('contextName'):
+ if 'contextName' in statusInformation:
contextName = statusInformation['contextName']
else:
contextName = ""
@@ -367,7 +370,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
'Unknown securityLevel %s' % securityLevel
)
- if rfc3411.confirmedClassPDUs.has_key(pdu.tagSet): # XXX not needed?
+ if pdu.tagSet in rfc3411.confirmedClassPDUs: # XXX not needed?
msgFlags = msgFlags | 0x04
headerData.setComponentByPosition(2, chr(msgFlags))
@@ -377,8 +380,9 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
debug.logger & debug.flagMP and debug.logger('prepareResponseMessage: %s' % (msg.prettyPrint(),))
- smHandler = snmpEngine.securityModels.get(securityModel)
- if smHandler is None:
+ if securityModel in snmpEngine.securityModels:
+ smHandler = snmpEngine.securityModels[securityModel]
+ else:
raise error.StatusInformation(
errorIndication = errind.unsupportedSecurityModel
)
@@ -445,7 +449,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
debug.logger & debug.flagMP and debug.logger('prepareDataElements: msg data msgVersion %s msgID %s securityModel %s' % (msgVersion, msgID, securityModel))
# 7.2.4
- if not snmpEngine.securityModels.has_key(securityModel):
+ if securityModel not in snmpEngine.securityModels:
snmpUnknownSecurityModels, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpUnknownSecurityModels')
snmpUnknownSecurityModels.syntax = snmpUnknownSecurityModels.syntax + 1
raise error.StatusInformation(
@@ -491,17 +495,17 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
debug.logger & debug.flagMP and debug.logger('prepareDataElements: SM succeeded')
except error.StatusInformation, statusInformation:
debug.logger & debug.flagMP and debug.logger('prepareDataElements: SM failed, statusInformation %s' % statusInformation)
- if statusInformation.has_key('errorIndication'):
+ if 'errorIndication' in statusInformation:
# 7.2.6a
- if statusInformation.has_key('oid'):
+ if 'oid' in statusInformation:
# 7.2.6a1
securityStateReference = statusInformation[
'securityStateReference'
]
contextEngineId = statusInformation['contextEngineId']
contextName = statusInformation['contextName']
- scopedPDU = statusInformation.get('scopedPDU')
- if scopedPDU is not None:
+ if 'scopedPDU' in statusInformation:
+ scopedPDU = statusInformation['scopedPDU']
pdu = scopedPDU.getComponentByPosition(2).getComponent()
else:
pdu = None
@@ -554,7 +558,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
else:
# Sniff for engineIDs
k = (transportDomain, transportAddress)
- if not self.__engineIDs.has_key(k):
+ if k not in self.__engineIDs:
contextEngineId, contextName, pdu = scopedPDU
self.__engineIDs[k] = {
@@ -564,7 +568,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
}
expireAt = self.__expirationTimer + 300
- if not self.__engineIDsExpQueue.has_key(expireAt):
+ if expireAt not in self.__engineIDsExpQueue:
self.__engineIDsExpQueue[expireAt] = []
self.__engineIDsExpQueue[expireAt].append(k)
@@ -584,8 +588,8 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
pduType = pdu.tagSet
# 7.2.10
- if rfc3411.responseClassPDUs.has_key(pduType) or \
- rfc3411.internalClassPDUs.has_key(pduType):
+ if pduType in rfc3411.responseClassPDUs or \
+ pduType in rfc3411.internalClassPDUs:
# 7.2.10a
try:
cachedReqParams = self._cachePopByMsgId(msgID)
@@ -602,7 +606,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
debug.logger & debug.flagMP and debug.logger('prepareDataElements: using sendPduHandle %s for msgID %s' % (sendPduHandle, msgID))
# 7.2.11
- if rfc3411.internalClassPDUs.has_key(pduType):
+ if pduType in rfc3411.internalClassPDUs:
# 7.2.11a
varBinds = pMod.apiPDU.getVarBinds(pdu)
if varBinds:
@@ -629,7 +633,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
statusInformation = None # no errors ahead
# 7.2.12
- if rfc3411.responseClassPDUs.has_key(pduType):
+ if pduType in rfc3411.responseClassPDUs:
# 7.2.12a -> noop
# 7.2.12b
@@ -663,7 +667,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
stateReference )
# 7.2.13
- if rfc3411.confirmedClassPDUs.has_key(pduType):
+ if pduType in rfc3411.confirmedClassPDUs:
# 7.2.13a
if securityEngineID != snmpEngineID:
smHandler.releaseStateInformation(securityStateReference)
@@ -708,7 +712,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
stateReference )
# 7.2.14
- if rfc3411.unconfirmedClassPDUs.has_key(pduType):
+ if pduType in rfc3411.unconfirmedClassPDUs:
# Pass new stateReference to let app browse request details
stateReference = self._newStateReference()
@@ -735,7 +739,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
)
def __expireEnginesInfo(self):
- if self.__engineIDsExpQueue.has_key(self.__expirationTimer):
+ if self.__expirationTimer in self.__engineIDsExpQueue:
for engineKey in self.__engineIDsExpQueue[self.__expirationTimer]:
del self.__engineIDs[engineKey]
debug.logger & debug.flagMP and debug.logger('__expireEnginesInfo: expiring %s' % (engineKey,))
diff --git a/pysnmp/proto/proxy/rfc2576.py b/pysnmp/proto/proxy/rfc2576.py
index bf8fec4..9816c92 100644
--- a/pysnmp/proto/proxy/rfc2576.py
+++ b/pysnmp/proto/proxy/rfc2576.py
@@ -99,7 +99,7 @@ def v1ToV2(v1Pdu, origV2Pdu=None):
v2VarBinds = []
# 3.1
- if rfc3411.notificationClassPDUs.has_key(pduType):
+ if pduType in rfc3411.notificationClassPDUs:
# 3.1.1
sysUpTime = v1.apiTrapPDU.getTimeStamp(v1Pdu)
@@ -138,7 +138,7 @@ def v1ToV2(v1Pdu, origV2Pdu=None):
(oid, __v1ToV2ValueMap[v1Val.tagSet].clone(v1Val))
)
- if rfc3411.responseClassPDUs.has_key(pduType):
+ if pduType in rfc3411.responseClassPDUs:
# 4.1.2.2.1&2
errorStatus = int(v1.apiPDU.getErrorStatus(v1Pdu))
errorIndex = int(v1.apiPDU.getErrorIndex(v1Pdu))
@@ -157,7 +157,7 @@ def v1ToV2(v1Pdu, origV2Pdu=None):
# 4.1.2.1 --> no-op
- if not rfc3411.notificationClassPDUs.has_key(pduType):
+ if pduType not in rfc3411.notificationClassPDUs:
v2c.apiPDU.setRequestID(v2Pdu, long(v1.apiPDU.getRequestID(v1Pdu)))
v2c.apiPDU.setVarBinds(v2Pdu, v2VarBinds)
@@ -171,7 +171,7 @@ def v2ToV1(v2Pdu, origV1Pdu=None):
pduType = v2Pdu.tagSet
- if __v2ToV1PduMap.has_key(pduType):
+ if pduType in __v2ToV1PduMap:
v1Pdu = __v2ToV1PduMap[pduType].clone()
else:
raise error.ProtocolError('Unsupported PDU type')
@@ -179,19 +179,19 @@ def v2ToV1(v2Pdu, origV1Pdu=None):
v2VarBinds = v2c.apiPDU.getVarBinds(v2Pdu)
v1VarBinds = []
- if rfc3411.notificationClassPDUs.has_key(pduType):
+ if pduType in rfc3411.notificationClassPDUs:
v1.apiTrapPDU.setDefaults(v1Pdu)
else:
v1.apiPDU.setDefaults(v1Pdu)
# 3.2
- if rfc3411.notificationClassPDUs.has_key(pduType):
+ if pduType in rfc3411.notificationClassPDUs:
# 3.2.1
(snmpTrapOID, snmpTrapOIDParam) = v2VarBinds[1]
if snmpTrapOID != v2c.apiTrapPDU.snmpTrapOID:
raise error.ProtocolError('Second OID not snmpTrapOID')
- if __v2ToV1TrapMap.has_key(snmpTrapOIDParam):
+ if snmpTrapOIDParam in __v2ToV1TrapMap:
for oid, val in v2VarBinds:
if oid == v2c.apiTrapPDU.snmpTrapEnterprise:
v1.apiTrapPDU.setEnterprise(v1Pdu, val)
@@ -215,13 +215,13 @@ def v2ToV1(v2Pdu, origV1Pdu=None):
v1.apiTrapPDU.setAgentAddr(v1Pdu, v1.apiTrapPDU.agentAddress)
# 3.2.3
- if __v2ToV1TrapMap.has_key(snmpTrapOIDParam):
+ if snmpTrapOIDParam in __v2ToV1TrapMap:
v1.apiTrapPDU.setGenericTrap(v1Pdu, __v2ToV1TrapMap[snmpTrapOIDParam])
else:
v1.apiTrapPDU.setGenericTrap(v1Pdu, 6)
# 3.2.4
- if __v2ToV1TrapMap.has_key(snmpTrapOIDParam):
+ if snmpTrapOIDParam in __v2ToV1TrapMap:
v1.apiTrapPDU.setSpecificTrap(v1Pdu, 0)
else:
v1.apiTrapPDU.setSpecificTrap(v1Pdu, snmpTrapOIDParam[-1])
@@ -231,7 +231,7 @@ def v2ToV1(v2Pdu, origV1Pdu=None):
__v2VarBinds = []
for oid, val in v2VarBinds[2:]:
- if __v2ToV1TrapMap.has_key(oid) or \
+ if oid in __v2ToV1TrapMap or \
oid in (v2c.apiTrapPDU.sysUpTime,
v2c.apiTrapPDU.snmpTrapAddress,
v2c.apiTrapPDU.snmpTrapEnterprise):
@@ -241,7 +241,7 @@ def v2ToV1(v2Pdu, origV1Pdu=None):
# 3.2.6 --> done below
- if rfc3411.responseClassPDUs.has_key(pduType):
+ if pduType in rfc3411.responseClassPDUs:
idx = len(v2VarBinds)-1
while idx >= 0:
# 4.1.2.1
@@ -272,7 +272,7 @@ def v2ToV1(v2Pdu, origV1Pdu=None):
v1.apiPDU.setErrorIndex(v1Pdu, v2c.apiPDU.getErrorIndex(v2Pdu))
# Translate Var-Binds
- if rfc3411.responseClassPDUs.has_key(pduType) and \
+ if pduType in rfc3411.responseClassPDUs and \
v1.apiPDU.getErrorStatus(v1Pdu):
v1VarBinds = v1.apiPDU.getVarBinds(origV1Pdu)
else:
@@ -281,7 +281,7 @@ def v2ToV1(v2Pdu, origV1Pdu=None):
(oid, __v2ToV1ValueMap[v2Val.tagSet].clone(v2Val))
)
- if rfc3411.notificationClassPDUs.has_key(pduType):
+ if pduType in rfc3411.notificationClassPDUs:
v1.apiTrapPDU.setVarBinds(v1Pdu, v1VarBinds)
else:
v1.apiPDU.setVarBinds(v1Pdu, v1VarBinds)
diff --git a/pysnmp/proto/rfc3412.py b/pysnmp/proto/rfc3412.py
index 665e7f3..4f6ca17 100644
--- a/pysnmp/proto/rfc3412.py
+++ b/pysnmp/proto/rfc3412.py
@@ -44,14 +44,15 @@ class MsgAndPduDispatcher:
return index
def __cachePop(self, index):
- cachedParams = self.__cacheRepository.get(index)
- if cachedParams is None:
+ if index in self.__cacheRepository:
+ cachedParams = self.__cacheRepository[index]
+ else:
return
del self.__cacheRepository[index]
return cachedParams
def __cacheUpdate(self, index, **kwargs):
- if not self.__cacheRepository.has_key(index):
+ if index not in self.__cacheRepository:
raise error.ProtocolError(
'Cache miss on update for %s' % kwargs
)
@@ -64,7 +65,7 @@ class MsgAndPduDispatcher:
del self.__cacheRepository[index]
def getTransportInfo(self, stateReference):
- if self.__transportInfo.has_key(stateReference):
+ if stateReference in self.__transportInfo:
return self.__transportInfo[stateReference]
else:
raise error.ProtocolError(
@@ -81,7 +82,7 @@ class MsgAndPduDispatcher:
# 4.3.3
for pduType in pduTypes:
k = (str(contextEngineId), pduType)
- if self.__appsRegistration.has_key(k):
+ if k in self.__appsRegistration:
raise error.ProtocolError(
'Duplicate registration %s/%s' % (contextEngineId, pduType)
)
@@ -100,17 +101,17 @@ class MsgAndPduDispatcher:
for pduType in pduTypes:
k = (str(contextEngineId), pduType)
- if self.__appsRegistration.has_key(k):
+ if k in self.__appsRegistration:
del self.__appsRegistration[k]
debug.logger & debug.flagDsp and debug.logger('unregisterContextEngineId: contextEngineId %s pduTypes %s' % (repr(contextEngineId), pduTypes))
def getRegisteredApp(self, contextEngineId, pduType):
k = ( str(contextEngineId), pduType )
- if self.__appsRegistration.has_key(k):
+ if k in self.__appsRegistration:
return self.__appsRegistration[k]
k = ( '', pduType )
- if self.__appsRegistration.has_key(k):
+ if k in self.__appsRegistration:
return self.__appsRegistration[k] # wildcard
# Dispatcher <-> application API
@@ -134,10 +135,10 @@ class MsgAndPduDispatcher:
):
"""PDU dispatcher -- prepare and serialize a request or notification"""
# 4.1.1.2
- mpHandler = snmpEngine.messageProcessingSubsystems.get(
- int(messageProcessingModel)
- )
- if mpHandler is None:
+ k = int(messageProcessingModel)
+ if k in snmpEngine.messageProcessingSubsystems:
+ mpHandler = snmpEngine.messageProcessingSubsystems[k]
+ else:
raise error.StatusInformation(
errorIndication=errind.unsupportedMsgProcessingModel
)
@@ -223,10 +224,10 @@ class MsgAndPduDispatcher:
):
"""PDU dispatcher -- prepare and serialize a response"""
# Extract input values and initialize defaults
- mpHandler = snmpEngine.messageProcessingSubsystems.get(
- int(messageProcessingModel)
- )
- if mpHandler is None:
+ k = int(messageProcessingModel)
+ if k in snmpEngine.messageProcessingSubsystems:
+ mpHandler = snmpEngine.messageProcessingSubsystems[k]
+ else:
raise error.StatusInformation(
errorIndication=errind.unsupportedMsgProcessingModel
)
@@ -298,11 +299,11 @@ class MsgAndPduDispatcher:
debug.logger & debug.flagDsp and debug.logger('receiveMessage: msgVersion %s, msg decoded' % msgVersion)
messageProcessingModel = msgVersion
-
- mpHandler = snmpEngine.messageProcessingSubsystems.get(
- int(messageProcessingModel)
- )
- if mpHandler is None:
+
+ k = int(messageProcessingModel)
+ if k in snmpEngine.messageProcessingSubsystems:
+ mpHandler = snmpEngine.messageProcessingSubsystems[k]
+ else:
snmpInBadVersions, = self.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpInBadVersions')
snmpInBadVersions.syntax = snmpInBadVersions.syntax + 1
return restOfWholeMsg
@@ -331,7 +332,7 @@ class MsgAndPduDispatcher:
)
debug.logger & debug.flagDsp and debug.logger('receiveMessage: MP succeded')
except error.StatusInformation, statusInformation:
- if statusInformation.has_key('sendPduHandle'):
+ if 'sendPduHandle' in statusInformation:
# Dropped REPORT -- re-run pending reqs queue as some
# of them may be waiting for this REPORT
debug.logger & debug.flagDsp and debug.logger('receiveMessage: MP failed, statusInformation %s' % statusInformation)
@@ -469,10 +470,10 @@ class MsgAndPduDispatcher:
def releaseStateInformation(
self, snmpEngine, sendPduHandle, messageProcessingModel
):
- mpHandler = snmpEngine.messageProcessingSubsystems.get(
- int(messageProcessingModel)
- )
- mpHandler.releaseStateInformation(sendPduHandle)
+ k = int(messageProcessingModel)
+ if k in snmpEngine.messageProcessingSubsystems:
+ mpHandler = snmpEngine.messageProcessingSubsystems[k]
+ mpHandler.releaseStateInformation(sendPduHandle)
# Cache expiration stuff
diff --git a/pysnmp/proto/secmod/base.py b/pysnmp/proto/secmod/base.py
index e68ada3..70ca456 100644
--- a/pysnmp/proto/secmod/base.py
+++ b/pysnmp/proto/secmod/base.py
@@ -63,8 +63,9 @@ class AbstractSecurityModel:
return stateReference
def _cachePop(self, stateReference):
- securityData = self.__cacheEntries.get(stateReference)
- if securityData is None:
+ if stateReference in self.__cacheEntries:
+ securityData = self.__cacheEntries[stateReference]
+ else:
raise error.ProtocolError(
'Cache miss for stateReference=%s at %s' %
(stateReference, self)
diff --git a/pysnmp/proto/secmod/rfc2576.py b/pysnmp/proto/secmod/rfc2576.py
index cf99d40..3eda9e0 100644
--- a/pysnmp/proto/secmod/rfc2576.py
+++ b/pysnmp/proto/secmod/rfc2576.py
@@ -200,7 +200,7 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel):
targetAddrTagList = snmpTargetAddrTagList.getNode(
snmpTargetAddrTagList.name + __instId
).syntax
- if not addrToTagMap.has_key(targetAddr):
+ if targetAddr not in addrToTagMap:
addrToTagMap[targetAddr] = {}
for tag in string.split(str(targetAddrTagList)):
addrToTagMap[targetAddr][tag] = 1
@@ -209,9 +209,9 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel):
# XXX snmpTargetAddrTMask matching not implemented
- if addrToTagMap.has_key(srcTransport):
+ if srcTransport in addrToTagMap:
for tag in string.split(str(mibNode.syntax)):
- if addrToTagMap[srcTransport].has_key(tag):
+ if tag in addrToTagMap[srcTransport]:
debug.logger & debug.flagSM and debug.logger('processIncomingMsg: tag %s matched transport %s' % (tag, srcTransport))
break
else:
diff --git a/pysnmp/proto/secmod/rfc3414/service.py b/pysnmp/proto/secmod/rfc3414/service.py
index 5b3e134..1eda407 100644
--- a/pysnmp/proto/secmod/rfc3414/service.py
+++ b/pysnmp/proto/secmod/rfc3414/service.py
@@ -144,7 +144,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
pysnmpUsmKeyAuthLocalized = pysnmpUsmKeyEntry.getNode(
pysnmpUsmKeyEntry.name + (1,) + tblIdx
)
- if self.authServices.has_key(usmUserAuthProtocol.syntax):
+ if usmUserAuthProtocol.syntax in self.authServices:
localizeKey = self.authServices[usmUserAuthProtocol.syntax].localizeKey
localAuthKey = localizeKey(
pysnmpUsmKeyAuth.syntax,
@@ -159,7 +159,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
pysnmpUsmKeyPrivLocalized = pysnmpUsmKeyEntry.getNode(
pysnmpUsmKeyEntry.name + (2,) + tblIdx
)
- if self.privServices.has_key(usmUserPrivProtocol.syntax):
+ if usmUserPrivProtocol.syntax in self.privServices:
localizeKey = self.privServices[usmUserPrivProtocol.syntax].localizeKey
localPrivKey = localizeKey(
usmUserAuthProtocol.syntax,
@@ -199,14 +199,22 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
# 3.1.1a
cachedSecurityData = self._cachePop(securityStateReference)
usmUserName = cachedSecurityData['msgUserName']
- usmUserAuthProtocol = cachedSecurityData.get('usmUserAuthProtocol')
- usmUserAuthKeyLocalized = cachedSecurityData.get(
- 'usmUserAuthKeyLocalized'
- )
- usmUserPrivProtocol = cachedSecurityData.get('usmUserPrivProtocol')
- usmUserPrivKeyLocalized = cachedSecurityData.get(
- 'usmUserPrivKeyLocalized'
- )
+ if 'usmUserAuthProtocol' in cachedSecurityData:
+ usmUserAuthProtocol = cachedSecurityData['usmUserAuthProtocol']
+ else:
+ usmUserAuthProtocol = None
+ if 'usmUserAuthKeyLocalized' in cachedSecurityData:
+ usmUserAuthKeyLocalized = cachedSecurityData['usmUserAuthKeyLocalized']
+ else:
+ usmUserAuthKeyLocalized = None
+ if 'usmUserPrivProtocol' in cachedSecurityData:
+ usmUserPrivProtocol = cachedSecurityData['usmUserPrivProtocol']
+ else:
+ usmUserPrivProtocol = None
+ if 'usmUserPrivKeyLocalized' in cachedSecurityData:
+ usmUserPrivKeyLocalized = cachedSecurityData['usmUserPrivKeyLocalized']
+ else:
+ usmUserPrivKeyLocalized = None
securityEngineID = snmpEngineID
debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: user info read from cache')
elif securityName:
@@ -277,7 +285,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
if securityStateReference is None and ( # request type check added
securityLevel == 3 or securityLevel == 2
):
- if self.__timeline.has_key(securityEngineID):
+ if securityEngineID in self.__timeline:
( snmpEngineBoots,
snmpEngineTime,
latestReceivedEngineTime,
@@ -305,8 +313,9 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
# 3.1.4a
if securityLevel == 3:
- privHandler = self.privServices.get(usmUserPrivProtocol)
- if privHandler is None:
+ if usmUserPrivProtocol in self.privServices:
+ privHandler = self.privServices[usmUserPrivProtocol]
+ else:
raise error.StatusInformation(
errorIndication = errind.encryptionError
)
@@ -345,8 +354,9 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
# 3.1.8a
if securityLevel == 3 or securityLevel == 2:
- authHandler = self.authServices.get(usmUserAuthProtocol)
- if authHandler is None:
+ if usmUserAuthProtocol in self.authServices:
+ authHandler = self.authServices[usmUserAuthProtocol]
+ else:
raise error.StatusInformation(
errorIndication = errind.authenticationFailure
)
@@ -482,7 +492,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
contextName = ''
# 3.2.3
- if not self.__timeline.has_key(msgAuthoritativeEngineID):
+ if msgAuthoritativeEngineID not in self.__timeline:
debug.logger & debug.flagSM and debug.logger('processIncomingMsg: unknown securityEngineID %s' % repr(msgAuthoritativeEngineID))
if not msgAuthoritativeEngineID:
# 3.2.3b
@@ -615,8 +625,9 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
# 3.2.6
if securityLevel == 3 or securityLevel == 2:
- authHandler = self.authServices.get(usmUserAuthProtocol)
- if authHandler is None:
+ if usmUserAuthProtocol in self.authServices:
+ authHandler = self.authServices[usmUserAuthProtocol]
+ else:
raise error.StatusInformation(
errorIndication = errind.authenticationFailure
)
@@ -652,7 +663,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
)
expireAt = self.__expirationTimer + 300
- if not self.__timelineExpQueue.has_key(expireAt):
+ if expireAt not in self.__timelineExpQueue:
self.__timelineExpQueue[expireAt] = []
self.__timelineExpQueue[expireAt].append(
msgAuthoritativeEngineID
@@ -672,7 +683,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
debug.logger & debug.flagSM and debug.logger('processIncomingMsg: read snmpEngineBoots (%s), snmpEngineTime (%s) from LCD' % (snmpEngineBoots, snmpEngineTime))
else:
# Non-authoritative SNMP engine: use cached estimates
- if self.__timeline.has_key(msgAuthoritativeEngineID):
+ if msgAuthoritativeEngineID in self.__timeline:
( snmpEngineBoots,
snmpEngineTime,
latestReceivedEngineTime,
@@ -719,7 +730,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
int(time.time())
)
expireAt = self.__expirationTimer + 300
- if not self.__timelineExpQueue.has_key(expireAt):
+ if expireAt not in self.__timelineExpQueue:
self.__timelineExpQueue[expireAt] = []
self.__timelineExpQueue[expireAt].append(
msgAuthoritativeEngineID
@@ -739,8 +750,9 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
# 3.2.8a
if securityLevel == 3:
- privHandler = self.privServices.get(usmUserPrivProtocol)
- if privHandler is None:
+ if usmUserPrivProtocol in self.privServices:
+ privHandler = self.privServices[usmUserPrivProtocol]
+ else:
raise error.StatusInformation(
errorIndication = errind.decryptionError
)
@@ -822,9 +834,9 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
securityStateReference )
def __expireTimelineInfo(self):
- if self.__timelineExpQueue.has_key(self.__expirationTimer):
+ if self.__expirationTimer in self.__timelineExpQueue:
for engineIdKey in self.__timelineExpQueue[self.__expirationTimer]:
- if self.__timeline.has_key(engineIdKey):
+ if engineIdKey in self.__timeline:
del self.__timeline[engineIdKey]
debug.logger & debug.flagSM and debug.logger('__expireEnginesInfo: expiring %s' % (engineIdKey,))
del self.__timelineExpQueue[self.__expirationTimer]
diff --git a/pysnmp/smi/builder.py b/pysnmp/smi/builder.py
index f6c2372..ee8a64e 100644
--- a/pysnmp/smi/builder.py
+++ b/pysnmp/smi/builder.py
@@ -107,7 +107,7 @@ class ZipMibSource(__AbstractMibSource):
return tuple(self._uniqNames(l))
def _getTimestamp(self, p):
- if self.__loader._files.has_key(p):
+ if p in self.__loader._files:
return self._parseDosTime(
self.__loader._files[p][6],
self.__loader._files[p][5]
@@ -142,9 +142,9 @@ class MibBuilder:
):
sources.append(ZipMibSource(m).init())
# Compatibility variable
- if os.environ.has_key('PYSNMP_MIB_DIR'):
+ if 'PYSNMP_MIB_DIR' in os.environ:
os.environ['PYSNMP_MIB_DIRS'] = os.environ['PYSNMP_MIB_DIR']
- if os.environ.has_key('PYSNMP_MIB_DIRS'):
+ if 'PYSNMP_MIB_DIRS' in os.environ:
for m in string.split(os.environ['PYSNMP_MIB_DIRS'], ':'):
sources.append(DirMibSource(m).init())
if self.defaultMiscMibs:
@@ -201,7 +201,7 @@ class MibBuilder:
modPath = mibSource.fullPath(modName, sfx)
- if self.__modPathsSeen.has_key(modPath):
+ if modPath in self.__modPathsSeen:
debug.logger & debug.flagBld and debug.logger('loadModules: seen %s' % modPath)
break
else:
@@ -225,7 +225,7 @@ class MibBuilder:
break
- if not self.__modSeen.has_key(modName):
+ if modName not in self.__modSeen:
raise error.SmiError(
'MIB file \"%s\" not found in search path' % (modName and modName + ".py[co]")
)
@@ -236,7 +236,7 @@ class MibBuilder:
if not modNames:
modNames = self.mibSymbols.keys()
for modName in modNames:
- if not self.mibSymbols.has_key(modName):
+ if modName not in self.mibSymbols:
raise error.SmiError(
'No module %s at %s' % (modName, self)
)
@@ -255,13 +255,13 @@ class MibBuilder:
)
r = ()
for symName in symNames:
- if not self.mibSymbols.has_key(modName):
+ if modName not in self.mibSymbols:
self.loadModules(modName)
- if not self.mibSymbols.has_key(modName):
+ if modName not in self.mibSymbols:
raise error.SmiError(
'No module %s loaded at %s' % (modName, self)
)
- if not self.mibSymbols[modName].has_key(symName):
+ if symName not in self.mibSymbols[modName]:
raise error.SmiError(
'No symbol %s::%s at %s' % (modName, symName, self)
)
@@ -269,7 +269,7 @@ class MibBuilder:
return r
def exportSymbols(self, modName, *anonymousSyms, **namedSyms):
- if not self.mibSymbols.has_key(modName):
+ if modName not in self.mibSymbols:
self.mibSymbols[modName] = {}
mibSymbols = self.mibSymbols[modName]
@@ -278,7 +278,7 @@ class MibBuilder:
mibSymbols['__pysnmp_%ld' % self._autoName] = symObj
self._autoName = self._autoName + 1
for symName, symObj in namedSyms.items():
- if mibSymbols.has_key(symName):
+ if symName in mibSymbols:
raise error.SmiError(
'Symbol %s already exported at %s' % (symName, modName)
)
@@ -295,7 +295,7 @@ class MibBuilder:
self.lastBuildId = self.lastBuildId + 1
def unexportSymbols(self, modName, *symNames):
- if not self.mibSymbols.has_key(modName):
+ if modName not in self.mibSymbols:
raise error.SmiError(
'No module %s at %s' % (modName, self)
)
@@ -303,7 +303,7 @@ class MibBuilder:
if not symNames:
symNames = mibSymbols.keys()
for symName in symNames:
- if not mibSymbols.has_key(symName):
+ if symName not in mibSymbols:
raise error.SmiError(
'No symbol %s::%s at %s' % (modName, symName, self)
)
diff --git a/pysnmp/smi/error.py b/pysnmp/smi/error.py
index 79d6910..8a2dc3e 100644
--- a/pysnmp/smi/error.py
+++ b/pysnmp/smi/error.py
@@ -8,7 +8,7 @@ class MibOperationError(SmiError):
self.__class__.__name__, self.__outArgs
)
def __getitem__(self, key): return self.__outArgs[key]
- def has_key(self, key): return self.__outArgs.has_key(key)
+ def __contains__(self, key): return key in self.__outArgs
def get(self, key, defVal=None): return self.__outArgs.get(key, defVal)
def keys(self): return self.__outArgs.keys()
def update(self, d): self.__outArgs.update(d)
diff --git a/pysnmp/smi/indices.py b/pysnmp/smi/indices.py
index 1742e4f..2978d3b 100644
--- a/pysnmp/smi/indices.py
+++ b/pysnmp/smi/indices.py
@@ -3,145 +3,70 @@ from types import DictType, TupleType
from string import join, split, atol
from bisect import bisect
-try:
- from sys import version_info
-except ImportError:
- version_info = ( 0, 0 ) # a really early version
-
-if version_info < (2, 2):
- class OrderedDict:
- def __init__(self, **kwargs):
- self.__dict = {}
- self.__keys = []
- self.__dirty = 1
- if kwargs:
- self.update(kwargs)
- self.__dirty = 1
- def __len__(self): return len(self.__dict)
- def __getitem__(self, key): return self.__dict[key]
- def __setitem__(self, key, value):
- if not self.__dict.has_key(key):
- self.__keys.append(key)
- self.__dict[key] = value
- self.__dirty = 1
- def __repr__(self):
- if self.__dirty: self.__order()
- return repr(self.__dict)
- def __str__(self):
- if self.__dirty: self.__order()
- return str(self.__dict)
- def __delitem__(self, key):
- if self.__dict.has_key(key):
- self.__keys.remove(key)
- del self.__dict[key]
- self.__dirty = 1
- __delattr__ = __delitem__
- def clear(self):
- self.__dict.clear()
- self.__keys = []
- self.__dirty = 1
- def get(self, key, default=None): return self.__dict.get(key, default)
- def has_key(self, key): return self.__dict.has_key(key)
- def keys(self):
- if self.__dirty: self.__order()
- return list(self.__keys)
- def values(self):
- if self.__dirty: self.__order()
- return map(lambda k, d=self.__dict: d[k], self.__keys)
- def items(self):
- if self.__dirty: self.__order()
- return map(lambda k, d=self.__dict: (k, d[k]), self.__keys)
- def update(self, d):
- map(lambda (k, v), self=self: self.__setitem__(k, v), d.items())
- def sortingFun(self, keys): keys.sort()
- def __order(self):
- self.sortingFun(self.__keys)
- d = {}
- for k in self.__keys:
- d[len(k)] = 1
- l = d.keys()
- l.sort(); l.reverse()
- self.__keysLens = tuple(l)
- self.__dirty = 0
- def nextKey(self, key):
- keys = self.keys()
- if self.has_key(key):
- nextIdx = keys.index(key) + 1
- else:
- nextIdx = bisect(keys, key)
- if nextIdx < len(keys):
- return keys[nextIdx]
- else:
- raise KeyError(key)
- def getKeysLens(self):
- if self.__dirty:
- self.__order()
- return self.__keysLens
-else:
- class OrderedDict(DictType):
- def __init__(self, **kwargs):
- self.__keys = []
- self.__dirty = 1
- super(OrderedDict, self).__init__()
- if kwargs:
- self.update(kwargs)
- def __setitem__(self, key, value):
- if not self.has_key(key):
- self.__keys.append(key)
- super(OrderedDict, self).__setitem__(key, value)
- self.__dirty = 1
- def __repr__(self):
- if self.__dirty: self.__order()
- return super(OrderedDict, self).__repr__()
- def __str__(self):
- if self.__dirty: self.__order()
- return super(OrderedDict, self).__str__()
- def __delitem__(self, key):
- if super(OrderedDict, self).has_key(key):
- self.__keys.remove(key)
- super(OrderedDict, self).__delitem__(key)
- self.__dirty = 1
- __delattr__ = __delitem__
- def clear(self):
- super(OrderedDict, self).clear()
- self.__keys = []
- self.__dirty = 1
- def keys(self):
- if self.__dirty: self.__order()
- return list(self.__keys)
- def values(self):
- if self.__dirty: self.__order()
- return map(lambda k, d=self: d[k], self.__keys)
- def items(self):
- if self.__dirty: self.__order()
- return map(lambda k, d=self: (k, d[k]), self.__keys)
- def update(self, d):
- map(lambda (k, v), self=self: self.__setitem__(k, v), d.items())
- def sortingFun(self, keys): keys.sort()
- def __order(self):
- self.sortingFun(self.__keys)
- d = {}
- for k in self.__keys:
- d[len(k)] = 1
- l = d.keys()
- l.sort(); l.reverse()
- self.__keysLens = tuple(l)
- self.__dirty = 0
- def nextKey(self, key):
- keys = self.keys()
- if self.has_key(key):
- nextIdx = keys.index(key) + 1
- else:
- nextIdx = bisect(keys, key)
- if nextIdx < len(keys):
- return keys[nextIdx]
- else:
- raise KeyError(key)
+class OrderedDict(DictType):
+ def __init__(self, **kwargs):
+ self.__keys = []
+ self.__dirty = 1
+ super(OrderedDict, self).__init__()
+ if kwargs:
+ self.update(kwargs)
+ def __setitem__(self, key, value):
+ if key not in self:
+ self.__keys.append(key)
+ super(OrderedDict, self).__setitem__(key, value)
+ self.__dirty = 1
+ def __repr__(self):
+ if self.__dirty: self.__order()
+ return super(OrderedDict, self).__repr__()
+ def __str__(self):
+ if self.__dirty: self.__order()
+ return super(OrderedDict, self).__str__()
+ def __delitem__(self, key):
+ if super(OrderedDict, self).__contains__(key):
+ self.__keys.remove(key)
+ super(OrderedDict, self).__delitem__(key)
+ self.__dirty = 1
+ __delattr__ = __delitem__
+ def clear(self):
+ super(OrderedDict, self).clear()
+ self.__keys = []
+ self.__dirty = 1
+ def keys(self):
+ if self.__dirty: self.__order()
+ return list(self.__keys)
+ def values(self):
+ if self.__dirty: self.__order()
+ return map(lambda k, d=self: d[k], self.__keys)
+ def items(self):
+ if self.__dirty: self.__order()
+ return map(lambda k, d=self: (k, d[k]), self.__keys)
+ def update(self, d):
+ map(lambda (k, v), self=self: self.__setitem__(k, v), d.items())
+ def sortingFun(self, keys): keys.sort()
+ def __order(self):
+ self.sortingFun(self.__keys)
+ d = {}
+ for k in self.__keys:
+ d[len(k)] = 1
+ l = d.keys()
+ l.sort(); l.reverse()
+ self.__keysLens = tuple(l)
+ self.__dirty = 0
+ def nextKey(self, key):
+ keys = self.keys()
+ if key in self:
+ nextIdx = keys.index(key) + 1
+ else:
+ nextIdx = bisect(keys, key)
+ if nextIdx < len(keys):
+ return keys[nextIdx]
+ else:
+ raise KeyError(key)
- def getKeysLens(self):
- if self.__dirty:
- self.__order()
- return self.__keysLens
+ def getKeysLens(self):
+ if self.__dirty:
+ self.__order()
+ return self.__keysLens
class OidOrderedDict(OrderedDict):
def __init__(self, **kwargs):
@@ -149,7 +74,7 @@ class OidOrderedDict(OrderedDict):
apply(OrderedDict.__init__, [self], kwargs)
def __setitem__(self, key, value):
- if not self.__keysCache.has_key(key):
+ if key not in self.__keysCache:
if type(key) == TupleType:
self.__keysCache[key] = key
else:
@@ -159,7 +84,7 @@ class OidOrderedDict(OrderedDict):
OrderedDict.__setitem__(self, key, value)
def __delitem__(self, key):
- if self.__keysCache.has_key(key):
+ if key in self.__keysCache:
del self.__keysCache[key]
OrderedDict.__delitem__(self, key)
__delattr__ = __delitem__
diff --git a/pysnmp/smi/instrum.py b/pysnmp/smi/instrum.py
index 23b95ec..bcb1cd9 100644
--- a/pysnmp/smi/instrum.py
+++ b/pysnmp/smi/instrum.py
@@ -112,11 +112,11 @@ class MibInstrumController:
# Detach items from each other
for symName, parentName in self.lastBuildSyms.items():
- if scalars.has_key(parentName):
+ if parentName in scalars:
scalars[parentName].unregisterSubtrees(symName)
- elif cols.has_key(parentName):
+ elif parentName in cols:
cols[parentName].unregisterSubtrees(symName)
- elif rows.has_key(parentName):
+ elif parentName in rows:
rows[parentName].unregisterSubtrees(symName)
else:
mibTree.unregisterSubtrees(symName)
@@ -125,9 +125,9 @@ class MibInstrumController:
# Attach Managed Objects Instances to Managed Objects
for inst in instances.values():
- if scalars.has_key(inst.typeName):
+ if inst.typeName in scalars:
scalars[inst.typeName].registerSubtrees(inst)
- elif cols.has_key(inst.typeName):
+ elif inst.typeName in cols:
cols[inst.typeName].registerSubtrees(inst)
else:
raise error.SmiError(
@@ -138,7 +138,7 @@ class MibInstrumController:
# Attach Table Columns to Table Rows
for col in cols.values():
rowName = col.name[:-1] # XXX
- if rows.has_key(rowName):
+ if rowName in rows:
rows[rowName].registerSubtrees(col)
else:
raise error.SmiError(
@@ -177,10 +177,14 @@ class MibInstrumController:
state, status = 'start', 'ok'
myErr = None
while 1:
- fsmState = fsmTable.get((state, status))
- if fsmState is None:
- fsmState = fsmTable.get(('*', status))
- if fsmState is None:
+ k = (state, status)
+ if k in fsmTable:
+ fsmState = fsmTable[k]
+ else:
+ k = ('*', status)
+ if k in fsmTable:
+ fsmState = fsmTable[k]
+ else:
raise error.SmiError(
'Unresolved FSM state %s, %s' % (state, status)
)
diff --git a/pysnmp/smi/mibs/SNMPv2-SMI.py b/pysnmp/smi/mibs/SNMPv2-SMI.py
index 38b9606..0573401 100644
--- a/pysnmp/smi/mibs/SNMPv2-SMI.py
+++ b/pysnmp/smi/mibs/SNMPv2-SMI.py
@@ -229,7 +229,7 @@ class MibTree(ObjectType):
"""Register subtrees at this tree. Subtrees are always attached
at the level of this tree, not subtrees."""
for subTree in subTrees:
- if self._vars.has_key(subTree.name):
+ if subTree.name in self._vars:
raise error.SmiError(
'MIB subtree %s already registered at %s' % (subTree.name, self)
)
@@ -241,7 +241,7 @@ class MibTree(ObjectType):
for name in names:
# This may fail if you fill a table by exporting MibScalarInstances
# but later drop them through SNMP.
- if not self._vars.has_key(name):
+ if name not in self._vars:
raise error.SmiError(
'MIB subtree %s not registered at %s' % (name, self)
)
@@ -256,7 +256,7 @@ class MibTree(ObjectType):
if len(self.name) < len(name):
for keyLen in self._vars.getKeysLens():
subName = name[:keyLen]
- if self._vars.has_key(subName):
+ if subName in self._vars:
return self._vars[subName]
raise error.NoSuchObjectError(name=name, idx=idx)
@@ -521,7 +521,7 @@ class MibTableColumn(MibScalar):
# No branches here, terminal OIDs only
def getBranch(self, name, idx):
if len(self.name) < len(name):
- if self._vars.has_key(name):
+ if name in self._vars:
return self._vars[name]
raise error.NoSuchObjectError(name=name, idx=idx)
@@ -551,7 +551,7 @@ class MibTableColumn(MibScalar):
node = self.getNextNode(node.name)
except error.NoSuchInstanceError:
break
- if not self.__valIdx.has_key(node.syntax):
+ if node.syntax not in self.__valIdx:
self.__valIdx[node.syntax] = OidOrderedDict()
self.__valIdx[node.syntax][node.name] = 1
@@ -560,7 +560,7 @@ class MibTableColumn(MibScalar):
# Sync to tree version
self.__valIdxId = self.branchVersionId
- if self.__valIdx.has_key(value):
+ if value in self.__valIdx:
try:
return self.getNode(
self.__valIdx[value].nextKey(name)
@@ -587,7 +587,7 @@ class MibTableColumn(MibScalar):
raise error.NoCreationError(idx=idx, name=name)
# Create instances if either it does not yet exist (row creation)
# or a value is passed (multiple OIDs in SET PDU)
- if val is None and self.__createdInstances.has_key(name):
+ if val is None and name in self.__createdInstances:
return
self.__createdInstances[name] = self.protoInstance(
self.name, name[len(self.name):], self.syntax.clone()
@@ -598,8 +598,8 @@ class MibTableColumn(MibScalar):
def createCommit(self, name, val, idx, (acFun, acCtx)):
# Commit new instance value
- if self._vars.has_key(name): # XXX
- if self.__createdInstances.has_key(name):
+ if name in self._vars: # XXX
+ if name in self.__createdInstances:
self._vars[name].createCommit(name, val, idx, (acFun, acCtx))
return
self.__createdInstances[name].createCommit(
@@ -614,18 +614,18 @@ class MibTableColumn(MibScalar):
self.__valIdx.clear()
# Drop previous column instance
- if self.__createdInstances.has_key(name):
+ if name in self.__createdInstances:
if self.__createdInstances[name] is not None:
self.__createdInstances[name].createCleanup(
name, val, idx, (acFun, acCtx)
)
del self.__createdInstances[name]
- elif self._vars.has_key(name):
+ elif name in self._vars:
self._vars[name].createCleanup(name, val, idx, (acFun, acCtx))
def createUndo(self, name, val, idx, (acFun, acCtx)):
# Set back previous column instance, drop the new one
- if self.__createdInstances.has_key(name):
+ if name in self.__createdInstances:
self._vars[name] = self.__createdInstances[name]
del self.__createdInstances[name]
# Remove new instance on rollback
@@ -646,7 +646,7 @@ class MibTableColumn(MibScalar):
# Make sure destruction is allowed
if name == self.name:
raise error.NoAccessError(idx=idx, name=name)
- if not self._vars.has_key(name):
+ if name not in self._vars:
return
if acFun and \
val is not None and \
@@ -659,7 +659,7 @@ class MibTableColumn(MibScalar):
def destroyCommit(self, name, val, idx, (acFun, acCtx)):
# Make a copy of column instance and take it off the tree
- if self._vars.has_key(name):
+ if name in self._vars:
self._vars[name].destroyCommit(
name, val, idx, (acFun, acCtx)
)
@@ -671,7 +671,7 @@ class MibTableColumn(MibScalar):
self.__valIdx.clear()
# Drop instance copy
- if self.__destroyedInstances.has_key(name):
+ if name in self.__destroyedInstances:
self.__destroyedInstances[name].destroyCleanup(
name, val, idx, (acFun, acCtx)
)
@@ -680,7 +680,7 @@ class MibTableColumn(MibScalar):
def destroyUndo(self, name, val, idx, (acFun, acCtx)):
# Set back column instance
- if self.__destroyedInstances.has_key(name):
+ if name in self.__destroyedInstances:
self._vars[name] = self.__destroyedInstances[name]
self._vars[name].destroyUndo(
name, val, idx, (acFun, acCtx)
@@ -703,12 +703,12 @@ class MibTableColumn(MibScalar):
except error.RowDestructionWanted:
self.__rowOpWanted[name] = error.RowDestructionWanted()
self.destroyTest(name, val, idx, (acFun, acCtx))
- if self.__rowOpWanted.has_key(name):
+ if name in self.__rowOpWanted:
debug.logger & debug.flagIns and debug.logger('%s flagged by %s=%s' % (self.__rowOpWanted[name], name, repr(val)))
raise self.__rowOpWanted[name]
def __delegateWrite(self, subAction, name, val, idx, (acFun, acCtx)):
- if not self.__rowOpWanted.has_key(name):
+ if name not in self.__rowOpWanted:
getattr(MibScalar, 'write'+subAction)(
self, name, val, idx, (acFun, acCtx)
)
@@ -726,7 +726,7 @@ class MibTableColumn(MibScalar):
self.__delegateWrite(
'Commit', name, val, idx, (acFun, acCtx)
)
- if self.__rowOpWanted.has_key(name):
+ if name in self.__rowOpWanted:
raise self.__rowOpWanted[name]
def writeCleanup(self, name, val, idx, (acFun, acCtx)):
@@ -736,7 +736,7 @@ class MibTableColumn(MibScalar):
self.__delegateWrite(
'Cleanup', name, val, idx, (acFun, acCtx)
)
- if self.__rowOpWanted.has_key(name):
+ if name in self.__rowOpWanted:
e = self.__rowOpWanted[name]
del self.__rowOpWanted[name]
debug.logger & debug.flagIns and debug.logger('%s dropped by %s=%s' % (e, name, repr(val)))
@@ -746,7 +746,7 @@ class MibTableColumn(MibScalar):
self.__delegateWrite(
'Undo', name, val, idx, (acFun, acCtx)
)
- if self.__rowOpWanted.has_key(name):
+ if name in self.__rowOpWanted:
e = self.__rowOpWanted[name]
del self.__rowOpWanted[name]
debug.logger & debug.flagIns and debug.logger('%s dropped by %s=%s' % (e, name, repr(val)))
@@ -889,7 +889,7 @@ class MibTableRow(MibTree):
def registerAugmentions(self, *names):
for modName, symName in names:
- if self.augmentingRows.has_key((modName, symName)):
+ if (modName, symName) in self.augmentingRows:
raise error.SmiError(
'Row %s already augmented by %s::%s' % \
(self.name, modName, symName)
@@ -918,13 +918,13 @@ class MibTableRow(MibTree):
for name, var in self._vars.items():
if name == excludeName:
continue
- if indexVals.has_key(name):
+ if name in indexVals:
getattr(var, action)(name + nameSuffix, indexVals[name], idx,
(None, None))
else:
getattr(var, action)(name + nameSuffix, val, idx,
(acFun, acCtx))
- debug.logger & debug.flagIns and debug.logger('__manageColumns: action %s name %s suffix %s %svalue %s' % (action, name, nameSuffix, indexVals.has_key(name) and "index " or "", repr(indexVals.get(name, val))))
+ debug.logger & debug.flagIns and debug.logger('__manageColumns: action %s name %s suffix %s %svalue %s' % (action, name, nameSuffix, name in indexVals and "index " or "", repr(indexVals.get(name, val))))
def __delegate(self, subAction, name, val, idx, (acFun, acCtx)):
# Relay operation request to column, expect row operation request.
diff --git a/pysnmp/smi/mibs/instances/__SNMPv2-MIB.py b/pysnmp/smi/mibs/instances/__SNMPv2-MIB.py
index 5a66437..66326c5 100644
--- a/pysnmp/smi/mibs/instances/__SNMPv2-MIB.py
+++ b/pysnmp/smi/mibs/instances/__SNMPv2-MIB.py
@@ -96,7 +96,7 @@ __sysObjectID = MibScalarInstance(sysObjectID.name, (0,), sysObjectID.syntax.clo
class SysUpTime(TimeTicks):
createdAt = time()
def clone(self, **kwargs):
- if kwargs.get('value') is None:
+ if 'value' not in kwargs:
kwargs['value'] = int((time()-self.createdAt)*100)
return apply(TimeTicks.clone, [self], kwargs)
diff --git a/pysnmp/smi/view.py b/pysnmp/smi/view.py
index ff89232..fcdd716 100644
--- a/pysnmp/smi/view.py
+++ b/pysnmp/smi/view.py
@@ -35,8 +35,14 @@ class MibViewController:
# This is potentionally ambiguous mapping. Sort modules in
# ascending age for resolution
def __sortFun(x, y, s=self.mibBuilder.mibSymbols):
- m1 = s[x].get("PYSNMP_MODULE_ID")
- m2 = s[y].get("PYSNMP_MODULE_ID")
+ if "PYSNMP_MODULE_ID" in s[x]:
+ m1 = s[x]["PYSNMP_MODULE_ID"]
+ else:
+ m1 = None
+ if "PYSNMP_MODULE_ID" in s[y]:
+ m2 = s[y]["PYSNMP_MODULE_ID"]
+ else:
+ m2 = None
r1 = r2 = "1970-01-01 00:00"
if m1:
r = m1.getRevisions()
@@ -69,7 +75,7 @@ class MibViewController:
if n == "PYSNMP_MODULE_ID": # do not index this special symbol
continue
if type(v) == ClassType:
- if mibMod['typeToModIdx'].has_key(n):
+ if n in mibMod['typeToModIdx']:
raise error.SmiError(
'Duplicate SMI type %s::%s, has %s' % \
(modName, n, mibMod['typeToModIdx'][n])
@@ -79,7 +85,7 @@ class MibViewController:
elif type(v) == InstanceType:
if isinstance(v, MibScalarInstance):
continue
- if mibMod['varToNameIdx'].has_key(n):
+ if n in mibMod['varToNameIdx']:
raise error.SmiError(
'Duplicate MIB variable %s::%s has %s' % \
(modName, n, mibMod['varToNameIdx'][n])
@@ -114,8 +120,9 @@ class MibViewController:
keyLen = len(key)
i = keyLen-1
while i:
- baseLabel = oidToLabelIdx.get(key[:i])
- if baseLabel:
+ k = key[:i]
+ if k in oidToLabelIdx:
+ baseLabel = oidToLabelIdx[k]
if i != keyLen-1:
baseLabel = baseLabel + key[i:-1]
break
@@ -158,12 +165,10 @@ class MibViewController:
"""getOidLabel(nodeName) -> (oid, label, suffix)"""
if not nodeName:
return nodeName, nodeName, ()
- oid = labelToOidIdx.get(nodeName)
- if oid:
- return oid, nodeName, ()
- label = oidToLabelIdx.get(nodeName)
- if label:
- return nodeName, label, ()
+ if nodeName in labelToOidIdx:
+ return labelToOidIdx[nodeName], nodeName, ()
+ if nodeName in oidToLabelIdx:
+ return nodeName, oidToLabelIdx[nodeName], ()
if len(nodeName) < 2:
return nodeName, nodeName, ()
oid, label, suffix = self.__getOidLabel(
@@ -171,19 +176,18 @@ class MibViewController:
)
suffix = suffix + nodeName[-1:]
resLabel = label + suffix
- resOid = labelToOidIdx.get(resLabel)
- if resOid:
- return resOid, resLabel, ()
+ if resLabel in labelToOidIdx:
+ return labelToOidIdx[resLabel], resLabel, ()
resOid = oid + suffix
- resLabel = oidToLabelIdx.get(resOid)
- if resLabel:
- return resOid, resLabel, ()
+ if resOid in oidToLabelIdx:
+ return resOid, oidToLabelIdx[resOid], ()
return oid, label, suffix
def getNodeNameByOid(self, nodeName, modName=''):
self.indexMib()
- mibMod = self.__mibSymbolsIdx.get(modName)
- if mibMod is None:
+ if modName in self.__mibSymbolsIdx:
+ mibMod = self.__mibSymbolsIdx[modName]
+ else:
raise error.SmiError(
'No module %s at %s' % (modName, self)
)
@@ -199,14 +203,16 @@ class MibViewController:
return oid, label, suffix
def getNodeNameByDesc(self, nodeName, modName=''):
- self.indexMib()
- mibMod = self.__mibSymbolsIdx.get(modName)
- if mibMod is None:
+ self.indexMib()
+ if modName in self.__mibSymbolsIdx:
+ mibMod = self.__mibSymbolsIdx[modName]
+ else:
raise error.SmiError(
'No module %s at %s' % (modName, self)
)
- oid = mibMod['varToNameIdx'].get(nodeName)
- if oid is None:
+ if nodeName in mibMod['varToNameIdx']:
+ oid = mibMod['varToNameIdx'][nodeName]
+ else:
raise error.NoSuchObjectError(
str='No such symbol %s::%s at %s' % (modName, nodeName, self)
)
@@ -230,9 +236,10 @@ class MibViewController:
)
def getFirstNodeName(self, modName=''):
- self.indexMib()
- mibMod = self.__mibSymbolsIdx.get(modName)
- if mibMod is None:
+ self.indexMib()
+ if modName in self.__mibSymbolsIdx:
+ mibMod = self.__mibSymbolsIdx[modName]
+ else:
raise error.SmiError(
'No module %s at %s' % (modName, self)
)
@@ -271,13 +278,15 @@ class MibViewController:
def getTypeName(self, typeName, modName=''):
self.indexMib()
- mibMod = self.__mibSymbolsIdx.get(modName)
- if mibMod is None:
+ if modName in self.__mibSymbolsIdx:
+ mibMod = self.__mibSymbolsIdx[modName]
+ else:
raise error.SmiError(
'No module %s at %s' % (modName, self)
)
- m = mibMod['typeToModIdx'].get(typeName)
- if m is None:
+ if typeName in mibMod['typeToModIdx']:
+ m = mibMod['typeToModIdx'][typeName]
+ else:
raise error.NoSuchObjectError(
str='No such type %s::%s at %s' % (modName, typeName, self)
)
@@ -285,8 +294,9 @@ class MibViewController:
def getFirstTypeName(self, modName=''):
self.indexMib()
- mibMod = self.__mibSymbolsIdx.get(modName)
- if mibMod is None:
+ if modName in self.__mibSymbolsIdx:
+ mibMod = self.__mibSymbolsIdx[modName]
+ else:
raise error.SmiError(
'No module %s at %s' % (modName, self)
)