[tor-commits] [stem/master] Dropping unnecessary list() calls

atagar at torproject.org atagar at torproject.org
Sun Jan 4 02:29:03 UTC 2015


commit c9653bcfc88082e66ca8a6b151741dd6a33e07da
Author: Damian Johnson <atagar at torproject.org>
Date:   Sat Jan 3 12:34:47 2015 -0800

    Dropping unnecessary list() calls
    
    Python's 2to3 converter wraps quite a few things with list() to be safe...
    
      https://stackoverflow.com/questions/17695456/why-python-3-needs-wrap-dict-items-with-list
    
    More often than not this is the right thing. In particular...
    
      * If we return the value then we need the list() call, since dict's keys(),
        values(), and items() now return a different type.
    
      * If we concurrently modify the dictionary *or* it's an argument provided
        from our caller (so they might concurrently modify it) then we need this
        shallow copy so we don't raise an exception due to concurrent modification.
    
    That is to say, the only time we *don't* need the list() call is when it's a
    local variable that won't be concurrently modified. There's quite a few
    instances of this, so dropping the extraneous list() when we can.
---
 run_tests.py                                       |    6 ++---
 stem/__init__.py                                   |    2 +-
 stem/control.py                                    |   18 +++++++-------
 stem/descriptor/microdescriptor.py                 |    2 +-
 stem/descriptor/networkstatus.py                   |   12 ++++-----
 stem/descriptor/remote.py                          |    8 +++---
 stem/exit_policy.py                                |    4 +--
 stem/interpreter/arguments.py                      |    2 +-
 stem/interpreter/autocomplete.py                   |    2 +-
 stem/interpreter/help.py                           |    2 +-
 stem/response/__init__.py                          |    2 +-
 stem/response/events.py                            |    2 +-
 stem/util/conf.py                                  |    2 +-
 stem/util/connection.py                            |    2 +-
 stem/util/system.py                                |    2 +-
 stem/util/test_tools.py                            |    2 +-
 test/integ/control/controller.py                   |    2 +-
 test/integ/descriptor/remote.py                    |    2 +-
 test/mocking.py                                    |    4 +--
 test/unit/control/controller.py                    |    2 +-
 .../descriptor/networkstatus/bridge_document.py    |    2 +-
 test/unit/descriptor/networkstatus/document_v3.py  |   10 ++++----
 test/unit/descriptor/router_status_entry.py        |   16 ++++++------
 test/unit/exit_policy/policy.py                    |   10 ++++----
 test/unit/exit_policy/rule.py                      |   26 ++++++++++----------
 test/unit/tutorial.py                              |    2 +-
 test/unit/tutorial_examples.py                     |   14 +++++------
 test/unit/util/connection.py                       |    4 +--
 test/unit/util/str_tools.py                        |    2 +-
 test/util.py                                       |    4 +--
 30 files changed, 85 insertions(+), 85 deletions(-)

diff --git a/run_tests.py b/run_tests.py
index c881f66..2bf2744 100755
--- a/run_tests.py
+++ b/run_tests.py
@@ -300,14 +300,14 @@ def main():
     static_check_issues = {}
 
     if pyflakes_task and pyflakes_task.is_successful:
-      for path, issues in list(pyflakes_task.result.items()):
+      for path, issues in pyflakes_task.result.items():
         for issue in issues:
           static_check_issues.setdefault(path, []).append(issue)
     elif not stem.util.test_tools.is_pyflakes_available():
       println("Static error checking requires pyflakes version 0.7.3 or later. Please install it from ...\n  http://pypi.python.org/pypi/pyflakes\n", ERROR)
 
     if pep8_task and pep8_task.is_successful:
-      for path, issues in list(pep8_task.result.items()):
+      for path, issues in pep8_task.result.items():
         for issue in issues:
           static_check_issues.setdefault(path, []).append(issue)
     elif not stem.util.test_tools.is_pep8_available():
@@ -403,7 +403,7 @@ def _get_args(argv):
 
   # translates our args dict into a named tuple
 
-  Args = collections.namedtuple('Args', list(args.keys()))
+  Args = collections.namedtuple('Args', args.keys())
   return Args(**args)
 
 
diff --git a/stem/__init__.py b/stem/__init__.py
index 3ac4565..baa2ef8 100644
--- a/stem/__init__.py
+++ b/stem/__init__.py
@@ -712,7 +712,7 @@ StreamStatus = stem.util.enum.UppercaseEnum(
 )
 
 # StreamClosureReason is a superset of RelayEndReason
-StreamClosureReason = stem.util.enum.UppercaseEnum(*(list(RelayEndReason.keys()) + [
+StreamClosureReason = stem.util.enum.UppercaseEnum(*(RelayEndReason.keys() + [
   'END',
   'PRIVATE_ADDR',
 ]))
diff --git a/stem/control.py b/stem/control.py
index 993d5c3..6c34671 100644
--- a/stem/control.py
+++ b/stem/control.py
@@ -926,7 +926,7 @@ class Controller(BaseController):
       if self.is_caching_enabled():
         self._set_cache(dict((k, None) for k in event.config), 'getconf')
 
-        if 'exitpolicy' in list(event.config.keys()):
+        if 'exitpolicy' in event.config.keys():
           self._set_cache({'exitpolicy': None})
 
     self.add_event_listener(_confchanged_listener, EventType.CONF_CHANGED)
@@ -1020,7 +1020,7 @@ class Controller(BaseController):
 
     # if everything was cached then short circuit making the query
     if not params:
-      log.trace('GETINFO %s (cache fetch)' % ' '.join(list(reply.keys())))
+      log.trace('GETINFO %s (cache fetch)' % ' '.join(reply.keys()))
 
       if is_multiple:
         return reply
@@ -1035,14 +1035,14 @@ class Controller(BaseController):
       # usually we want unicode values under python 3.x
 
       if stem.prereq.is_python_3() and not get_bytes:
-        response.entries = dict((k, stem.util.str_tools._to_unicode(v)) for (k, v) in list(response.entries.items()))
+        response.entries = dict((k, stem.util.str_tools._to_unicode(v)) for (k, v) in response.entries.items())
 
       reply.update(response.entries)
 
       if self.is_caching_enabled():
         to_cache = {}
 
-        for key, value in list(response.entries.items()):
+        for key, value in response.entries.items():
           key = key.lower()  # make case insensitive
 
           if key in CACHEABLE_GETINFO_PARAMS:
@@ -1911,7 +1911,7 @@ class Controller(BaseController):
 
     # if everything was cached then short circuit making the query
     if not lookup_params:
-      log.trace('GETCONF %s (cache fetch)' % ' '.join(list(reply.keys())))
+      log.trace('GETCONF %s (cache fetch)' % ' '.join(reply.keys()))
       return self._get_conf_dict_to_response(reply, default, multiple)
 
     try:
@@ -1920,7 +1920,7 @@ class Controller(BaseController):
       reply.update(response.entries)
 
       if self.is_caching_enabled():
-        to_cache = dict((k.lower(), v) for k, v in list(response.entries.items()))
+        to_cache = dict((k.lower(), v) for k, v in response.entries.items())
 
         for key in UNCACHEABLE_GETCONF_PARAMS:
           if key in to_cache:
@@ -1939,7 +1939,7 @@ class Controller(BaseController):
       # be sure what they wanted.
 
       for key in reply:
-        if not key.lower() in list(MAPPED_CONFIG_KEYS.values()):
+        if not key.lower() in MAPPED_CONFIG_KEYS.values():
           user_expected_key = _case_insensitive_lookup(params, key, key)
 
           if key != user_expected_key:
@@ -2447,7 +2447,7 @@ class Controller(BaseController):
             del self._event_listeners[event_type]
 
       if event_types_changed:
-        response = self.msg('SETEVENTS %s' % ' '.join(list(self._event_listeners.keys())))
+        response = self.msg('SETEVENTS %s' % ' '.join(self._event_listeners.keys()))
 
         if not response.is_ok():
           raise stem.ProtocolError('SETEVENTS received unexpected response\n%s' % response)
@@ -3158,7 +3158,7 @@ class Controller(BaseController):
     with self._event_listeners_lock:
       if self.is_authenticated():
         # try to set them all
-        response = self.msg('SETEVENTS %s' % ' '.join(list(self._event_listeners.keys())))
+        response = self.msg('SETEVENTS %s' % ' '.join(self._event_listeners.keys()))
 
         if response.is_ok():
           set_events = list(self._event_listeners.keys())
diff --git a/stem/descriptor/microdescriptor.py b/stem/descriptor/microdescriptor.py
index e5d690f..093e6f0 100644
--- a/stem/descriptor/microdescriptor.py
+++ b/stem/descriptor/microdescriptor.py
@@ -302,7 +302,7 @@ class Microdescriptor(Descriptor):
       if keyword in entries and len(entries[keyword]) > 1:
         raise ValueError("The '%s' entry can only appear once in a microdescriptor" % keyword)
 
-    if "onion-key" != list(entries.keys())[0]:
+    if 'onion-key' != list(entries.keys())[0]:
       raise ValueError("Microdescriptor must start with a 'onion-key' entry")
 
   def _name(self, is_plural = False):
diff --git a/stem/descriptor/networkstatus.py b/stem/descriptor/networkstatus.py
index 65bf5cc..33beb4a 100644
--- a/stem/descriptor/networkstatus.py
+++ b/stem/descriptor/networkstatus.py
@@ -516,7 +516,7 @@ class NetworkStatusDocumentV3(NetworkStatusDocument):
     self._header = _DocumentHeader(document_file, validate, default_params)
 
     # merge header attributes into us
-    for attr, value in list(vars(self._header).items()):
+    for attr, value in vars(self._header).items():
       if attr != '_unrecognized_lines':
         setattr(self, attr, value)
       else:
@@ -553,7 +553,7 @@ class NetworkStatusDocumentV3(NetworkStatusDocument):
     self._footer = _DocumentFooter(document_file, validate, self._header)
 
     # merge header attributes into us
-    for attr, value in list(vars(self._footer).items()):
+    for attr, value in vars(self._footer).items():
       if attr != '_unrecognized_lines':
         setattr(self, attr, value)
       else:
@@ -795,7 +795,7 @@ class _DocumentHeader(object):
     Checks that the params we know about are within their documented ranges.
     """
 
-    for key, value in list(self.params.items()):
+    for key, value in self.params.items():
       # all parameters are constrained to int32 range
       minimum, maximum = -2147483648, 2147483647
 
@@ -941,11 +941,11 @@ def _check_for_missing_and_disallowed_fields(header, entries, fields):
   for field, in_votes, in_consensus, mandatory in fields:
     if mandatory and ((header.is_consensus and in_consensus) or (header.is_vote and in_votes)):
       # mandatory field, check that we have it
-      if field not in list(entries.keys()):
+      if field not in entries.keys():
         missing_fields.append(field)
     elif (header.is_consensus and not in_consensus) or (header.is_vote and not in_votes):
       # field we shouldn't have, check that we don't
-      if field in list(entries.keys()):
+      if field in entries.keys():
         disallowed_fields.append(field)
 
   if missing_fields:
@@ -972,7 +972,7 @@ def _check_for_misordered_fields(entries, expected):
   # document type or are unknown. Remove the unknown fields since they
   # reflect a spec change and can appear anywhere in the document.
 
-  actual = [field for field in list(entries.keys()) if field in expected]
+  actual = [field for field in entries.keys() if field in expected]
 
   # Narrow the expected to just what we have. If the lists then match then the
   # order's valid.
diff --git a/stem/descriptor/remote.py b/stem/descriptor/remote.py
index fa0a672..058741f 100644
--- a/stem/descriptor/remote.py
+++ b/stem/descriptor/remote.py
@@ -344,7 +344,7 @@ class Query(object):
     """
 
     if use_authority or not self.endpoints:
-      authority = random.choice(list(filter(HAS_V3IDENT, list(get_authorities().values()))))
+      authority = random.choice(filter(HAS_V3IDENT, get_authorities().values()))
       address, dirport = authority.address, authority.dir_port
     else:
       address, dirport = random.choice(self.endpoints)
@@ -394,7 +394,7 @@ class DescriptorDownloader(object):
   def __init__(self, use_mirrors = False, **default_args):
     self._default_args = default_args
 
-    authorities = list(filter(HAS_V3IDENT, list(get_authorities().values())))
+    authorities = filter(HAS_V3IDENT, get_authorities().values())
     self._endpoints = [(auth.address, auth.dir_port) for auth in authorities]
 
     if use_mirrors:
@@ -416,12 +416,12 @@ class DescriptorDownloader(object):
     :raises: **Exception** if unable to determine the directory mirrors
     """
 
-    authorities = list(filter(HAS_V3IDENT, list(get_authorities().values())))
+    authorities = filter(HAS_V3IDENT, get_authorities().values())
     new_endpoints = set([(auth.address, auth.dir_port) for auth in authorities])
 
     consensus = list(self.get_consensus(document_handler = stem.descriptor.DocumentHandler.DOCUMENT).run())[0]
 
-    for desc in list(consensus.routers.values()):
+    for desc in consensus.routers.values():
       if Flag.V2DIR in desc.flags:
         new_endpoints.add((desc.address, desc.dir_port))
 
diff --git a/stem/exit_policy.py b/stem/exit_policy.py
index 06b2b53..afcd81d 100644
--- a/stem/exit_policy.py
+++ b/stem/exit_policy.py
@@ -306,7 +306,7 @@ class ExitPolicy(object):
         if rule.is_port_wildcard():
           return False
         else:
-          rejected_ports.update(list(range(rule.min_port, rule.max_port + 1)))
+          rejected_ports.update(range(rule.min_port, rule.max_port + 1))
 
     return self._is_allowed_default
 
@@ -1026,7 +1026,7 @@ def _address_type_to_int(address_type):
 
 
 def _int_to_address_type(address_type_int):
-  return AddressType[list(AddressType.keys())[address_type_int]]
+  return list(AddressType)[address_type_int]
 
 
 class MicroExitPolicyRule(ExitPolicyRule):
diff --git a/stem/interpreter/arguments.py b/stem/interpreter/arguments.py
index d36d618..d62a386 100644
--- a/stem/interpreter/arguments.py
+++ b/stem/interpreter/arguments.py
@@ -77,7 +77,7 @@ def parse(argv):
 
   # translates our args dict into a named tuple
 
-  Args = collections.namedtuple('Args', list(args.keys()))
+  Args = collections.namedtuple('Args', args.keys())
   return Args(**args)
 
 
diff --git a/stem/interpreter/autocomplete.py b/stem/interpreter/autocomplete.py
index c014ef3..3a9b40b 100644
--- a/stem/interpreter/autocomplete.py
+++ b/stem/interpreter/autocomplete.py
@@ -70,7 +70,7 @@ def _get_commands(controller, config):
 
   usage_info = config.get('help.usage', {})
 
-  for cmd in list(usage_info.keys()):
+  for cmd in usage_info.keys():
     commands.append('/help ' + cmd)
 
   return commands
diff --git a/stem/interpreter/help.py b/stem/interpreter/help.py
index 174bc43..983da3e 100644
--- a/stem/interpreter/help.py
+++ b/stem/interpreter/help.py
@@ -97,7 +97,7 @@ def _response(controller, arg, config):
   elif arg == 'SIGNAL':
     signal_options = config.get('help.signal.options', {})
 
-    for signal, summary in list(signal_options.items()):
+    for signal, summary in signal_options.items():
       output += format('%-15s' % signal, *BOLD_OUTPUT)
       output += format(' - %s' % summary, *STANDARD_OUTPUT) + '\n'
   elif arg == 'SETEVENTS':
diff --git a/stem/response/__init__.py b/stem/response/__init__.py
index 38d7d8e..6a91698 100644
--- a/stem/response/__init__.py
+++ b/stem/response/__init__.py
@@ -532,7 +532,7 @@ def _unescape(entry):
     #
     #   (unescaped prefix, remaining entry)
 
-    for esc_sequence, replacement in list(CONTROL_ESCAPES.items()):
+    for esc_sequence, replacement in CONTROL_ESCAPES.items():
       if entry.startswith(esc_sequence):
         return (replacement, entry[len(esc_sequence):])
 
diff --git a/stem/response/events.py b/stem/response/events.py
index 55c73e3..3e54281 100644
--- a/stem/response/events.py
+++ b/stem/response/events.py
@@ -123,7 +123,7 @@ class Event(stem.response.ControlMessage):
 
       setattr(self, attr_name, attr_value)
 
-    for controller_attr_name, attr_name in list(self._KEYWORD_ARGS.items()):
+    for controller_attr_name, attr_name in self._KEYWORD_ARGS.items():
       setattr(self, attr_name, self.keyword_args.get(controller_attr_name))
 
   # method overwritten by our subclasses for special handling that they do
diff --git a/stem/util/conf.py b/stem/util/conf.py
index c74361c..0b1e937 100644
--- a/stem/util/conf.py
+++ b/stem/util/conf.py
@@ -576,7 +576,7 @@ class Config(object):
       self._listeners.append(listener)
 
       if backfill:
-        for key in list(self.keys()):
+        for key in self.keys():
           listener(self, key)
 
   def clear_listeners(self):
diff --git a/stem/util/connection.py b/stem/util/connection.py
index ded09b3..2165b45 100644
--- a/stem/util/connection.py
+++ b/stem/util/connection.py
@@ -304,7 +304,7 @@ def port_usage(port):
       config.load(config_path)
       port_uses = {}
 
-      for key, value in list(config.get('port', {}).items()):
+      for key, value in config.get('port', {}).items():
         if key.isdigit():
          port_uses[int(key)] = value
         elif '-' in key:
diff --git a/stem/util/system.py b/stem/util/system.py
index 315c39e..66f46a9 100644
--- a/stem/util/system.py
+++ b/stem/util/system.py
@@ -243,7 +243,7 @@ def is_running(command):
       command_listing = call(secondary_resolver, None)
 
     if command_listing:
-      command_listing = list(map(str_type.strip, command_listing))
+      command_listing = map(str_type.strip, command_listing)
       return command in command_listing
 
   return None
diff --git a/stem/util/test_tools.py b/stem/util/test_tools.py
index 624f445..8209c58 100644
--- a/stem/util/test_tools.py
+++ b/stem/util/test_tools.py
@@ -262,7 +262,7 @@ def pyflakes_issues(paths):
         # Paths in pyflakes_ignore are relative, so we need to check to see if our
         # path ends with any of them.
 
-        for ignored_path, ignored_issues in list(self._ignored_issues.items()):
+        for ignored_path, ignored_issues in self._ignored_issues.items():
           if path.endswith(ignored_path) and issue in ignored_issues:
             return True
 
diff --git a/test/integ/control/controller.py b/test/integ/control/controller.py
index fbe66e5..0839bc1 100644
--- a/test/integ/control/controller.py
+++ b/test/integ/control/controller.py
@@ -420,7 +420,7 @@ class TestController(unittest.TestCase):
       self.assertEqual(expected, controller.get_conf_map([config_key], 'la-di-dah'))
 
       request_params = ['ControlPORT', 'dirport', 'datadirectory']
-      reply_params = list(controller.get_conf_map(request_params, multiple=False).keys())
+      reply_params = controller.get_conf_map(request_params, multiple=False).keys()
       self.assertEqual(set(request_params), set(reply_params))
 
       # queries an option that is unset
diff --git a/test/integ/descriptor/remote.py b/test/integ/descriptor/remote.py
index d1700a5..d1a377c 100644
--- a/test/integ/descriptor/remote.py
+++ b/test/integ/descriptor/remote.py
@@ -31,7 +31,7 @@ class TestDescriptorDownloader(unittest.TestCase):
 
     queries = []
 
-    for nickname, authority in list(stem.descriptor.remote.get_authorities().items()):
+    for nickname, authority in stem.descriptor.remote.get_authorities().items():
       queries.append((stem.descriptor.remote.Query(
         '/tor/server/fp/9695DFC35FFEB861329B9F1AB04C46397020CE31',
         'server-descriptor 1.0',
diff --git a/test/mocking.py b/test/mocking.py
index 3d6ac16..28a2e65 100644
--- a/test/mocking.py
+++ b/test/mocking.py
@@ -323,7 +323,7 @@ def _get_descriptor_content(attr = None, exclude = (), header_template = (), foo
 
   remainder = []
 
-  for k, v in list(attr.items()):
+  for k, v in attr.items():
     if v:
       remainder.append('%s %s' % (k, v))
     else:
@@ -605,7 +605,7 @@ def get_network_status_document_v3(attr = None, exclude = (), authorities = None
       'consensus-method': '9',
     }
 
-  for k, v in list(extra_defaults.items()):
+  for k, v in extra_defaults.items():
     if not (k in attr or (exclude and k in exclude)):
       attr[k] = v
 
diff --git a/test/unit/control/controller.py b/test/unit/control/controller.py
index 3dd57d3..58df2d4 100644
--- a/test/unit/control/controller.py
+++ b/test/unit/control/controller.py
@@ -585,7 +585,7 @@ class TestControl(unittest.TestCase):
         ],
     }
 
-    for test_input, expected in list(pydoc_examples.items()):
+    for test_input, expected in pydoc_examples.items():
       self.assertEqual(expected, _parse_circ_path(test_input))
 
     # exercise with some invalid inputs
diff --git a/test/unit/descriptor/networkstatus/bridge_document.py b/test/unit/descriptor/networkstatus/bridge_document.py
index 2ec2a22..1ba53e7 100644
--- a/test/unit/descriptor/networkstatus/bridge_document.py
+++ b/test/unit/descriptor/networkstatus/bridge_document.py
@@ -111,5 +111,5 @@ GM9hAsAMRX9Ogqhq5UjDNqEsvDKuyVeyh7unSZEOip9Zr6K/+7VsVPNb8vfBRBjo
     self.assertEqual(datetime.datetime(2012, 6, 1, 4, 7, 4), document.published)
 
     self.assertEqual(2, len(document.routers))
-    self.assertEqual(set(['Unnamed', 'TolFuin']), set([desc.nickname for desc in list(document.routers.values())]))
+    self.assertEqual(set(['Unnamed', 'TolFuin']), set([desc.nickname for desc in document.routers.values()]))
     self.assertEqual([], document.get_unrecognized_lines())
diff --git a/test/unit/descriptor/networkstatus/document_v3.py b/test/unit/descriptor/networkstatus/document_v3.py
index fafd455..9e6f510 100644
--- a/test/unit/descriptor/networkstatus/document_v3.py
+++ b/test/unit/descriptor/networkstatus/document_v3.py
@@ -383,7 +383,7 @@ DnN5aFtYKiTc19qIC7Nmo+afPdDEf0MlJvEOP5EWl3w=
     consensus = NetworkStatusDocumentV3(consensus_file.read())
     consensus_file.close()
 
-    for router in list(consensus.routers.values()):
+    for router in consensus.routers.values():
       self.assertEqual('caerSidi', router.nickname)
 
     # second example: using stem.descriptor.parse_file
@@ -1048,8 +1048,8 @@ DnN5aFtYKiTc19qIC7Nmo+afPdDEf0MlJvEOP5EWl3w=
 
     document = get_network_status_document_v3(routers = (entry1, entry2))
 
-    self.assertTrue(entry1 in list(document.routers.values()))
-    self.assertTrue(entry2 in list(document.routers.values()))
+    self.assertTrue(entry1 in document.routers.values())
+    self.assertTrue(entry2 in document.routers.values())
 
     # try with an invalid RouterStatusEntry
 
@@ -1082,8 +1082,8 @@ DnN5aFtYKiTc19qIC7Nmo+afPdDEf0MlJvEOP5EWl3w=
 
     document = get_network_status_document_v3({'network-status-version': '3 microdesc'}, routers = (entry1, entry2))
 
-    self.assertTrue(entry1 in list(document.routers.values()))
-    self.assertTrue(entry2 in list(document.routers.values()))
+    self.assertTrue(entry1 in document.routers.values())
+    self.assertTrue(entry2 in document.routers.values())
 
     # try with an invalid RouterStatusEntry
 
diff --git a/test/unit/descriptor/router_status_entry.py b/test/unit/descriptor/router_status_entry.py
index 603cb86..50924de 100644
--- a/test/unit/descriptor/router_status_entry.py
+++ b/test/unit/descriptor/router_status_entry.py
@@ -34,7 +34,7 @@ class TestRouterStatusEntry(unittest.TestCase):
       '/nHdqoKZ6bKZixxAPzYt9Qen+Is': 'FE71DDAA8299E9B2998B1C403F362DF507A7F88B',
     }
 
-    for arg, expected in list(test_values.items()):
+    for arg, expected in test_values.items():
       self.assertEqual(expected, _base64_to_hex(arg, True))
 
     # checks with some malformed inputs
@@ -319,7 +319,7 @@ class TestRouterStatusEntry(unittest.TestCase):
         ('2607:fcd0:daaa:101::602c:bd62', 443, True)],
     }
 
-    for a_line, expected in list(test_values.items()):
+    for a_line, expected in test_values.items():
       entry = get_router_status_entry_v3({'a': a_line})
       self.assertEqual(expected, entry.or_addresses)
 
@@ -360,7 +360,7 @@ class TestRouterStatusEntry(unittest.TestCase):
       'Ugabuga': ['Ugabuga'],
     }
 
-    for s_line, expected in list(test_values.items()):
+    for s_line, expected in test_values.items():
       entry = get_router_status_entry_v3({'s': s_line})
       self.assertEqual(expected, entry.flags)
 
@@ -371,7 +371,7 @@ class TestRouterStatusEntry(unittest.TestCase):
       'Fast Fast': [Flag.FAST, Flag.FAST],
     }
 
-    for s_line, expected in list(test_values.items()):
+    for s_line, expected in test_values.items():
       content = get_router_status_entry_v3({'s': s_line}, content = True)
       self._expect_invalid_attr(content, 'flags', expected)
 
@@ -387,7 +387,7 @@ class TestRouterStatusEntry(unittest.TestCase):
       'new_stuff and stuff': None,
     }
 
-    for v_line, expected in list(test_values.items()):
+    for v_line, expected in test_values.items():
       entry = get_router_status_entry_v3({'v': v_line})
       self.assertEqual(expected, entry.version)
       self.assertEqual(v_line, entry.version_line)
@@ -409,7 +409,7 @@ class TestRouterStatusEntry(unittest.TestCase):
       'Bandwidth=11111 Measured=482 Unmeasured=1 Blarg!': (11111, 482, True, ['Blarg!']),
     }
 
-    for w_line, expected in list(test_values.items()):
+    for w_line, expected in test_values.items():
       entry = get_router_status_entry_v3({'w': w_line})
       self.assertEqual(expected[0], entry.bandwidth)
       self.assertEqual(expected[1], entry.measured)
@@ -449,7 +449,7 @@ class TestRouterStatusEntry(unittest.TestCase):
       'accept 80,110,143,443': MicroExitPolicy('accept 80,110,143,443'),
     }
 
-    for p_line, expected in list(test_values.items()):
+    for p_line, expected in test_values.items():
       entry = get_router_status_entry_v3({'p': p_line})
       self.assertEqual(expected, entry.exit_policy)
 
@@ -484,7 +484,7 @@ class TestRouterStatusEntry(unittest.TestCase):
     setattr(mock_document, 'is_vote', True)
     setattr(mock_document, 'is_consensus', False)
 
-    for m_line, expected in list(test_values.items()):
+    for m_line, expected in test_values.items():
       content = get_router_status_entry_v3({'m': m_line}, content = True)
       entry = RouterStatusEntryV3(content, document = mock_document)
       self.assertEqual(expected, entry.microdescriptor_hashes)
diff --git a/test/unit/exit_policy/policy.py b/test/unit/exit_policy/policy.py
index 3eef79b..d4eaa75 100644
--- a/test/unit/exit_policy/policy.py
+++ b/test/unit/exit_policy/policy.py
@@ -78,7 +78,7 @@ class TestExitPolicy(unittest.TestCase):
       ('reject 127.0.0.1:*', 'accept *:80', 'reject *:*'): True,
     }
 
-    for rules, expected_result in list(test_inputs.items()):
+    for rules, expected_result in test_inputs.items():
       policy = ExitPolicy(*rules)
       self.assertEqual(expected_result, policy.is_exiting_allowed())
 
@@ -190,7 +190,7 @@ class TestExitPolicy(unittest.TestCase):
       'bar 80,443': False,
     }
 
-    for policy_arg, expect_success in list(test_inputs.items()):
+    for policy_arg, expect_success in test_inputs.items():
       try:
         policy = MicroExitPolicy(policy_arg)
 
@@ -225,10 +225,10 @@ class TestExitPolicy(unittest.TestCase):
       'reject 1-1024': {1: False, 1024: False, 1025: True},
     }
 
-    for policy_arg, attr in list(test_inputs.items()):
+    for policy_arg, attr in test_inputs.items():
       policy = MicroExitPolicy(policy_arg)
 
-      for port, expected_value in list(attr.items()):
+      for port, expected_value in attr.items():
         self.assertEqual(expected_value, policy.can_exit_to(port = port))
 
     # address argument should be ignored
@@ -261,7 +261,7 @@ class TestExitPolicy(unittest.TestCase):
       ),
     }
 
-    for test_input, expected in list(test_inputs.items()):
+    for test_input, expected in test_inputs.items():
       self.assertEqual(expected, get_config_policy(test_input, '12.34.56.78'))
 
     test_inputs = (
diff --git a/test/unit/exit_policy/rule.py b/test/unit/exit_policy/rule.py
index 39b6de9..1661442 100644
--- a/test/unit/exit_policy/rule.py
+++ b/test/unit/exit_policy/rule.py
@@ -58,7 +58,7 @@ class TestExitPolicyRule(unittest.TestCase):
       'accept [::]/128:*': 'accept [0000:0000:0000:0000:0000:0000:0000:0000]:*',
     }
 
-    for rule_arg, expected_str in list(test_inputs.items()):
+    for rule_arg, expected_str in test_inputs.items():
       rule = ExitPolicyRule(rule_arg)
       self.assertEqual(expected_str, str(rule))
 
@@ -83,7 +83,7 @@ class TestExitPolicyRule(unittest.TestCase):
       'accept 192.168.0.1:1-65534': (False, False),
     }
 
-    for rule_arg, attr in list(test_inputs.items()):
+    for rule_arg, attr in test_inputs.items():
       is_address_wildcard, is_port_wildcard = attr
 
       rule = ExitPolicyRule(rule_arg)
@@ -128,7 +128,7 @@ class TestExitPolicyRule(unittest.TestCase):
       '255.255.255.255/0': ('255.255.255.255', '0.0.0.0', 0),
     }
 
-    for rule_addr, attr in list(test_inputs.items()):
+    for rule_addr, attr in test_inputs.items():
       address, mask, masked_bits = attr
 
       rule = ExitPolicyRule('accept %s:*' % rule_addr)
@@ -167,7 +167,7 @@ class TestExitPolicyRule(unittest.TestCase):
          'FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF', 128),
     }
 
-    for rule_addr, attr in list(test_inputs.items()):
+    for rule_addr, attr in test_inputs.items():
       address, mask, masked_bits = attr
 
       rule = ExitPolicyRule('accept %s:*' % rule_addr)
@@ -199,7 +199,7 @@ class TestExitPolicyRule(unittest.TestCase):
       '80-443': (80, 443),
     }
 
-    for rule_port, attr in list(test_inputs.items()):
+    for rule_port, attr in test_inputs.items():
       min_port, max_port = attr
 
       rule = ExitPolicyRule('accept 127.0.0.1:%s' % rule_port)
@@ -246,11 +246,11 @@ class TestExitPolicyRule(unittest.TestCase):
       },
     }
 
-    for rule_arg, matches in list(test_inputs.items()):
+    for rule_arg, matches in test_inputs.items():
       rule = ExitPolicyRule(rule_arg)
       rule._submask_wildcard = False
 
-      for match_args, expected_result in list(matches.items()):
+      for match_args, expected_result in matches.items():
         self.assertEqual(expected_result, rule.is_match(*match_args))
 
     # port zero is special in that exit policies can include it, but it's not
@@ -282,10 +282,10 @@ class TestExitPolicyRule(unittest.TestCase):
       },
     }
 
-    for rule_arg, matches in list(test_inputs.items()):
+    for rule_arg, matches in test_inputs.items():
       rule = ExitPolicyRule(rule_arg)
 
-      for match_args, expected_result in list(matches.items()):
+      for match_args, expected_result in matches.items():
         self.assertEqual(expected_result, rule.is_match(*match_args))
 
   def test_is_match_ipv6(self):
@@ -313,10 +313,10 @@ class TestExitPolicyRule(unittest.TestCase):
       },
     }
 
-    for rule_arg, matches in list(test_inputs.items()):
+    for rule_arg, matches in test_inputs.items():
       rule = ExitPolicyRule(rule_arg)
 
-      for match_args, expected_result in list(matches.items()):
+      for match_args, expected_result in matches.items():
         self.assertEqual(expected_result, rule.is_match(*match_args))
 
   def test_is_match_port(self):
@@ -341,8 +341,8 @@ class TestExitPolicyRule(unittest.TestCase):
       },
     }
 
-    for rule_arg, matches in list(test_inputs.items()):
+    for rule_arg, matches in test_inputs.items():
       rule = ExitPolicyRule(rule_arg)
 
-      for match_args, expected_result in list(matches.items()):
+      for match_args, expected_result in matches.items():
         self.assertEqual(expected_result, rule.is_match(*match_args))
diff --git a/test/unit/tutorial.py b/test/unit/tutorial.py
index 98d2a1a..55a170b 100644
--- a/test/unit/tutorial.py
+++ b/test/unit/tutorial.py
@@ -227,7 +227,7 @@ class TestTutorial(unittest.TestCase):
       bw_to_relay = get_bw_to_relay()
       count = 1
 
-      for bw_value in sorted(list(bw_to_relay.keys()), reverse = True):
+      for bw_value in sorted(bw_to_relay.keys(), reverse = True):
         for nickname in bw_to_relay[bw_value]:
           print('%i. %s (%s/s)' % (count, nickname, str_tools.size_label(bw_value, 2)))
           count += 1
diff --git a/test/unit/tutorial_examples.py b/test/unit/tutorial_examples.py
index 99b4466..d1f8673 100644
--- a/test/unit/tutorial_examples.py
+++ b/test/unit/tutorial_examples.py
@@ -284,7 +284,7 @@ class TestTutorialExamples(unittest.TestCase):
       downloader = remote.DescriptorDownloader(document_handler = DocumentHandler.DOCUMENT)
       queries = {}
 
-      for name, authority in list(remote.get_authorities().items()):
+      for name, authority in remote.get_authorities().items():
         if authority.v3ident is None:
           continue  # authority doens't vote if it lacks a v3ident
 
@@ -293,14 +293,14 @@ class TestTutorialExamples(unittest.TestCase):
       # Wait for the votes to finish being downloaded, this produces a dictionary of
       # authority nicknames to their vote.
 
-      votes = dict((name, query.run()[0]) for (name, query) in list(queries.items()))
+      votes = dict((name, query.run()[0]) for (name, query) in queries.items())
 
       # Get a superset of all the fingerprints in all the votes.
 
       all_fingerprints = set()
 
-      for vote in list(votes.values()):
-        all_fingerprints.update(list(vote.routers.keys()))
+      for vote in votes.values():
+        all_fingerprints.update(vote.routers.keys())
 
       # Finally, compare moria1's votes to maatuska.
 
@@ -367,14 +367,14 @@ class TestTutorialExamples(unittest.TestCase):
       queries = {}
       downloader = remote.DescriptorDownloader()
 
-      for authority in list(remote.get_authorities().values()):
+      for authority in remote.get_authorities().values():
         if authority.is_bandwidth_authority:
           queries[authority.nickname] = downloader.query(
             '/tor/status-vote/current/authority',
             endpoints = [(authority.address, authority.dir_port)],
           )
 
-      for authority_name, query in list(queries.items()):
+      for authority_name, query in queries.items():
         try:
           print("Getting %s's vote from %s:" % (authority_name, query.download_url))
 
@@ -448,7 +448,7 @@ class TestTutorialExamples(unittest.TestCase):
         document_handler = DocumentHandler.DOCUMENT,
       ))
 
-      for fingerprint, relay in list(consensus.routers.items()):
+      for fingerprint, relay in consensus.routers.items():
         print("%s: %s" % (fingerprint, relay.nickname))
 
     network_status = get_network_status_document_v3(routers = (get_router_status_entry_v3(),))
diff --git a/test/unit/util/connection.py b/test/unit/util/connection.py
index 710122b..582e747 100644
--- a/test/unit/util/connection.py
+++ b/test/unit/util/connection.py
@@ -403,7 +403,7 @@ class TestConnection(unittest.TestCase):
       '1::1': '0001:0000:0000:0000:0000:0000:0000:0001',
     }
 
-    for test_arg, expected in list(test_values.items()):
+    for test_arg, expected in test_values.items():
       self.assertEqual(expected, stem.util.connection.expand_ipv6_address(test_arg))
 
     self.assertRaises(ValueError, stem.util.connection.expand_ipv6_address, '127.0.0.1')
@@ -462,7 +462,7 @@ class TestConnection(unittest.TestCase):
       '2001:db8::ff00:42:8329': '00100000000000010000110110111000000000000000000000000000000000000000000000000000111111110000000000000000010000101000001100101001',
     }
 
-    for test_arg, expected in list(test_values.items()):
+    for test_arg, expected in test_values.items():
       self.assertEqual(expected, stem.util.connection._get_address_binary(test_arg))
 
     self.assertRaises(ValueError, stem.util.connection._get_address_binary, '')
diff --git a/test/unit/util/str_tools.py b/test/unit/util/str_tools.py
index 1805d56..922026c 100644
--- a/test/unit/util/str_tools.py
+++ b/test/unit/util/str_tools.py
@@ -143,7 +143,7 @@ class TestStrTools(unittest.TestCase):
         datetime.datetime(2012, 11, 8, 16, 48, 41, 0),
     }
 
-    for arg, expected in list(test_inputs.items()):
+    for arg, expected in test_inputs.items():
       self.assertEqual(expected, str_tools._parse_iso_timestamp(arg))
 
     invalid_input = [
diff --git a/test/util.py b/test/util.py
index 314b5e7..714d949 100644
--- a/test/util.py
+++ b/test/util.py
@@ -141,7 +141,7 @@ def get_help_message():
   help_msg = CONFIG['msg.help']
 
   # gets the longest target length so we can show the entries in columns
-  target_name_length = max(list(map(len, Target)))
+  target_name_length = max(map(len, Target))
   description_format = '\n    %%-%is - %%s' % target_name_length
 
   for target in Target:
@@ -192,7 +192,7 @@ def get_torrc_entries(target):
     for opt in config_csv.split(','):
       opt = opt.strip()
 
-      if opt in list(test.runner.Torrc.keys()):
+      if opt in test.runner.Torrc.keys():
         torrc_opts.append(test.runner.Torrc[opt])
       else:
         raise ValueError("'%s' isn't a test.runner.Torrc enumeration" % opt)





More information about the tor-commits mailing list