Skip to content

Commit c906d40

Browse files
committed
Minor optimizations by using comprehensions
1 parent 9b9ee63 commit c906d40

18 files changed

+73
-83
lines changed

.pre-commit-config.yaml

+4-2
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,9 @@ repos:
4949
hooks:
5050
- id: ruff
5151
args: [
52-
--target-version, py37,
5352
--exclude, setup.py,
54-
--extend-ignore, "E401,E402,E701,E721,E722,E731,E741,F401,F403,F405,F821,F841"
53+
--extend-ignore, "E401,E402,E701,E721,E722,E731,E741,F401,F403,F405,F821,F841",
54+
--extend-select, "ASYNC,C4,PERF,W",
55+
# --line-length, "159",
56+
--target-version, py37,
5557
]

buildconfig/config.py

+7-9
Original file line numberDiff line numberDiff line change
@@ -71,23 +71,21 @@ def prepdep(dep, basepath):
7171
dep.found = 1
7272
return
7373

74-
incs = []
75-
lids = []
7674
IPREFIX = ' -I$(BASE)' if basepath else ' -I'
7775
LPREFIX = ' -L$(BASE)' if basepath else ' -L'
7876
startind = len(basepath) if basepath else 0
77+
incs = []
7978
if dep.inc_dir:
8079
if isinstance(dep.inc_dir, str):
81-
incs.append(IPREFIX+dep.inc_dir[startind:])
80+
incs = [IPREFIX+dep.inc_dir[startind:]]
8281
else:
83-
for dir in dep.inc_dir:
84-
incs.append(IPREFIX+dir[startind:])
82+
incs = [IPREFIX+dir[startind:] for dir in dep.inc_dir]
83+
lids = []
8584
if dep.lib_dir:
8685
if isinstance(dep.lib_dir, str):
87-
lids.append(LPREFIX+dep.lib_dir[startind:])
86+
lids = [LPREFIX+dep.lib_dir[startind:]]
8887
else:
89-
for dir in dep.lib_dir:
90-
lids.append(LPREFIX+dir[startind:])
88+
lids = [LPREFIX+dir[startind:]for dir in dep.lib_dir]
9189
libs = ''
9290
for lib in dep.libs:
9391
libs += ' -l' + lib
@@ -231,7 +229,7 @@ def main(auto=False):
231229
shutil.copyfile(setup_path, backup_path)
232230
except Exception as e:
233231
logging.error(f"Failed to backup 'Setup' file: {e}")
234-
232+
235233

236234
deps = CFG.main(**kwds, auto_config=auto)
237235
if '-conan' in sys.argv:

buildconfig/config_unix.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,7 @@ def main(auto_config=False):
143143
origincdirs = ['/include', '/include/SDL2']
144144
origlibdirs = ['/lib', '/lib64', '/X11R6/lib']
145145

146-
# If we are on a debian based system, we also need to handle
146+
# If we are on a debian based system, we also need to handle
147147
# /lib/<multiarch-tuple>
148148
# We have a few commands to get the correct <multiarch-tuple>, we try those
149149
# one by one till we get something that works

buildconfig/stubs/gen_stubs.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ def Overlay(format: int, size: Tuple[int, int]) -> NoReturn: ...
118118
for mod, items in pygame_all_imports.items():
119119
if len(items) <= 4:
120120
# try to write imports in a single line if it can fit the line limit
121-
import_items = map(lambda string: f"{string} as {string}", items)
121+
import_items = (f"{string} as {string}" for string in items)
122122
import_line = f"\nfrom {mod} import {', '.join(import_items)}"
123123
if len(import_line) <= 88:
124124
f.write(import_line)

buildconfig/stubs/pygame/sprite.pyi

+1-1
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ class DirtySprite(_SupportsDirtySprite):
8080
_layer: int
8181
def _set_visible(self, val: int) -> None: ...
8282
def _get_visible(self) -> int: ...
83-
83+
8484
class WeakDirtySprite(WeakSprite, DirtySprite):
8585
...
8686

docs/reST/ref/code_examples/cursors_module_example.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
)
1616

1717
# create a color cursor
18-
surf = pg.Surface((40, 40)) # you could also load an image
18+
surf = pg.Surface((40, 40)) # you could also load an image
1919
surf.fill((120, 50, 50)) # and use that as your surface
2020
color = pg.cursors.Cursor((20, 20), surf)
2121

examples/font_viewer.py

+4-7
Original file line numberDiff line numberDiff line change
@@ -70,14 +70,11 @@ def get_font_list(self):
7070
path = ""
7171
if len(sys.argv) > 1 and os.path.exists(sys.argv[1]):
7272
path = os.path.join(sys.argv[1], "")
73-
fonts = []
7473
if os.path.exists(path):
75-
# this list comprehension could replace the following loop
76-
# fonts = [f in os.listdir(path) if f.endswith('.ttf')]
77-
for font in os.listdir(path):
78-
if font.endswith(".ttf"):
79-
fonts.append(font)
80-
return fonts or pg.font.get_fonts(), path
74+
fonts = [font for font in os.listdir(path) if font.endswith(".ttf")]
75+
else:
76+
fonts = pg.font.get_fonts()
77+
return fonts, path
8178

8279
def render_fonts(self, text="A display of font &N"):
8380
"""

setup.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,7 @@ def spawn(self, cmd, **kwargs):
126126
distutils.ccompiler.CCompiler.spawn = spawn
127127

128128
# A (bit hacky) fix for https://github.com/pygame/pygame/issues/2613
129-
# This is due to the fact that distutils uses command line args to
129+
# This is due to the fact that distutils uses command line args to
130130
# export PyInit_* functions on windows, but those functions are already exported
131131
# and that is why compiler gives warnings
132132
from distutils.command.build_ext import build_ext
@@ -311,7 +311,7 @@ def consume_arg(name):
311311
for i, kwargs in enumerate(queue):
312312
kwargs['progress'] = f'[{i + 1}/{count}] '
313313
cythonize_one(**kwargs)
314-
314+
315315
if cython_only:
316316
sys.exit(0)
317317

@@ -467,7 +467,7 @@ def run_install_headers(self):
467467

468468
if "freetype" in e.name and sys.platform not in ("darwin", "win32"):
469469
# TODO: fix freetype issues here
470-
if sysconfig.get_config_var("MAINCC") != "clang":
470+
if sysconfig.get_config_var("MAINCC") != "clang":
471471
e.extra_compile_args.append("-Wno-error=unused-but-set-variable")
472472

473473
if "mask" in e.name and IS_MSC:

src_py/cursors.py

+2-9
Original file line numberDiff line numberDiff line change
@@ -828,17 +828,10 @@ def bitswap(num):
828828
if line.startswith(possible_starts):
829829
break
830830
data = " ".join(curs[i + 1 :]).replace("};", "").replace(",", " ")
831-
cursdata = []
832-
for x in data.split():
833-
cursdata.append(bitswap(int(x, 16)))
834-
cursdata = tuple(cursdata)
831+
cursdata = tuple(bitswap(int(x, 16)) for x in data.split())
835832
for i, line in enumerate(mask):
836833
if line.startswith(possible_starts):
837834
break
838835
data = " ".join(mask[i + 1 :]).replace("};", "").replace(",", " ")
839-
maskdata = []
840-
for x in data.split():
841-
maskdata.append(bitswap(int(x, 16)))
842-
843-
maskdata = tuple(maskdata)
836+
maskdata = tuple(bitswap(int(x, 16)) for x in data.split())
844837
return info[:2], info[2:], cursdata, maskdata

src_py/surfarray.py

+5-4
Original file line numberDiff line numberDiff line change
@@ -56,10 +56,11 @@
5656

5757

5858
# float96 not available on all numpy versions.
59-
numpy_floats = []
60-
for type_name in "float32 float64 float96".split():
61-
if hasattr(numpy, type_name):
62-
numpy_floats.append(getattr(numpy, type_name))
59+
numpy_floats = [
60+
getattr(numpy, type_name)
61+
for type_name in "float32 float64 float96".split()
62+
if hasattr(numpy, type_name)
63+
]
6364
# Added below due to deprecation of numpy.float. See issue #2814
6465
numpy_floats.append(float)
6566

src_py/sysfont.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -163,9 +163,7 @@ def _font_finder_darwin():
163163

164164
strange_root = "/System/Library/Assets/com_apple_MobileAsset_Font3"
165165
if exists(strange_root):
166-
strange_locations = os.listdir(strange_root)
167-
for loc in strange_locations:
168-
locations.append(f"{strange_root}/{loc}/AssetData")
166+
locations += [f"{strange_root}/{loc}" for loc in os.listdir(strange_root)]
169167

170168
fonts = {}
171169

@@ -240,7 +238,7 @@ def initsysfonts_unix(path="fc-list"):
240238
for entry in proc.stdout.decode("ascii", "ignore").splitlines():
241239
try:
242240
_parse_font_entry_unix(entry, fonts)
243-
except ValueError:
241+
except ValueError: # noqa: PERF203
244242
# try the next one.
245243
pass
246244

src_py/threads/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -267,5 +267,5 @@ def tmap(f, seq_args, num_workers=20, worker_queue=None, wait=True, stop_on_erro
267267
if error_ones:
268268
raise error_ones[0].exception
269269

270-
return map(lambda x: x.result, results)
270+
return (x.result for x in results)
271271
return [wq, results]

test/draw_test.py

+11-11
Original file line numberDiff line numberDiff line change
@@ -1446,7 +1446,7 @@ def test_line__invalid_start_pos_formats(self):
14461446
(2, 1, 0), # Too many coords.
14471447
(2, "1"), # Wrong type.
14481448
{2, 1}, # Wrong type.
1449-
dict(((2, 1),)),
1449+
{2: 1},
14501450
) # Wrong type.
14511451

14521452
for start_pos in start_pos_fmts:
@@ -1470,7 +1470,7 @@ def test_line__invalid_end_pos_formats(self):
14701470
(2, 1, 0), # Too many coords.
14711471
(2, "1"), # Wrong type.
14721472
{2, 1}, # Wrong type.
1473-
dict(((2, 1),)),
1473+
{2: 1},
14741474
) # Wrong type.
14751475

14761476
for end_pos in end_pos_fmts:
@@ -2122,9 +2122,9 @@ def test_lines__invalid_points_formats(self):
21222122
((1, 1), (2, 2, 2)), # Too many coords.
21232123
((1, 1), (2, "2")), # Wrong type.
21242124
((1, 1), {2, 3}), # Wrong type.
2125-
((1, 1), dict(((2, 2), (3, 3)))), # Wrong type.
2125+
((1, 1), {2: 2, 3: 3}), # Wrong type.
21262126
{(1, 1), (1, 2)}, # Wrong type.
2127-
dict(((1, 1), (4, 4))),
2127+
{1: 1, 4: 4},
21282128
) # Wrong type.
21292129

21302130
for points in points_fmts:
@@ -2715,7 +2715,7 @@ def test_aaline__invalid_start_pos_formats(self):
27152715
(2, 1, 0), # Too many coords.
27162716
(2, "1"), # Wrong type.
27172717
{2, 1}, # Wrong type.
2718-
dict(((2, 1),)),
2718+
{2: 1},
27192719
) # Wrong type.
27202720

27212721
for start_pos in start_pos_fmts:
@@ -2738,7 +2738,7 @@ def test_aaline__invalid_end_pos_formats(self):
27382738
(2, 1, 0), # Too many coords.
27392739
(2, "1"), # Wrong type.
27402740
{2, 1}, # Wrong type.
2741-
dict(((2, 1),)),
2741+
{2: 1},
27422742
) # Wrong type.
27432743

27442744
for end_pos in end_pos_fmts:
@@ -3441,9 +3441,9 @@ def test_aalines__invalid_points_formats(self):
34413441
((1, 1), (2, 2, 2)), # Too many coords.
34423442
((1, 1), (2, "2")), # Wrong type.
34433443
((1, 1), {2, 3}), # Wrong type.
3444-
((1, 1), dict(((2, 2), (3, 3)))), # Wrong type.
3444+
((1, 1), {2: 2, 3: 3}), # Wrong type.
34453445
{(1, 1), (1, 2)}, # Wrong type.
3446-
dict(((1, 1), (4, 4))),
3446+
{1: 1, 4: 4},
34473447
) # Wrong type.
34483448

34493449
for points in points_fmts:
@@ -3952,9 +3952,9 @@ def test_polygon__invalid_points_formats(self):
39523952
((1, 1), (2, 1), (2, 2, 2)), # Too many coords.
39533953
((1, 1), (2, 1), (2, "2")), # Wrong type.
39543954
((1, 1), (2, 1), {2, 3}), # Wrong type.
3955-
((1, 1), (2, 1), dict(((2, 2), (3, 3)))), # Wrong type.
3955+
((1, 1), (2, 1), {2: 2, 3: 3}), # Wrong type.
39563956
{(1, 1), (2, 1), (2, 2), (1, 2)}, # Wrong type.
3957-
dict(((1, 1), (2, 2), (3, 3), (4, 4))),
3957+
{1: 1, 2: 2, 3: 3, 4: 4},
39583958
) # Wrong type.
39593959

39603960
for points in points_fmts:
@@ -3973,7 +3973,7 @@ def test_polygon__invalid_points_values(self):
39733973
}
39743974

39753975
points_fmts = (
3976-
tuple(), # Too few points.
3976+
(), # Too few points.
39773977
((1, 1),), # Too few points.
39783978
((1, 1), (2, 1)),
39793979
) # Too few points.

test/event_test.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,9 @@
3131
{
3232
pygame.KEYDOWN: {"key": pygame.K_SPACE},
3333
pygame.KEYUP: {"key": pygame.K_SPACE},
34-
pygame.MOUSEMOTION: dict(),
35-
pygame.MOUSEBUTTONDOWN: dict(button=1),
36-
pygame.MOUSEBUTTONUP: dict(button=1),
34+
pygame.MOUSEMOTION: {},
35+
pygame.MOUSEBUTTONDOWN: {"button": 1},
36+
pygame.MOUSEBUTTONUP: {"button": 1},
3737
}
3838
)
3939

test/mouse_test.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,7 @@ def test_set_system_cursor(self):
134134
# Making sure the warnings are working properly
135135
self.assertEqual(len(w), 6)
136136
self.assertTrue(
137-
all([issubclass(warn.category, DeprecationWarning) for warn in w])
137+
all(issubclass(warn.category, DeprecationWarning) for warn in w)
138138
)
139139

140140
@unittest.skipIf(

test/test_utils/png.py

+10-10
Original file line numberDiff line numberDiff line change
@@ -746,15 +746,15 @@ def extend(sl):
746746
a.extend([0] * int(extra))
747747
# Pack into bytes
748748
l = group(a, spb)
749-
l = map(lambda e: reduce(lambda x, y: (x << self.bitdepth) + y, e), l)
749+
l = (reduce(lambda x, y: (x << self.bitdepth) + y, e) for e in l)
750750
data.extend(l)
751751

752752
if self.rescale:
753753
oldextend = extend
754754
factor = float(2 ** self.rescale[1] - 1) / float(2 ** self.rescale[0] - 1)
755755

756756
def extend(sl):
757-
oldextend(map(lambda x: int(round(factor * x)), sl))
757+
oldextend((int(round(factor * x)) for x in sl))
758758

759759
# Build the first row, testing mostly to see if we need to
760760
# changed the extend function to cope with NumPy integer types
@@ -1642,7 +1642,7 @@ def asvalues(raw):
16421642
mask = 2**self.bitdepth - 1
16431643
shifts = map(self.bitdepth.__mul__, reversed(range(spb)))
16441644
for o in raw:
1645-
out.extend(map(lambda i: mask & (o >> i), shifts))
1645+
out.extend((mask & (o >> i) for i in shifts))
16461646
return out[:width]
16471647

16481648
return map(asvalues, rows)
@@ -1941,7 +1941,7 @@ def iterdecomp(idat):
19411941
)
19421942
else:
19431943
pixels = self.iterboxed(self.iterstraight(raw))
1944-
meta = dict()
1944+
meta = {}
19451945
for attr in "greyscale alpha planes bitdepth interlace".split():
19461946
meta[attr] = getattr(self, attr)
19471947
meta["size"] = (self.width, self.height)
@@ -2128,7 +2128,7 @@ def _as_rescale(self, get, targetbitdepth):
21282128

21292129
def iterscale():
21302130
for row in pixels:
2131-
yield map(lambda x: int(round(x * factor)), row)
2131+
yield (int(round(x * factor)) for x in row)
21322132

21332133
return width, height, iterscale(), meta
21342134

@@ -2426,7 +2426,7 @@ def testPtrns(self):
24262426
d = d + (255,)
24272427
e = e + (255,)
24282428
boxed = [(e, d, c), (d, c, a), (c, a, b)]
2429-
flat = map(lambda row: itertools.chain(*row), boxed)
2429+
flat = (itertools.chain(*row) for row in boxed)
24302430
self.assertEqual(map(list, pixels), map(list, flat))
24312431

24322432
def testRGBtoRGBA(self):
@@ -2744,8 +2744,8 @@ def testfromarrayIter(self):
27442744
import itertools
27452745

27462746
i = itertools.islice(itertools.count(10), 20)
2747-
i = map(lambda x: [x, x, x], i)
2748-
img = from_array(i, "RGB;5", dict(height=20))
2747+
i = ([x, x, x] for x in i)
2748+
img = from_array(i, "RGB;5", {"height": 20})
27492749
f = open("testiter.png", "wb")
27502750
img.save(f)
27512751
f.close()
@@ -3606,7 +3606,7 @@ def read_pam_header(infile):
36063606
"""
36073607

36083608
# Unlike PBM, PGM, and PPM, we can read the header a line at a time.
3609-
header = dict()
3609+
header = {}
36103610
while True:
36113611
l = infile.readline().strip()
36123612
if l == strtobytes("ENDHDR"):
@@ -3960,7 +3960,7 @@ def _main(argv):
39603960
# care about TUPLTYPE.
39613961
greyscale = depth <= 2
39623962
pamalpha = depth in (2, 4)
3963-
supported = map(lambda x: 2**x - 1, range(1, 17))
3963+
supported = (2**x - 1 for x in range(1, 17))
39643964
try:
39653965
mi = supported.index(maxval)
39663966
except ValueError:

0 commit comments

Comments
 (0)