[Git][NTPsec/ntpsec][master] PEP8: fix boolean comparisons

Matt Selsky gitlab at mg.gitlab.com
Mon Feb 4 08:08:45 UTC 2019


Matt Selsky pushed to branch master at NTPsec / ntpsec


Commits:
522a4ece by Matt Selsky at 2019-02-04T08:02:54Z
PEP8: fix boolean comparisons

Don't compare boolean values to True or False using "==" or "is".

- - - - -


10 changed files:

- ntpclients/ntpdig.py
- ntpclients/ntpmon.py
- ntpclients/ntpsnmpd.py
- ntpclients/ntpviz.py
- pylib/agentx.py
- pylib/agentx_packet.py
- pylib/packet.py
- pylib/util.py
- tests/pylib/jigs.py
- tests/pylib/test_packet.py


Changes:

=====================================
ntpclients/ntpdig.py
=====================================
@@ -402,7 +402,7 @@ if __name__ == '__main__':
             for s in range(samples):
                 if needgap and not firstloop:
                     time.sleep(gap)
-                if firstloop is True:
+                if firstloop:
                     firstloop = False
                 for server in concurrent_hosts:
                     try:


=====================================
ntpclients/ntpmon.py
=====================================
@@ -173,7 +173,7 @@ class Fatal(Exception):
 class OutputContext:
     def __enter__(self):
         "Begin critical region."
-        if (sys.version_info[0] < 3) and (disableunicode is False):
+        if sys.version_info[0] < 3 and not disableunicode:
             # This appears to only be needed under python 2, it is only
             # activated when we already have UTF-8. Otherwise we drop
             # down to non-unicode versions.


=====================================
ntpclients/ntpsnmpd.py
=====================================
@@ -543,7 +543,7 @@ class DataSource(ntp.agentx.MIBControl):
                 ipv6 = None
             # Convert address string to octets
             srcadr = []
-            if ipv6 is False:
+            if not ipv6:
                 pieces = addr.split(".")
                 for piece in pieces:
                     try:
@@ -553,7 +553,7 @@ class DataSource(ntp.agentx.MIBControl):
                         # Still try to return data because it is potential
                         # debugging information.
                         continue
-            elif ipv6 is True:
+            elif ipv6:
                 pieces = addr.split(":")
                 for piece in pieces:
                     srcadr.append(ntp.util.hexstr2octets(piece))
@@ -630,32 +630,31 @@ class DataSource(ntp.agentx.MIBControl):
             return
         self.lastNotifyCheck = currentTime
 
-        if self.notifyModeChange is True:
+        if self.notifyModeChange:
             self.doNotifyModeChange(control)
 
-        if self.notifyStratumChange is True:
+        if self.notifyStratumChange:
             self.doNotifyStratumChange(control)
 
-        if self.notifySyspeerChange is True:
+        if self.notifySyspeerChange:
             self.doNotifySyspeerChange(control)
 
         # Both add and remove have to look at the same data, don't want them
         # stepping on each other. Therefore the functions are combined.
-        if (self.notifyAddAssociation is True) and \
-           (self.notifyRMAssociation is True):
+        if self.notifyAddAssociation and self.notifyRMAssociation:
             self.doNotifyChangeAssociation(control, "both")
-        elif self.notifyAddAssociation is True:
+        elif self.notifyAddAssociation:
             self.doNotifyChangeAssociation(control, "add")
-        elif self.notifyRMAssociation is True:
+        elif self.notifyRMAssociation:
             self.doNotifyChangeAssociation(control, "rm")
 
-        if self.notifyConfigChange is True:
+        if self.notifyConfigChange:
             self.doNotifyConfigChange(control)
 
-        if self.notifyLeapSecondAnnounced is True:
+        if self.notifyLeapSecondAnnounced:
             self.doNotifyLeapSecondAnnounced(control)
 
-        if self.notifyHeartbeat is True:
+        if self.notifyHeartbeat:
             self.doNotifyHeartbeat(control)
 
     def doNotifyModeChange(self, control):
@@ -947,7 +946,7 @@ class DataSource(ntp.agentx.MIBControl):
             return None
 
     def dynamicCallbackPeerdata(self, variable, raw, valueType):
-        rawindex = 1 if raw is True else 0
+        rawindex = 1 if raw else 0
 
         def handler(oid, associd):
             pdata = self.misc_getPeerData()
@@ -1032,7 +1031,7 @@ def mainloop(snmpSocket, reconnectionAddr, host=None):
         control = PacketControl(snmpSocket, dbase, logfp=logfp, debug=debug)
         control.loopCallback = dbase.checkNotifications
         control.initNewSession()
-        if control.mainloop(True) is False:  # disconnected
+        if not control.mainloop(True):  # disconnected
             snmpSocket.close()
             snmpSocket = connect(reconnectionAddr)
             log("disconnected from master, attempting reconnect", 2)
@@ -1073,7 +1072,7 @@ def daemonize(runfunc, *runArgs):
 
 def loadSettings(filename, optionList):
     log("Loading config file: %s" % filename, 3)
-    if os.path.isfile(filename) is False:
+    if not os.path.isfile(filename):
         return None
     options = {}
     with open(filename) as f:
@@ -1088,7 +1087,7 @@ def loadSettings(filename, optionList):
 
 def storeSettings(filename, settings):
     dirname = os.path.dirname(filename)
-    if os.path.exists(dirname) is False:
+    if not os.path.exists(dirname):
         os.makedirs(dirname)
     data = []
     for key in settings.keys():
@@ -1189,10 +1188,10 @@ if __name__ == "__main__":
             logfile = val
             fileLogging = True
 
-    if nofork is False:
+    if not nofork:
         fileLogging = True
 
-    if fileLogging is True:
+    if fileLogging:
         if logfp != sys.stderr:
             logfp.close()
         logfp = open(logfile, "a", 1)  # 1 => line buffered
@@ -1202,7 +1201,7 @@ if __name__ == "__main__":
     # Connect here so it can always report a connection error
     sock = connect(masterAddr)
 
-    if nofork is True:
+    if nofork:
         mainloop(sock, hostname)
     else:
         daemonize(mainloop, sock, hostname)


=====================================
ntpclients/ntpviz.py
=====================================
@@ -1524,14 +1524,14 @@ Python by ESR, concept and gnuplot code by Dan Drown.
     args.statsdirs = [os.path.expanduser(path)
                       for path in args.statsdirs.split(",")]
 
-    if args.show_peer_offsets is True:
+    if args.show_peer_offsets:
         args.show_peer_offsets = []
     elif args.peer_offsets:
         args.show_peer_offsets = args.peer_offsets.split(",")
     else:
         args.show_peer_offsets = None
 
-    if args.show_peer_jitters is True:
+    if args.show_peer_jitters:
         args.show_peer_jitters = []
     elif args.peer_jitters:
         args.show_peer_jitters = args.peer_jitters.split(",")


=====================================
pylib/agentx.py
=====================================
@@ -86,7 +86,7 @@ class MIBControl:
         while True:
             try:
                 oid, reader, writer = gen_next(gen)
-                if nextP is True:  # GetNext
+                if nextP:  # GetNext
                     # For getnext any OID greater than the start qualifies
                     oidhit = (oid > searchoid)
                 else:  # Get
@@ -95,12 +95,12 @@ class MIBControl:
                 if oidhit and (reader is not None):
                     # We only return OIDs that have a minimal implementation
                     # walkMIBTree handles the generation of dynamic trees
-                    if returnGenerator is True:
+                    if returnGenerator:
                         return oid, reader, writer, gen
                     else:
                         return oid, reader, writer
             except StopIteration:  # Couldn't find anything in the tree
-                if returnGenerator is True:
+                if returnGenerator:
                     return None, None, None, None
                 else:
                     return None, None, None
@@ -126,15 +126,14 @@ class MIBControl:
                     continue  # skip unimplemented OIDs
                 elif oid.subids == oidrange.start.subids:
                     # ok, found the start, do we need to skip it?
-                    if oidrange.start.include is True:
+                    if oidrange.start.include:
                         oids.append((oid, reader, writer))
                         break
                     else:
                         continue
                 elif oid > oidrange.start:
                     # If we are here it means we hit the start but skipped
-                    if (oidrange.end.isNull() is False) and \
-                       (oid >= oidrange.end):
+                    if not oidrange.end.isNull() and oid >= oidrange.end:
                         # We fell off the range
                         return []
                     oids.append((oid, reader, writer))
@@ -142,7 +141,7 @@ class MIBControl:
             except StopIteration:
                 # Couldn't find *anything*
                 return []
-        if firstOnly is True:
+        if firstOnly:
             return oids
         # Start filling in the rest of the range
         while True:
@@ -150,8 +149,7 @@ class MIBControl:
                 oid, reader, writer = gen_next(gen)
                 if reader is None:
                     continue  # skip unimplemented OIDs
-                elif (oidrange.end.isNull() is False) and \
-                     (oid >= oidrange.end):
+                elif not oidrange.end.isNull() and oid >= oidrange.end:
                     break  # past the end of a bounded range
                 else:
                     oids.append((oid, reader, writer))
@@ -194,7 +192,7 @@ class PacketControl:
         if self.stillConnected is not True:
             return False
         if runforever:
-            while self.stillConnected is True:
+            while self.stillConnected:
                 self._doloop()
                 if self.loopCallback is not None:
                     self.loopCallback(self)
@@ -258,9 +256,9 @@ class PacketControl:
                     continue
                 haveit = (opkt.transactionID == packet.transactionID) and \
                          (opkt.packetID == packet.packetID)
-                if ignoreSID is False:
+                if not ignoreSID:
                     haveit = haveit and (opkt.sessionID == packet.sessionID)
-                if haveit is True:
+                if haveit:
                     self.log("Received waited for response", 4)
                     return packet
             time.sleep(self.spinGap)
@@ -284,7 +282,7 @@ class PacketControl:
                 return None  # We don't even have a packet header, bail
             try:
                 pkt, fullPkt, extraData = ax.decode_packet(self.receivedData)
-                if fullPkt is False:
+                if not fullPkt:
                     return None
                 self.receivedData = extraData
                 self.receivedPackets.append(pkt)
@@ -308,7 +306,7 @@ class PacketControl:
         self.log("Sending packet (with reply: %s): %s" % (expectsReply,
                                                           repr(packet)), 4)
         self.socket.sendall(encoded)
-        if expectsReply is True:
+        if expectsReply:
             index = (packet.sessionID,
                      packet.transactionID,
                      packet.packetID)
@@ -445,9 +443,9 @@ class PacketControl:
         # Be advised: MOST OF THE VALIDATION IS DUMMY CODE OR DOESN'T EXIST
         # According to the RFC this is one of the most demanding parts and
         #  *has* to be gotten right
-        if self.database.inSetP is True:
+        if self.database.inSetP:
             pass  # Is this an error?
-        # if (inSetP is True) is an error these will go in an else block
+        # if (inSetP) is an error these will go in an else block
         self.database.inSetP = True
         self.database.setVarbinds = []
         self.database.setHandlers = []
@@ -488,7 +486,7 @@ class PacketControl:
             self.sendPacket(resp, False)
 
     def handle_CommitSetPDU(self, packet):
-        if self.database.inSetP is False:
+        if not self.database.inSetP:
             pass  # how to handle this?
         varbinds = self.database.setVarbinds
         handlers = self.database.setHandlers
@@ -569,7 +567,7 @@ def walkMIBTree(tree, rootpath=()):
             # Push current node, move down a level
             nodeStack.append((current, currentKeys, keyID, key))
             oidStack.append(key)
-            if isinstance(subs, dict) is True:
+            if isinstance(subs, dict):
                 current = subs
             else:
                 current = subs()  # Tree generator function


=====================================
pylib/agentx_packet.py
=====================================
@@ -98,7 +98,7 @@ class AgentXPDU:
                 # *might* have to rethink this if contents get classified
                 continue
             pktvars[vname] = var
-        if self._hascontext is True:
+        if self._hascontext:
             # context is always present, not always used
             pktvars["context"] = self.context
         return pktvars
@@ -130,7 +130,7 @@ class AgentXPDU:
             return False
         if self._hascontext != other._hascontext:
             return False
-        if self._hascontext is True:
+        if self._hascontext:
             if self.context != other.context:
                 return False
         return True
@@ -766,7 +766,7 @@ class OID:
         self.sanity()
 
     def __eq__(self, other):
-        if isinstance(other, OID) is False:
+        if not isinstance(other, OID):
             return False
         if not (self.subids == other.subids):
             return False
@@ -810,10 +810,10 @@ class OID:
             else:
                 # this is the Py3 version of c = cmp(x[i], y[i])
                 c = (x[i] > y[i]) - (x[i] < y[i])
-                c = -c if flipped is True else c
+                c = -c if flipped else c
                 return c
         # Only reach this if shorter, and each index is equal
-        if flipped is True:
+        if flipped:
             return 1
         else:
             return -1
@@ -828,7 +828,7 @@ class OID:
             raise ValueError
 
     def isNull(self):
-        if not self.subids and self.include is False:
+        if not self.subids and not self.include:
             return True
         return False
 
@@ -1076,7 +1076,7 @@ class SearchRange:
     def sanity(self):
         self.start.sanity()
         self.end.sanity()
-        if self.end.include is True:
+        if self.end.include:
             raise ValueError
 
     def encode(self, bigEndian):
@@ -1151,7 +1151,7 @@ def makeflags(iR, nI, aI, cP, bE):
 
 
 def getendian(bigEndian):
-    return ">" if bigEndian is True else "<"
+    return ">" if bigEndian else "<"
 
 
 def encode_pduheader(pduType, instanceRegistration, newIndex,
@@ -1205,7 +1205,7 @@ def encode_context(bigEndian, context):
 
 def decode_context(data, header):
     flags = header["flags"]
-    if flags["contextP"] is True:
+    if flags["contextP"]:
         context, data = decode_octetstr(data, header)
     else:
         context = None


=====================================
pylib/packet.py
=====================================
@@ -993,7 +993,7 @@ class ControlSession:
 
             # Validate that packet header is sane, and the correct type
             valid = self.__validate_packet(rpkt, rawdata, opcode, associd)
-            if valid is False:  # pragma: no cover
+            if not valid:  # pragma: no cover
                 continue
 
             # Someday, perhaps, check authentication here
@@ -1195,7 +1195,7 @@ class ControlSession:
             if c == '"':
                 response += c
                 instring = not instring
-            elif (instring is False) and (c == ","):
+            elif not instring and c == ",":
                 # Separator between key=value pairs, done with this pair
                 kvpairs.append(response.strip())
                 response = ""
@@ -1219,7 +1219,7 @@ class ControlSession:
                 except ValueError:
                     try:
                         castedvalue = float(value)
-                        if (key == "delay") and (raw is False):
+                        if key == "delay" and not raw:
                             # Hack for non-raw-mode to get precision
                             items.append(("delay-s", value))
                     except ValueError:
@@ -1228,7 +1228,7 @@ class ControlSession:
                         castedvalue = value  # str / unknown, stillneed casted
             else:  # no value
                 castedvalue = value
-            if raw is True:
+            if raw:
                 items.append((key, (castedvalue, value)))
             else:
                 items.append((key, castedvalue))


=====================================
pylib/util.py
=====================================
@@ -169,7 +169,7 @@ def parseConf(text):
 
     def pushToken():
         token = "".join(current)
-        if inQuote is False:  # Attempt type conversion
+        if not inQuote:  # Attempt type conversion
             try:
                 token = int(token)
             except ValueError:
@@ -191,7 +191,7 @@ def parseConf(text):
     i = 0
     tlen = len(text)
     while i < tlen:
-        if inQuote is True:
+        if inQuote:
             if text[i] == quoteStarter:  # Ending a text string
                 pushToken()
                 quoteStarter = ""
@@ -320,7 +320,7 @@ def gluenumberstring(above, below, isnegative):
         newvalue = ".".join((above, below))
     else:
         newvalue = above
-    if isnegative is True:
+    if isnegative:
         newvalue = "-" + newvalue
     return newvalue
 
@@ -507,7 +507,7 @@ def unitify(value, startingunit, baseunit=None, width=8, unitSpace=False):
         newvalue = cropprecision(value, ooms)
         newvalue, unitsmoved = scalestring(newvalue)
     unitget = unitrelativeto(startingunit, unitsmoved)
-    if unitSpace is True:
+    if unitSpace:
         spaceWidthAdjustment = 1
         spacer = " "
     else:


=====================================
tests/pylib/jigs.py
=====================================
@@ -62,7 +62,7 @@ class SocketJig:
         self.closed = True
 
     def connect(self, addr):
-        if self.fail_connect is True:
+        if self.fail_connect:
             err = socket.error()
             err.strerror = "socket!"
             err.errno = 16
@@ -150,13 +150,13 @@ class SocketModuleJig:
 
     def socket(self, family, socktype, protocol):
         self.socket_calls.append((family, socktype, protocol))
-        if self.socket_fail is True:
+        if self.socket_fail:
             err = self.error()
             err.strerror = "error!"
             err.errno = 23
             raise err
         sock = SocketJig()
-        if self.socket_fail_connect is True:
+        if self.socket_fail_connect:
             sock.fail_connect = True
         self.socketsReturned.append(sock)
         return sock
@@ -217,7 +217,7 @@ class SelectModuleJig:
         if not self.do_return:  # simplify code that doesn't need it
             self.do_return.append(True)
         doreturn = self.do_return.pop(0)
-        if doreturn is True:
+        if doreturn:
             return (ins, [], [])
         else:
             return ([], [], [])


=====================================
tests/pylib/test_packet.py
=====================================
@@ -59,7 +59,7 @@ class AuthenticatorJig:
         self.compute_mac_calls = []
 
     def __getitem__(self, key):
-        if self.fail_getitem is True:
+        if self.fail_getitem:
             raise IndexError
         return ("passtype", "pass")
 
@@ -795,9 +795,9 @@ class TestControlSession(unittest.TestCase):
 
         def lookup_jig(hostname, family):
             lookups.append((hostname, family))
-            if returnNothing is True:
+            if returnNothing:
                 return None
-            elif noCanon is True:
+            elif noCanon:
                 return [("family", "socktype", "protocol", None,
                          ("1.2.3.4", 80)), ]
             else:



View it on GitLab: https://gitlab.com/NTPsec/ntpsec/commit/522a4ece2559ae03854979346416de8e8cc2652f

-- 
View it on GitLab: https://gitlab.com/NTPsec/ntpsec/commit/522a4ece2559ae03854979346416de8e8cc2652f
You're receiving this email because of your account on gitlab.com.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.ntpsec.org/pipermail/vc/attachments/20190204/7b240cdb/attachment-0001.html>


More information about the vc mailing list