[Git][NTPsec/ntpsec][master] PEP8: don't use len() to tell if the sequence is empty or not

Matt Selsky gitlab at mg.gitlab.com
Mon Feb 4 01:20:54 UTC 2019


Matt Selsky pushed to branch master at NTPsec / ntpsec


Commits:
d2cda592 by Matt Selsky at 2019-02-04T01:17:21Z
PEP8: don't use len() to tell if the sequence is empty or not

For sequences, (strings, lists, tuples), use the fact that empty sequences are
false.

- - - - -


8 changed files:

- contrib/make-leap-seconds.py
- ntpclients/ntpq.py
- pylib/agentx.py
- pylib/agentx_packet.py
- pylib/packet.py
- pylib/util.py
- tests/pylib/jigs.py
- tests/pylib/test_packet.py


Changes:

=====================================
contrib/make-leap-seconds.py
=====================================
@@ -26,14 +26,14 @@ leap = time.time()
 days = int(leap/86400)
 leap = (days+1)*86400
 
-if len(args) > 0:
+if args:
     leapdate = datetime.datetime.strptime(args[0], "%Y-%m-%d")
     leap = (leapdate - epoch).total_seconds()
     leap = int(leap)
     args = args[1:]
 
 expire = leap + 28*86400
-if len(args) > 0:
+if args:
     expiredate = datetime.datetime.strptime(args[0], "%Y-%m-%d")
     expire = (expiredate - epoch).total_seconds()
     expire = int(expire)


=====================================
ntpclients/ntpq.py
=====================================
@@ -113,7 +113,7 @@ class Ntpq(cmd.Cmd):
             elif len(cmdprefixlist) > 1:
                 self.warn("***Command `%s' ambiguous\n" % cmd)
                 return
-            elif len(cmdprefixlist) == 0:
+            elif not cmdprefixlist:
                 self.warn("***Command `%s' unknown\n" % cmd)
                 return
 
@@ -127,7 +127,7 @@ class Ntpq(cmd.Cmd):
                     elif len(argprefixlist) > 1:
                         self.warn("Command `%s' is ambiguous\n" % arg)
                         return
-                    elif len(argprefixlist) == 0:
+                    elif not argprefixlist:
                         self.warn("Command `%s' is unknown\n" % arg)
                         return
 
@@ -178,7 +178,7 @@ usage: help [ command ]
             print(e.strerror)
             return False
 
-        if len(self.peers) == 0:
+        if not self.peers:
             if self.chosts:
                 self.say("server=%s " % self.session.hostname)
             self.say("No association IDs returned\n")
@@ -857,7 +857,7 @@ usage: clearvars
 
     def do_showvars(self, line):
         "print variables on the variable list"
-        if len(self.uservars) == 0:
+        if not self.uservars:
             print("No variables on list.")
         for (name, value) in self.uservars.items():
             if value:
@@ -1666,17 +1666,17 @@ if __name__ == '__main__':
         else:
             interpreter.chosts.append((token, session.ai_family))
 
-    if len(arguments) == 0:
+    if not arguments:
         interpreter.chosts.append((DEFHOST, session.ai_family))
 
-    if (len(interpreter.ccmds) == 0 and
+    if (not interpreter.ccmds and
             not interpreter.interactive and
             os.isatty(0) and
             os.isatty(1)):
         interpreter.interactive = True
 
     try:
-        if len(interpreter.ccmds) == 0:
+        if not interpreter.ccmds:
             if len(interpreter.chosts) > 1:
                 interpreter.warn(
                     "ntpq can only work interactively on one host.\n")


=====================================
pylib/agentx.py
=====================================
@@ -69,7 +69,7 @@ class MIBControl:
             if node not in currentLevel.keys():
                 currentLevel[node] = {"reader": None, "writer": None,
                                       "subids": None}
-            if len(remainingOID) == 0:  # We have reached the target node
+            if not remainingOID:  # We have reached the target node
                 currentLevel[node]["reader"] = reader
                 currentLevel[node]["writer"] = writer
                 if dynamic is not None:
@@ -207,7 +207,7 @@ class PacketControl:
         # loop body split out to separate the one-shot/run-forever switches
         # from the actual logic
         self.packetEater()
-        while len(self.receivedPackets) > 0:
+        while self.receivedPackets:
             packet = self.receivedPackets.pop(0)
             if packet.sessionID != self.sessionID:
                 self.log(
@@ -252,7 +252,7 @@ class PacketControl:
         "Wait for a response to a specific packet, dropping everything else"
         while True:
             self.packetEater()
-            while len(self.receivedPackets) > 0:
+            while self.receivedPackets:
                 packet = self.receivedPackets.pop(0)
                 if packet.__class__ != ax.ResponsePDU:
                     continue
@@ -352,11 +352,11 @@ class PacketControl:
         data = b""
         while True:
             tmp = select.select([self.socket], [], [], 0)[0]
-            if len(tmp) == 0:  # No socket, means no data available
+            if not tmp:  # No socket, means no data available
                 break
             tmp = tmp[0]
             newdata = tmp.recv(4096)  # Arbitrary value
-            if len(newdata) > 0:
+            if newdata:
                 self.log("Received data: %s" % repr(newdata), 5)
                 data += newdata
                 self.lastReception = time.time()
@@ -397,7 +397,7 @@ class PacketControl:
         for oidr in packet.oidranges:
             while True:
                 oids = self.database.getOIDsInRange(oidr, True)
-                if len(oids) == 0:  # Nothing found
+                if not oids:  # Nothing found
                     binds.append(ax.Varbind(ax.VALUE_END_OF_MIB_VIEW,
                                             oidr.start))
                     break
@@ -424,7 +424,7 @@ class PacketControl:
         # Handle non-repeats
         for oidr in nonreps:
             oids = self.database.getOIDsInRange(oidr, True)
-            if len(oids) == 0:  # Nothing found
+            if not oids:  # Nothing found
                 binds.append(ax.Varbind(ax.VALUE_END_OF_MIB_VIEW, oidr.start))
             else:
                 oid, reader, _ = oids[0]
@@ -432,7 +432,7 @@ class PacketControl:
         # Handle repeaters
         for oidr in repeats:
             oids = self.database.getOIDsInRange(oidr)
-            if len(oids) == 0:  # Nothing found
+            if not oids:  # Nothing found
                 binds.append(ax.Varbind(ax.VALUE_END_OF_MIB_VIEW, oidr.start))
             else:
                 for oid, reader, _ in oids[:packet.maxReps]:
@@ -553,7 +553,7 @@ def walkMIBTree(tree, rootpath=()):
     keyID = 0
     while True:
         if keyID >= len(currentKeys):
-            if len(nodeStack) > 0:
+            if nodeStack:
                 # No more nodes this level, pop higher node
                 current, currentKeys, keyID, key = nodeStack.pop()
                 oidStack.pop()


=====================================
pylib/agentx_packet.py
=====================================
@@ -673,7 +673,7 @@ def decode_ResponsePDU(data, header):
     temp, data = slicedata(data, 8)
     sysUptime, resError, resIndex = struct.unpack(endianToken + "IHH",
                                                   ntp.poly.polybytes(temp))
-    if len(data) > 0:
+    if data:
         varbinds = decode_varbindlist(data, header)
     else:
         varbinds = None
@@ -828,7 +828,7 @@ class OID:
             raise ValueError
 
     def isNull(self):
-        if (len(self.subids) == 0) and (self.include is False):
+        if not self.subids and self.include is False:
             return True
         return False
 
@@ -1095,7 +1095,7 @@ def encode_searchrange_list(bigEndian, searchranges):
 
 def decode_searchrange_list(data, header):  # Cannot handle extra data
     oidranges = []
-    while len(data) > 0:
+    while data:
         oids, data = decode_SearchRange(data, header)
         oidranges.append(oids)
     return tuple(oidranges)
@@ -1109,9 +1109,9 @@ def encode_varbindlist(bigEndian, varbinds):
 
 
 def decode_varbindlist(data, header):
-    if len(data) > 0:
+    if data:
         varbinds = []
-        while len(data) > 0:
+        while data:
             vb, data = decode_Varbind(data, header)
             varbinds.append(vb)
         varbinds = tuple(varbinds)


=====================================
pylib/packet.py
=====================================
@@ -592,7 +592,7 @@ SERR_NOTRUST = "***No trusted keys have been declared"
 def dump_hex_printable(xdata, outfp=sys.stdout):
     "Dump a packet in hex, in a familiar hex format"
     rowsize = 16
-    while len(xdata) > 0:
+    while xdata:
         # Slice one row off of our data
         linedata, xdata = ntp.util.slicedata(xdata, rowsize)
         # Output data in hex form
@@ -946,7 +946,7 @@ class ControlSession:
             if bail >= (2*MAXFRAGS):
                 raise ControlException(SERR_TOOMUCH)
 
-            if len(fragments) == 0:
+            if not fragments:
                 tvo = self.primary_timeout / 1000
             else:
                 tvo = self.secondary_timeout / 1000
@@ -962,7 +962,7 @@ class ControlSession:
 
             if not rd:
                 # Timed out.  Return what we have
-                if len(fragments) == 0:
+                if not fragments:
                     if timeo:
                         raise ControlException(SERR_TIMEOUT)
                 if timeo:
@@ -1014,7 +1014,7 @@ class ControlSession:
             # Find the most recent fragment with a
             not_earlier = [frag for frag in fragments
                            if frag.offset >= rpkt.offset]
-            if len(not_earlier):
+            if not_earlier:
                 not_earlier = not_earlier[0]
                 if not_earlier.offset == rpkt.offset:
                     warn("duplicate %d octets at %d ignored, prior "
@@ -1023,7 +1023,7 @@ class ControlSession:
                             not_earlier.count, not_earlier.offset))
                     continue
 
-            if len(fragments) > 0:
+            if fragments:
                 last = fragments[-1]
                 if last.end() > rpkt.offset:
                     warn("received frag at %d overlaps with %d octet "
@@ -1202,7 +1202,7 @@ class ControlSession:
             elif 0 < cord < 127:
                 # if it isn't a special case or garbage, add it
                 response += c
-        if len(response) > 0:  # The last item won't be caught by the loop
+        if response:  # The last item won't be caught by the loop
             kvpairs.append(response.strip())
         items = []
         for pair in kvpairs:


=====================================
pylib/util.py
=====================================
@@ -182,9 +182,9 @@ def parseConf(text):
         current[:] = []
 
     def pushLine():
-        if len(current) > 0:
+        if current:
             pushToken()
-        if len(tokens) > 0:
+        if tokens:
             lines.append(tokens[:])
             tokens[:] = []
 
@@ -210,7 +210,7 @@ def parseConf(text):
             elif text[i] in "'\"":  # Starting a text string
                 inQuote = True
                 quoteStarter = text[i]
-                if len(current) > 0:
+                if current:
                     pushToken()
             elif text[i] == "\\":  # Linebreak escape
                 i += 1
@@ -219,7 +219,7 @@ def parseConf(text):
             elif text[i] == "\n":  # EOL: break the lines
                 pushLine()
             elif text[i] in string.whitespace:
-                if len(current) > 0:
+                if current:
                     pushToken()
             else:
                 current.append(text[i])
@@ -316,7 +316,7 @@ def gluenumberstring(above, below, isnegative):
     "Glues together parts of a number string"
     if above == "":
         above = "0"
-    if len(below) > 0:
+    if below:
         newvalue = ".".join((above, below))
     else:
         newvalue = above


=====================================
tests/pylib/jigs.py
=====================================
@@ -33,7 +33,7 @@ class FileJig:
         self.flushed = True
 
     def readline(self):
-        if len(self.readline_return) > 0:
+        if self.readline_return:
             return self.readline_return.pop(0)
         return ""
 
@@ -70,7 +70,7 @@ class SocketJig:
         self.connected = addr
 
     def recv(self, bytecount):
-        if len(self.return_data) > 0:
+        if self.return_data:
             current = self.return_data.pop(0)
             if len(current) > bytecount:
                 ret = current[:bytecount]
@@ -89,7 +89,7 @@ class HasherJig:
 
     def update(self, data):
         self.update_calls.append(data)
-        if len(data) > 0:
+        if data:
             self.digest_size += 1
 
     def digest(self):
@@ -214,7 +214,7 @@ class SelectModuleJig:
         if self.select_fail > 0:
             self.select_fail -= 1
             raise select.error
-        if len(self.do_return) == 0:  # simplify code that doesn't need it
+        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:


=====================================
tests/pylib/test_packet.py
=====================================
@@ -1548,7 +1548,7 @@ class TestControlSession(unittest.TestCase):
                 query_fail[0] -= 1
                 code = query_fail_code.pop(0)
                 raise ctlerr("foo", errorcode=code)
-            if len(query_results) > 0:
+            if query_results:
                 setresponse(query_results.pop(0))
         logjig = jigs.FileJig()
         # Init



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

-- 
View it on GitLab: https://gitlab.com/NTPsec/ntpsec/commit/d2cda59232e1dc9bdd0a08e94015975837a00219
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/01af763a/attachment-0001.html>


More information about the vc mailing list