]> granicus.if.org Git - python/commitdiff
bpo-30296 Remove unnecessary tuples, lists, sets, and dicts (#1489)
authorJon Dufresne <jon.dufresne@gmail.com>
Thu, 18 May 2017 14:35:54 +0000 (07:35 -0700)
committerRaymond Hettinger <rhettinger@users.noreply.github.com>
Thu, 18 May 2017 14:35:54 +0000 (07:35 -0700)
* Replaced list(<generator expression>) with list comprehension
* Replaced dict(<generator expression>) with dict comprehension
* Replaced set(<list literal>) with set literal
* Replaced builtin func(<list comprehension>) with func(<generator
  expression>) when supported (e.g. any(), all(), tuple(), min(), &
  max())

19 files changed:
Lib/_weakrefset.py
Lib/distutils/msvc9compiler.py
Lib/email/headerregistry.py
Lib/inspect.py
Lib/logging/config.py
Lib/multiprocessing/context.py
Lib/multiprocessing/forkserver.py
Lib/multiprocessing/sharedctypes.py
Lib/pathlib.py
Lib/pstats.py
Lib/symtable.py
Lib/tokenize.py
Lib/traceback.py
Lib/turtle.py
Lib/turtledemo/wikipedia.py
Lib/urllib/request.py
Tools/gdb/libpython.py
Tools/scripts/byext.py
Tools/unicode/makeunicodedata.py

index 4d0de8ce753ab4f984bcedc91cb1712ef9e1f137..304c66f59bd1be7aa36bd1eb0d8f65c6932751be 100644 (file)
@@ -157,19 +157,19 @@ class WeakSet:
     __le__ = issubset
 
     def __lt__(self, other):
-        return self.data < set(ref(item) for item in other)
+        return self.data < set(map(ref, other))
 
     def issuperset(self, other):
         return self.data.issuperset(ref(item) for item in other)
     __ge__ = issuperset
 
     def __gt__(self, other):
-        return self.data > set(ref(item) for item in other)
+        return self.data > set(map(ref, other))
 
     def __eq__(self, other):
         if not isinstance(other, self.__class__):
             return NotImplemented
-        return self.data == set(ref(item) for item in other)
+        return self.data == set(map(ref, other))
 
     def symmetric_difference(self, other):
         newset = self.copy()
index 21191276227ec5e98f83163c51e48476e2106955..c401ddc86eb9198f02c8935edc3254ec1f09dc1d 100644 (file)
@@ -255,7 +255,7 @@ def query_vcvarsall(version, arch="x86"):
     """Launch vcvarsall.bat and read the settings from its environment
     """
     vcvarsall = find_vcvarsall(version)
-    interesting = set(("include", "lib", "libpath", "path"))
+    interesting = {"include", "lib", "libpath", "path"}
     result = {}
 
     if vcvarsall is None:
index 0fc2231e5cbd2949033523b101bfd493ed440537..81fee146dcc3575b693a3439c1689907a04e048a 100644 (file)
@@ -369,8 +369,8 @@ class AddressHeader:
     @property
     def addresses(self):
         if self._addresses is None:
-            self._addresses = tuple([address for group in self._groups
-                                             for address in group.addresses])
+            self._addresses = tuple(address for group in self._groups
+                                            for address in group.addresses)
         return self._addresses
 
 
index 3317f58f475dc80f0624ca75ff55cdcf9c036938..9c072eb0747fbd10052383a8f04d5434c4be7727 100644 (file)
@@ -389,7 +389,7 @@ def classify_class_attrs(cls):
 
     mro = getmro(cls)
     metamro = getmro(type(cls)) # for attributes stored in the metaclass
-    metamro = tuple([cls for cls in metamro if cls not in (type, object)])
+    metamro = tuple(cls for cls in metamro if cls not in (type, object))
     class_bases = (cls,) + mro
     all_bases = class_bases + metamro
     names = dir(cls)
index 917178e5118c36e06bbb80edc86808aa24a27e2d..d692514adfef5b69ae75ed14ce64259ce0d6e1a4 100644 (file)
@@ -463,7 +463,7 @@ class BaseConfigurator(object):
             c = self.resolve(c)
         props = config.pop('.', None)
         # Check for valid identifiers
-        kwargs = dict([(k, config[k]) for k in config if valid_ident(k)])
+        kwargs = dict((k, config[k]) for k in config if valid_ident(k))
         result = c(**kwargs)
         if props:
             for name, value in props.items():
@@ -726,7 +726,7 @@ class DictConfigurator(BaseConfigurator):
                 config['address'] = self.as_tuple(config['address'])
             factory = klass
         props = config.pop('.', None)
-        kwargs = dict([(k, config[k]) for k in config if valid_ident(k)])
+        kwargs = dict((k, config[k]) for k in config if valid_ident(k))
         try:
             result = factory(**kwargs)
         except TypeError as te:
index a3d491bde5a7dda63bf43d63acca8ca45dd6742d..c98ee4342490373c2ef4a896d040d61093c7756c 100644 (file)
@@ -261,7 +261,7 @@ class DefaultContext(BaseContext):
             else:
                 return ['fork', 'spawn']
 
-DefaultContext.__all__ = list(x for x in dir(DefaultContext) if x[0] != '_')
+DefaultContext.__all__ = [x for x in dir(DefaultContext) if x[0] != '_']
 
 #
 # Context types for fixed start method
index d5ce6257456766123080f16379eb21e249a82ff6..6e095399936e7ea9860fee351fc3d126529a425d 100644 (file)
@@ -98,8 +98,7 @@ class ForkServer(object):
             if self._preload_modules:
                 desired_keys = {'main_path', 'sys_path'}
                 data = spawn.get_preparation_data('ignore')
-                data = dict((x,y) for (x,y) in data.items()
-                            if x in desired_keys)
+                data = {x: y for x, y in data.items() if x in desired_keys}
             else:
                 data = {}
 
index 25cbcf2ae4cd6f89fb46f3187a51994dd48a8bff..7228751770f73ceeb7c5d3f931b3aa45059e17f8 100644 (file)
@@ -115,7 +115,7 @@ def synchronized(obj, lock=None, ctx=None):
             scls = class_cache[cls]
         except KeyError:
             names = [field[0] for field in cls._fields_]
-            d = dict((name, make_property(name)) for name in names)
+            d = {name: make_property(name) for name in names}
             classname = 'Synchronized' + cls.__name__
             scls = class_cache[cls] = type(classname, (SynchronizedBase,), d)
         return scls(obj, lock, ctx)
index 4368eba8a0efe056a1750dc736abf0fffe813797..4d89436f775c757fa1719d55df28d818087f2d43 100644 (file)
@@ -114,10 +114,7 @@ class _WindowsFlavour(_Flavour):
 
     is_supported = (os.name == 'nt')
 
-    drive_letters = (
-        set(chr(x) for x in range(ord('a'), ord('z') + 1)) |
-        set(chr(x) for x in range(ord('A'), ord('Z') + 1))
-    )
+    drive_letters = set('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
     ext_namespace_prefix = '\\\\?\\'
 
     reserved_names = (
index b8bcfb23a5f3fbd2d45b3a2da030d6f177b32a60..b7a20542a3994bef0fccb4b8b888d79d78a01afa 100644 (file)
@@ -500,8 +500,7 @@ def add_callers(target, source):
         if func in new_callers:
             if isinstance(caller, tuple):
                 # format used by cProfile
-                new_callers[func] = tuple([i[0] + i[1] for i in
-                                           zip(caller, new_callers[func])])
+                new_callers[func] = tuple(i[0] + i[1] for i in zip(caller, new_callers[func]))
             else:
                 # format used by profile
                 new_callers[func] += caller
index b0e52603dceeb170581fa93f80fecac07089ffc2..c7627a6ef68856a68a87a3c19942461e8dcc9cff 100644 (file)
@@ -119,8 +119,8 @@ class Function(SymbolTable):
     __globals = None
 
     def __idents_matching(self, test_func):
-        return tuple([ident for ident in self.get_identifiers()
-                      if test_func(self._table.symbols[ident])])
+        return tuple(ident for ident in self.get_identifiers()
+                     if test_func(self._table.symbols[ident]))
 
     def get_parameters(self):
         if self.__params is None:
index eea88b7d432a0f25e84744941d48d23e1aa0c495..634662da265d3126b8bb92c9b9ca0485f519dabb 100644 (file)
@@ -142,7 +142,7 @@ def _all_string_prefixes():
     #  'rf'). The various permutations will be generated.
     _valid_string_prefixes = ['b', 'r', 'u', 'f', 'br', 'fr']
     # if we add binary f-strings, add: ['fb', 'fbr']
-    result = set([''])
+    result = {''}
     for prefix in _valid_string_prefixes:
         for t in _itertools.permutations(prefix):
             # create a list with upper and lower versions of each
index 09bda717ad04768c73ed1d23d799aaa50f031b82..fb3bce12a131f76c50074668be12124fc386b672 100644 (file)
@@ -253,8 +253,7 @@ class FrameSummary:
         self._line = line
         if lookup_line:
             self.line
-        self.locals = \
-            dict((k, repr(v)) for k, v in locals.items()) if locals else None
+        self.locals = {k: repr(v) for k, v in locals.items()} if locals else None
 
     def __eq__(self, other):
         if isinstance(other, FrameSummary):
index 8036b7faaa8281a48a338339d430711c9f4b5fcb..b2623f16725d5eedaf30d49d1cd2909dceb6aad7 100644 (file)
@@ -1175,7 +1175,7 @@ class TurtleScreen(TurtleScreenBase):
             cl = [16*int(cstr[h], 16) for h in cstr[1:]]
         else:
             raise TurtleGraphicsError("bad colorstring: %s" % cstr)
-        return tuple([c * self._colormode/255 for c in cl])
+        return tuple(c * self._colormode/255 for c in cl)
 
     def colormode(self, cmode=None):
         """Return the colormode or set it to 1.0 or 255.
@@ -2989,7 +2989,7 @@ class RawTurtle(TPen, TNavigator):
             t11, t12, t21, t22 = l, 0, 0, l
         elif self._resizemode == "noresize":
             return polygon
-        return tuple([(t11*x + t12*y, t21*x + t22*y) for (x, y) in polygon])
+        return tuple((t11*x + t12*y, t21*x + t22*y) for (x, y) in polygon)
 
     def _drawturtle(self):
         """Manages the correct rendering of the turtle with respect to
@@ -3839,8 +3839,8 @@ def write_docstringdict(filename="turtle_docstringdict"):
         docsdict[key] = eval(key).__doc__
 
     with open("%s.py" % filename,"w") as f:
-        keys = sorted([x for x in docsdict.keys()
-                            if x.split('.')[1] not in _alias_list])
+        keys = sorted(x for x in docsdict.keys()
+                      if x.split('.')[1] not in _alias_list)
         f.write('docsdict = {\n\n')
         for key in keys[:-1]:
             f.write('%s :\n' % repr(key))
index 0f274420c8f71b1c1a39e99e30187cadb247194a..d6bbad892db363fbecd4ccbf95c9064d83a8d8d6 100644 (file)
@@ -52,7 +52,7 @@ def main():
     sleep(1)
 
     at = clock()
-    while any([t.undobufferentries() for t in s.turtles()]):
+    while any(t.undobufferentries() for t in s.turtles()):
         for t in s.turtles():
             t.undo()
     et = clock()
index 3f8dcfb151d744ec1a278ceb35592bf8cc96bbdf..a192d527d8bc9a4fac7e46c77041e3aa9da35b1a 100644 (file)
@@ -683,8 +683,8 @@ class HTTPRedirectHandler(BaseHandler):
         newurl = newurl.replace(' ', '%20')
 
         CONTENT_HEADERS = ("content-length", "content-type")
-        newheaders = dict((k, v) for k, v in req.headers.items()
-                          if k.lower() not in CONTENT_HEADERS)
+        newheaders = {k: v for k, v in req.headers.items()
+                      if k.lower() not in CONTENT_HEADERS}
         return Request(newurl,
                        headers=newheaders,
                        origin_req_host=req.origin_req_host,
@@ -845,7 +845,7 @@ class HTTPPasswordMgr:
             self.passwd[realm] = {}
         for default_port in True, False:
             reduced_uri = tuple(
-                [self.reduce_uri(u, default_port) for u in uri])
+                self.reduce_uri(u, default_port) for u in uri)
             self.passwd[realm][reduced_uri] = (user, passwd)
 
     def find_user_password(self, realm, authuri):
@@ -1286,8 +1286,7 @@ class AbstractHTTPHandler(BaseHandler):
         h.set_debuglevel(self._debuglevel)
 
         headers = dict(req.unredirected_hdrs)
-        headers.update(dict((k, v) for k, v in req.headers.items()
-                            if k not in headers))
+        headers.update((k, v) for k, v in req.headers.items() if k not in headers)
 
         # TODO(jhylton): Should this be redesigned to handle
         # persistent connections?
@@ -1299,7 +1298,7 @@ class AbstractHTTPHandler(BaseHandler):
         # So make sure the connection gets closed after the (only)
         # request.
         headers["Connection"] = "close"
-        headers = dict((name.title(), val) for name, val in headers.items())
+        headers = {name.title(): val for name, val in headers.items()}
 
         if req._tunnel_host:
             tunnel_headers = {}
index 0e9df2bd52f1f4fd0c75c02fad7e226260c5b3c9..cc23b8402df9d5586837290e7691bc82a78ab49d 100755 (executable)
@@ -1097,8 +1097,8 @@ class PyTupleObjectPtr(PyObjectPtr):
             return ProxyAlreadyVisited('(...)')
         visited.add(self.as_address())
 
-        result = tuple([PyObjectPtr.from_pyobject_ptr(self[i]).proxyval(visited)
-                        for i in safe_range(int_from_int(self.field('ob_size')))])
+        result = tuple(PyObjectPtr.from_pyobject_ptr(self[i]).proxyval(visited)
+                       for i in safe_range(int_from_int(self.field('ob_size'))))
         return result
 
     def write_repr(self, out, visited):
index 736a441761fd8548aea14eed82efe59969c8e02e..a4b2f7ff6d828b2697fb75f60dbdce8b1ef1dc63 100755 (executable)
@@ -83,7 +83,7 @@ class Stats:
             columns.update(self.stats[ext])
         cols = sorted(columns)
         colwidth = {}
-        colwidth["ext"] = max([len(ext) for ext in exts])
+        colwidth["ext"] = max(map(len, exts))
         minwidth = 6
         self.stats["TOTAL"] = {}
         for col in cols:
index 5d8014a5da3afe1432a7bfec899267d0bdf4e4ee..472324fdefa02536577f2fffc111cfbeb10805e5 100644 (file)
@@ -609,7 +609,7 @@ def makeunicodename(unicode, trace):
             if name and name[0] != "<":
                 names[char] = name + chr(0)
 
-    print(len(list(n for n in names if n is not None)), "distinct names")
+    print(len([n for n in names if n is not None]), "distinct names")
 
     # collect unique words from names (note that we differ between
     # words inside a sentence, and words ending a sentence.  the