[tor-commits] [stem/master] Checking for None by identity

atagar at torproject.org atagar at torproject.org
Tue Dec 4 17:07:37 UTC 2012


commit 69f72efc9367092c989819bb2e408598ecc9dcdb
Author: Damian Johnson <atagar at torproject.org>
Date:   Tue Dec 4 08:37:59 2012 -0800

    Checking for None by identity
    
    According to PEP 290 comparisons to None should be done via identity (the 'is'
    keyword):
    
    http://www.python.org/dev/peps/pep-0290/#testing-for-none
    
    I had already been doing this, albeit inconsistently. Inequality checks were
    still using '!=' - swapping all None comparisons to be by identity.
---
 run_tests.py                         |    2 +-
 stem/control.py                      |    6 +++---
 stem/descriptor/__init__.py          |    6 +++---
 stem/descriptor/server_descriptor.py |    2 +-
 stem/exit_policy.py                  |    4 ++--
 stem/response/events.py              |   30 +++++++++++++++---------------
 stem/util/conf.py                    |   10 +++++-----
 test/integ/control/controller.py     |    8 ++++----
 test/output.py                       |    2 +-
 test/runner.py                       |    2 +-
 10 files changed, 36 insertions(+), 36 deletions(-)

diff --git a/run_tests.py b/run_tests.py
index a9aebbe..cbf08d6 100755
--- a/run_tests.py
+++ b/run_tests.py
@@ -358,7 +358,7 @@ if __name__ == '__main__':
     # Queue up all the targets with torrc options we want to run against.
     
     integ_run_targets = []
-    all_run_targets = [t for t in Target if CONFIG["target.torrc"].get(t) != None]
+    all_run_targets = [t for t in Target if CONFIG["target.torrc"].get(t) is not None]
     
     if test_config.get("integ.target.run.all", False):
       # test against everything with torrc options
diff --git a/stem/control.py b/stem/control.py
index 8665a51..4d3bc8b 100644
--- a/stem/control.py
+++ b/stem/control.py
@@ -460,7 +460,7 @@ class BaseController(object):
       with self._status_listeners_lock:
         change_timestamp = time.time()
         
-        if expect_alive != None and expect_alive != self.is_alive():
+        if expect_alive is not None and expect_alive != self.is_alive():
           return
         
         for listener, spawn in self._status_listeners:
@@ -1546,13 +1546,13 @@ def _parse_circ_entry(entry):
     # old style, nickname only
     fingerprint, nickname = None, entry
   
-  if fingerprint != None:
+  if fingerprint is not None:
     if not stem.util.tor_tools.is_valid_fingerprint(fingerprint, True):
       raise stem.ProtocolError("Fingerprint in the circuit path is malformed (%s)" % fingerprint)
     
     fingerprint = fingerprint[1:] # strip off the leading '$'
   
-  if nickname != None and not stem.util.tor_tools.is_valid_nickname(nickname):
+  if nickname is not None and not stem.util.tor_tools.is_valid_nickname(nickname):
     raise stem.ProtocolError("Nickname in the circuit path is malformed (%s)" % fingerprint)
   
   return (fingerprint, nickname)
diff --git a/stem/descriptor/__init__.py b/stem/descriptor/__init__.py
index d667946..4c5841e 100644
--- a/stem/descriptor/__init__.py
+++ b/stem/descriptor/__init__.py
@@ -197,7 +197,7 @@ def _read_until_keywords(keywords, descriptor_file, inclusive = False, ignore_fi
   if ignore_first:
     first_line = descriptor_file.readline()
     
-    if content != None and first_line != None:
+    if content is not None and first_line is not None:
       content.append(first_line)
   
   while True:
@@ -220,11 +220,11 @@ def _read_until_keywords(keywords, descriptor_file, inclusive = False, ignore_fi
     if line_keyword in keywords:
       if not inclusive:
         descriptor_file.seek(last_position)
-      elif content != None:
+      elif content is not None:
         content.append(line)
       
       break
-    elif content != None:
+    elif content is not None:
       content.append(line)
   
   return content
diff --git a/stem/descriptor/server_descriptor.py b/stem/descriptor/server_descriptor.py
index 584d426..b87683c 100644
--- a/stem/descriptor/server_descriptor.py
+++ b/stem/descriptor/server_descriptor.py
@@ -821,7 +821,7 @@ class BridgeDescriptor(ServerDescriptor):
       scrubbing, this list is empty if we're properly scrubbed
     """
     
-    if self._scrubbing_issues == None:
+    if self._scrubbing_issues is None:
       issues = []
       
       if not self.address.startswith("10."):
diff --git a/stem/exit_policy.py b/stem/exit_policy.py
index 159fa2c..ce56551 100644
--- a/stem/exit_policy.py
+++ b/stem/exit_policy.py
@@ -443,7 +443,7 @@ class ExitPolicyRule(object):
     """
     
     # validate our input and check if the argument doesn't match our address type
-    if address != None:
+    if address is not None:
       if stem.util.connection.is_valid_ip_address(address):
         if self.address_type == AddressType.IPv6: return False
       elif stem.util.connection.is_valid_ipv6_address(address, allow_brackets = True):
@@ -453,7 +453,7 @@ class ExitPolicyRule(object):
       else:
         raise ValueError("'%s' isn't a valid IPv4 or IPv6 address" % address)
     
-    if port != None and not stem.util.connection.is_valid_port(port):
+    if port is not None and not stem.util.connection.is_valid_port(port):
       raise ValueError("'%s' isn't a valid port" % port)
     
     if not self.is_address_wildcard():
diff --git a/stem/response/events.py b/stem/response/events.py
index 30350a3..eb2aa64 100644
--- a/stem/response/events.py
+++ b/stem/response/events.py
@@ -161,10 +161,10 @@ class AddrMapEvent(Event):
     if self.destination == "<error>":
       self.destination = None
     
-    if self.expiry != None:
+    if self.expiry is not None:
       self.expiry = datetime.datetime.strptime(self.expiry, "%Y-%m-%d %H:%M:%S")
     
-    if self.utc_expiry != None:
+    if self.utc_expiry is not None:
       self.utc_expiry = datetime.datetime.strptime(self.utc_expiry, "%Y-%m-%d %H:%M:%S")
 
 class AuthDirNewDescEvent(Event):
@@ -247,7 +247,7 @@ class BuildTimeoutSetEvent(Event):
     for param in ('total_times', 'timeout', 'xm', 'close_timeout'):
       param_value = getattr(self, param)
       
-      if param_value != None:
+      if param_value is not None:
         try:
           setattr(self, param, int(param_value))
         except ValueError:
@@ -256,7 +256,7 @@ class BuildTimeoutSetEvent(Event):
     for param in ('alpha', 'quantile', 'timeout_rate', 'close_rate'):
       param_value = getattr(self, param)
       
-      if param_value != None:
+      if param_value is not None:
         try:
           setattr(self, param, float(param_value))
         except ValueError:
@@ -300,16 +300,16 @@ class CircuitEvent(Event):
   def _parse(self):
     self.path = tuple(stem.control._parse_circ_path(self.path))
     
-    if self.build_flags != None:
+    if self.build_flags is not None:
       self.build_flags = tuple(self.build_flags.split(','))
     
-    if self.created != None:
+    if self.created is not None:
       try:
         self.created = str_tools.parse_iso_timestamp(self.created)
       except ValueError, exc:
         raise stem.ProtocolError("Unable to parse create date (%s): %s" % (exc, self))
     
-    if self.id != None and not tor_tools.is_valid_circuit_id(self.id):
+    if self.id is not None and not tor_tools.is_valid_circuit_id(self.id):
       raise stem.ProtocolError("Circuit IDs must be one to sixteen alphanumeric characters, got '%s': %s" % (self.id, self))
     
     self._log_if_unrecognized('status', stem.CircStatus)
@@ -352,16 +352,16 @@ class CircMinorEvent(Event):
   def _parse(self):
     self.path = tuple(stem.control._parse_circ_path(self.path))
     
-    if self.build_flags != None:
+    if self.build_flags is not None:
       self.build_flags = tuple(self.build_flags.split(','))
     
-    if self.created != None:
+    if self.created is not None:
       try:
         self.created = str_tools.parse_iso_timestamp(self.created)
       except ValueError, exc:
         raise stem.ProtocolError("Unable to parse create date (%s): %s" % (exc, self))
     
-    if self.id != None and not tor_tools.is_valid_circuit_id(self.id):
+    if self.id is not None and not tor_tools.is_valid_circuit_id(self.id):
       raise stem.ProtocolError("Circuit IDs must be one to sixteen alphanumeric characters, got '%s': %s" % (self.id, self))
     
     self._log_if_unrecognized('event', stem.CircEvent)
@@ -387,10 +387,10 @@ class ClientsSeenEvent(Event):
   }
   
   def _parse(self):
-    if self.start_time != None:
+    if self.start_time is not None:
       self.start_time = datetime.datetime.strptime(self.start_time, "%Y-%m-%d %H:%M:%S")
     
-    if self.locales != None:
+    if self.locales is not None:
       locale_to_count = {}
       
       for entry in self.locales.split(','):
@@ -410,7 +410,7 @@ class ClientsSeenEvent(Event):
       
       self.locales = locale_to_count
     
-    if self.ip_versions != None:
+    if self.ip_versions is not None:
       protocol_to_count = {}
       
       for entry in self.ip_versions.split(','):
@@ -607,7 +607,7 @@ class ORConnEvent(Event):
       self.endpoint_address = address
       self.endpoint_port = int(port)
     
-    if self.circ_count != None:
+    if self.circ_count is not None:
       if not self.circ_count.isdigit():
         raise stem.ProtocolError("ORCONN event got a non-numeric circuit count (%s): %s" % (self.circ_count, self))
       
@@ -754,7 +754,7 @@ class StreamBwEvent(Event):
   _POSITIONAL_ARGS = ("id", "written", "read")
   
   def _parse(self):
-    if self.id != None and not tor_tools.is_valid_stream_id(self.id):
+    if self.id is not None and not tor_tools.is_valid_stream_id(self.id):
       raise stem.ProtocolError("Stream IDs must be one to sixteen alphanumeric characters, got '%s': %s" % (self.id, self))
     elif not self.written:
       raise stem.ProtocolError("STREAM_BW event is missing its written value")
diff --git a/stem/util/conf.py b/stem/util/conf.py
index cc80cb8..395d8f1 100644
--- a/stem/util/conf.py
+++ b/stem/util/conf.py
@@ -606,9 +606,9 @@ class Config(object):
       conf_comp = [entry.strip() for entry in conf_value.split(",")]
       
       # check if the count doesn't match
-      if count != None and len(conf_comp) != count:
+      if count is not None and len(conf_comp) != count:
         msg = "Config entry '%s' is expected to be %i comma separated values" % (key, count)
-        if default != None and (isinstance(default, list) or isinstance(default, tuple)):
+        if default is not None and (isinstance(default, list) or isinstance(default, tuple)):
           defaultStr = ", ".join([str(i) for i in default])
           msg += ", defaulting to '%s'" % defaultStr
         
@@ -642,7 +642,7 @@ class Config(object):
     base_error_msg = "Config entry '%s' is expected to %%s" % key
     
     # includes our default value in the message
-    if default != None and (isinstance(default, list) or isinstance(default, tuple)):
+    if default is not None and (isinstance(default, list) or isinstance(default, tuple)):
       default_str = ", ".join([str(i) for i in default])
       base_error_msg += ", defaulting to '%s'" % default_str
     
@@ -651,10 +651,10 @@ class Config(object):
         error_msg = base_error_msg % "only have integer values"
         break
       else:
-        if min_value != None and int(val) < min_value:
+        if min_value is not None and int(val) < min_value:
           error_msg = base_error_msg % "only have values over %i" % min_value
           break
-        elif max_value != None and int(val) > max_value:
+        elif max_value is not None and int(val) > max_value:
           error_msg = base_error_msg % "only have values less than %i" % max_value
           break
     
diff --git a/test/integ/control/controller.py b/test/integ/control/controller.py
index 496028c..7c424cf 100644
--- a/test/integ/control/controller.py
+++ b/test/integ/control/controller.py
@@ -554,8 +554,8 @@ class TestController(unittest.TestCase):
       count = 0
       
       for desc in controller.get_server_descriptors():
-        self.assertTrue(desc.fingerprint != None)
-        self.assertTrue(desc.nickname != None)
+        self.assertTrue(desc.fingerprint is not None)
+        self.assertTrue(desc.nickname is not None)
         
         # Se don't want to take the time to read the whole thing. We already
         # have another test that reads the full cached descriptors (and takes a
@@ -620,8 +620,8 @@ class TestController(unittest.TestCase):
       count = 0
       
       for desc in controller.get_network_statuses():
-        self.assertTrue(desc.fingerprint != None)
-        self.assertTrue(desc.nickname != None)
+        self.assertTrue(desc.fingerprint is not None)
+        self.assertTrue(desc.nickname is not None)
         
         count += 1
         if count > 10: break
diff --git a/test/output.py b/test/output.py
index 001c6a5..fdbafac 100644
--- a/test/output.py
+++ b/test/output.py
@@ -99,7 +99,7 @@ def apply_filters(testing_output, *filters):
       line = result_filter(line_type, line)
       if line is None: break
     
-    if line != None:
+    if line is not None:
       results.append(line)
   
   return "\n".join(results) + "\n"
diff --git a/test/runner.py b/test/runner.py
index acf346e..0393a68 100644
--- a/test/runner.py
+++ b/test/runner.py
@@ -360,7 +360,7 @@ class Runner(object):
       # Check for an unexpected shutdown by calling subprocess.Popen.poll(),
       # which returns the exit code or None if we're still running.
       
-      if self._tor_process and self._tor_process.poll() != None:
+      if self._tor_process and self._tor_process.poll() is not None:
         # clean up the temporary resources and note the unexpected shutdown
         self.stop()
         test.output.print_line("tor shut down unexpectedly", *ERROR_ATTR)



More information about the tor-commits mailing list