Skip to content

Commit 3972628

Browse files
jdufresnerhettinger
authored andcommitted
bpo-30296 Remove unnecessary tuples, lists, sets, and dicts (#1489)
* 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())
1 parent 906f533 commit 3972628

File tree

19 files changed

+32
-39
lines changed

19 files changed

+32
-39
lines changed

Lib/_weakrefset.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -157,19 +157,19 @@ def issubset(self, other):
157157
__le__ = issubset
158158

159159
def __lt__(self, other):
160-
return self.data < set(ref(item) for item in other)
160+
return self.data < set(map(ref, other))
161161

162162
def issuperset(self, other):
163163
return self.data.issuperset(ref(item) for item in other)
164164
__ge__ = issuperset
165165

166166
def __gt__(self, other):
167-
return self.data > set(ref(item) for item in other)
167+
return self.data > set(map(ref, other))
168168

169169
def __eq__(self, other):
170170
if not isinstance(other, self.__class__):
171171
return NotImplemented
172-
return self.data == set(ref(item) for item in other)
172+
return self.data == set(map(ref, other))
173173

174174
def symmetric_difference(self, other):
175175
newset = self.copy()

Lib/distutils/msvc9compiler.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -255,7 +255,7 @@ def query_vcvarsall(version, arch="x86"):
255255
"""Launch vcvarsall.bat and read the settings from its environment
256256
"""
257257
vcvarsall = find_vcvarsall(version)
258-
interesting = set(("include", "lib", "libpath", "path"))
258+
interesting = {"include", "lib", "libpath", "path"}
259259
result = {}
260260

261261
if vcvarsall is None:

Lib/email/headerregistry.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -369,8 +369,8 @@ def groups(self):
369369
@property
370370
def addresses(self):
371371
if self._addresses is None:
372-
self._addresses = tuple([address for group in self._groups
373-
for address in group.addresses])
372+
self._addresses = tuple(address for group in self._groups
373+
for address in group.addresses)
374374
return self._addresses
375375

376376

Lib/inspect.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -389,7 +389,7 @@ def classify_class_attrs(cls):
389389

390390
mro = getmro(cls)
391391
metamro = getmro(type(cls)) # for attributes stored in the metaclass
392-
metamro = tuple([cls for cls in metamro if cls not in (type, object)])
392+
metamro = tuple(cls for cls in metamro if cls not in (type, object))
393393
class_bases = (cls,) + mro
394394
all_bases = class_bases + metamro
395395
names = dir(cls)

Lib/logging/config.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -463,7 +463,7 @@ def configure_custom(self, config):
463463
c = self.resolve(c)
464464
props = config.pop('.', None)
465465
# Check for valid identifiers
466-
kwargs = dict([(k, config[k]) for k in config if valid_ident(k)])
466+
kwargs = dict((k, config[k]) for k in config if valid_ident(k))
467467
result = c(**kwargs)
468468
if props:
469469
for name, value in props.items():
@@ -726,7 +726,7 @@ def configure_handler(self, config):
726726
config['address'] = self.as_tuple(config['address'])
727727
factory = klass
728728
props = config.pop('.', None)
729-
kwargs = dict([(k, config[k]) for k in config if valid_ident(k)])
729+
kwargs = dict((k, config[k]) for k in config if valid_ident(k))
730730
try:
731731
result = factory(**kwargs)
732732
except TypeError as te:

Lib/multiprocessing/context.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -261,7 +261,7 @@ def get_all_start_methods(self):
261261
else:
262262
return ['fork', 'spawn']
263263

264-
DefaultContext.__all__ = list(x for x in dir(DefaultContext) if x[0] != '_')
264+
DefaultContext.__all__ = [x for x in dir(DefaultContext) if x[0] != '_']
265265

266266
#
267267
# Context types for fixed start method

Lib/multiprocessing/forkserver.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -98,8 +98,7 @@ def ensure_running(self):
9898
if self._preload_modules:
9999
desired_keys = {'main_path', 'sys_path'}
100100
data = spawn.get_preparation_data('ignore')
101-
data = dict((x,y) for (x,y) in data.items()
102-
if x in desired_keys)
101+
data = {x: y for x, y in data.items() if x in desired_keys}
103102
else:
104103
data = {}
105104

Lib/multiprocessing/sharedctypes.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ def synchronized(obj, lock=None, ctx=None):
115115
scls = class_cache[cls]
116116
except KeyError:
117117
names = [field[0] for field in cls._fields_]
118-
d = dict((name, make_property(name)) for name in names)
118+
d = {name: make_property(name) for name in names}
119119
classname = 'Synchronized' + cls.__name__
120120
scls = class_cache[cls] = type(classname, (SynchronizedBase,), d)
121121
return scls(obj, lock, ctx)

Lib/pathlib.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -114,10 +114,7 @@ class _WindowsFlavour(_Flavour):
114114

115115
is_supported = (os.name == 'nt')
116116

117-
drive_letters = (
118-
set(chr(x) for x in range(ord('a'), ord('z') + 1)) |
119-
set(chr(x) for x in range(ord('A'), ord('Z') + 1))
120-
)
117+
drive_letters = set('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
121118
ext_namespace_prefix = '\\\\?\\'
122119

123120
reserved_names = (

Lib/pstats.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -500,8 +500,7 @@ def add_callers(target, source):
500500
if func in new_callers:
501501
if isinstance(caller, tuple):
502502
# format used by cProfile
503-
new_callers[func] = tuple([i[0] + i[1] for i in
504-
zip(caller, new_callers[func])])
503+
new_callers[func] = tuple(i[0] + i[1] for i in zip(caller, new_callers[func]))
505504
else:
506505
# format used by profile
507506
new_callers[func] += caller

Lib/symtable.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -119,8 +119,8 @@ class Function(SymbolTable):
119119
__globals = None
120120

121121
def __idents_matching(self, test_func):
122-
return tuple([ident for ident in self.get_identifiers()
123-
if test_func(self._table.symbols[ident])])
122+
return tuple(ident for ident in self.get_identifiers()
123+
if test_func(self._table.symbols[ident]))
124124

125125
def get_parameters(self):
126126
if self.__params is None:

Lib/tokenize.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,7 @@ def _all_string_prefixes():
142142
# 'rf'). The various permutations will be generated.
143143
_valid_string_prefixes = ['b', 'r', 'u', 'f', 'br', 'fr']
144144
# if we add binary f-strings, add: ['fb', 'fbr']
145-
result = set([''])
145+
result = {''}
146146
for prefix in _valid_string_prefixes:
147147
for t in _itertools.permutations(prefix):
148148
# create a list with upper and lower versions of each

Lib/traceback.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -253,8 +253,7 @@ def __init__(self, filename, lineno, name, *, lookup_line=True,
253253
self._line = line
254254
if lookup_line:
255255
self.line
256-
self.locals = \
257-
dict((k, repr(v)) for k, v in locals.items()) if locals else None
256+
self.locals = {k: repr(v) for k, v in locals.items()} if locals else None
258257

259258
def __eq__(self, other):
260259
if isinstance(other, FrameSummary):

Lib/turtle.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1175,7 +1175,7 @@ def _color(self, cstr):
11751175
cl = [16*int(cstr[h], 16) for h in cstr[1:]]
11761176
else:
11771177
raise TurtleGraphicsError("bad colorstring: %s" % cstr)
1178-
return tuple([c * self._colormode/255 for c in cl])
1178+
return tuple(c * self._colormode/255 for c in cl)
11791179

11801180
def colormode(self, cmode=None):
11811181
"""Return the colormode or set it to 1.0 or 255.
@@ -2989,7 +2989,7 @@ def _getshapepoly(self, polygon, compound=False):
29892989
t11, t12, t21, t22 = l, 0, 0, l
29902990
elif self._resizemode == "noresize":
29912991
return polygon
2992-
return tuple([(t11*x + t12*y, t21*x + t22*y) for (x, y) in polygon])
2992+
return tuple((t11*x + t12*y, t21*x + t22*y) for (x, y) in polygon)
29932993

29942994
def _drawturtle(self):
29952995
"""Manages the correct rendering of the turtle with respect to
@@ -3839,8 +3839,8 @@ def write_docstringdict(filename="turtle_docstringdict"):
38393839
docsdict[key] = eval(key).__doc__
38403840

38413841
with open("%s.py" % filename,"w") as f:
3842-
keys = sorted([x for x in docsdict.keys()
3843-
if x.split('.')[1] not in _alias_list])
3842+
keys = sorted(x for x in docsdict.keys()
3843+
if x.split('.')[1] not in _alias_list)
38443844
f.write('docsdict = {\n\n')
38453845
for key in keys[:-1]:
38463846
f.write('%s :\n' % repr(key))

Lib/turtledemo/wikipedia.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ def main():
5252
sleep(1)
5353

5454
at = clock()
55-
while any([t.undobufferentries() for t in s.turtles()]):
55+
while any(t.undobufferentries() for t in s.turtles()):
5656
for t in s.turtles():
5757
t.undo()
5858
et = clock()

Lib/urllib/request.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -683,8 +683,8 @@ def redirect_request(self, req, fp, code, msg, headers, newurl):
683683
newurl = newurl.replace(' ', '%20')
684684

685685
CONTENT_HEADERS = ("content-length", "content-type")
686-
newheaders = dict((k, v) for k, v in req.headers.items()
687-
if k.lower() not in CONTENT_HEADERS)
686+
newheaders = {k: v for k, v in req.headers.items()
687+
if k.lower() not in CONTENT_HEADERS}
688688
return Request(newurl,
689689
headers=newheaders,
690690
origin_req_host=req.origin_req_host,
@@ -845,7 +845,7 @@ def add_password(self, realm, uri, user, passwd):
845845
self.passwd[realm] = {}
846846
for default_port in True, False:
847847
reduced_uri = tuple(
848-
[self.reduce_uri(u, default_port) for u in uri])
848+
self.reduce_uri(u, default_port) for u in uri)
849849
self.passwd[realm][reduced_uri] = (user, passwd)
850850

851851
def find_user_password(self, realm, authuri):
@@ -1286,8 +1286,7 @@ def do_open(self, http_class, req, **http_conn_args):
12861286
h.set_debuglevel(self._debuglevel)
12871287

12881288
headers = dict(req.unredirected_hdrs)
1289-
headers.update(dict((k, v) for k, v in req.headers.items()
1290-
if k not in headers))
1289+
headers.update((k, v) for k, v in req.headers.items() if k not in headers)
12911290

12921291
# TODO(jhylton): Should this be redesigned to handle
12931292
# persistent connections?
@@ -1299,7 +1298,7 @@ def do_open(self, http_class, req, **http_conn_args):
12991298
# So make sure the connection gets closed after the (only)
13001299
# request.
13011300
headers["Connection"] = "close"
1302-
headers = dict((name.title(), val) for name, val in headers.items())
1301+
headers = {name.title(): val for name, val in headers.items()}
13031302

13041303
if req._tunnel_host:
13051304
tunnel_headers = {}

Tools/gdb/libpython.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1097,8 +1097,8 @@ def proxyval(self, visited):
10971097
return ProxyAlreadyVisited('(...)')
10981098
visited.add(self.as_address())
10991099

1100-
result = tuple([PyObjectPtr.from_pyobject_ptr(self[i]).proxyval(visited)
1101-
for i in safe_range(int_from_int(self.field('ob_size')))])
1100+
result = tuple(PyObjectPtr.from_pyobject_ptr(self[i]).proxyval(visited)
1101+
for i in safe_range(int_from_int(self.field('ob_size'))))
11021102
return result
11031103

11041104
def write_repr(self, out, visited):

Tools/scripts/byext.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ def report(self):
8383
columns.update(self.stats[ext])
8484
cols = sorted(columns)
8585
colwidth = {}
86-
colwidth["ext"] = max([len(ext) for ext in exts])
86+
colwidth["ext"] = max(map(len, exts))
8787
minwidth = 6
8888
self.stats["TOTAL"] = {}
8989
for col in cols:

Tools/unicode/makeunicodedata.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -609,7 +609,7 @@ def makeunicodename(unicode, trace):
609609
if name and name[0] != "<":
610610
names[char] = name + chr(0)
611611

612-
print(len(list(n for n in names if n is not None)), "distinct names")
612+
print(len([n for n in names if n is not None]), "distinct names")
613613

614614
# collect unique words from names (note that we differ between
615615
# words inside a sentence, and words ending a sentence. the

0 commit comments

Comments
 (0)