Skip to content

Commit 53d5ac2

Browse files
authored
Merge pull request #4379 from DimitriPapadopoulos/UP
Enforce ruff/pyupgrade rules (UP)
2 parents 9ffbeb2 + f65ea5b commit 53d5ac2

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

41 files changed

+227
-270
lines changed

docs/userguide/extension.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ a non-``None`` value. Here's an example validation function::
122122
"""Verify that value is True, False, 0, or 1"""
123123
if bool(value) != value:
124124
raise SetupError(
125-
"%r must be a boolean value (got %r)" % (attr,value)
125+
f"{attr!r} must be a boolean value (got {value!r}"
126126
)
127127

128128
Your function should accept three arguments: the ``Distribution`` object,

pkg_resources/__init__.py

+25-34
Original file line numberDiff line numberDiff line change
@@ -200,7 +200,9 @@ def get_supported_platform():
200200
m = macosVersionString.match(plat)
201201
if m is not None and sys.platform == "darwin":
202202
try:
203-
plat = 'macosx-%s-%s' % ('.'.join(_macos_vers()[:2]), m.group(3))
203+
major_minor = '.'.join(_macos_vers()[:2])
204+
build = m.group(3)
205+
plat = f'macosx-{major_minor}-{build}'
204206
except ValueError:
205207
# not macOS
206208
pass
@@ -449,12 +451,8 @@ def get_build_platform():
449451
if sys.platform == "darwin" and not plat.startswith('macosx-'):
450452
try:
451453
version = _macos_vers()
452-
machine = os.uname()[4].replace(" ", "_")
453-
return "macosx-%d.%d-%s" % (
454-
int(version[0]),
455-
int(version[1]),
456-
_macos_arch(machine),
457-
)
454+
machine = _macos_arch(os.uname()[4].replace(" ", "_"))
455+
return f"macosx-{version[0]}.{version[1]}-{machine}"
458456
except ValueError:
459457
# if someone is running a non-Mac darwin system, this will fall
460458
# through to the default implementation
@@ -492,7 +490,7 @@ def compatible_platforms(provided: str | None, required: str | None) -> bool:
492490
provDarwin = darwinVersionString.match(provided)
493491
if provDarwin:
494492
dversion = int(provDarwin.group(1))
495-
macosversion = "%s.%s" % (reqMac.group(1), reqMac.group(2))
493+
macosversion = f"{reqMac.group(1)}.{reqMac.group(2)}"
496494
if (
497495
dversion == 7
498496
and macosversion >= "10.3"
@@ -1316,7 +1314,7 @@ def __iadd__(self, other: Distribution | Environment) -> Self:
13161314
for dist in other[project]:
13171315
self.add(dist)
13181316
else:
1319-
raise TypeError("Can't add %r to environment" % (other,))
1317+
raise TypeError(f"Can't add {other!r} to environment")
13201318
return self
13211319

13221320
def __add__(self, other: Distribution | Environment) -> Self:
@@ -1699,7 +1697,7 @@ def get_metadata(self, name: str) -> str:
16991697
except UnicodeDecodeError as exc:
17001698
# Include the path in the error message to simplify
17011699
# troubleshooting, and without changing the exception type.
1702-
exc.reason += ' in {} file at path: {}'.format(name, path)
1700+
exc.reason += f' in {name} file at path: {path}'
17031701
raise
17041702

17051703
def get_metadata_lines(self, name: str) -> Iterator[str]:
@@ -2018,15 +2016,15 @@ def _zipinfo_name(self, fspath):
20182016
return ''
20192017
if fspath.startswith(self.zip_pre):
20202018
return fspath[len(self.zip_pre) :]
2021-
raise AssertionError("%s is not a subpath of %s" % (fspath, self.zip_pre))
2019+
raise AssertionError(f"{fspath} is not a subpath of {self.zip_pre}")
20222020

20232021
def _parts(self, zip_path):
20242022
# Convert a zipfile subpath into an egg-relative path part list.
20252023
# pseudo-fs path
20262024
fspath = self.zip_pre + zip_path
20272025
if fspath.startswith(self.egg_root + os.sep):
20282026
return fspath[len(self.egg_root) + 1 :].split(os.sep)
2029-
raise AssertionError("%s is not a subpath of %s" % (fspath, self.egg_root))
2027+
raise AssertionError(f"{fspath} is not a subpath of {self.egg_root}")
20302028

20312029
@property
20322030
def zipinfo(self):
@@ -2729,15 +2727,16 @@ def __init__(
27292727
self.dist = dist
27302728

27312729
def __str__(self) -> str:
2732-
s = "%s = %s" % (self.name, self.module_name)
2730+
s = f"{self.name} = {self.module_name}"
27332731
if self.attrs:
27342732
s += ':' + '.'.join(self.attrs)
27352733
if self.extras:
2736-
s += ' [%s]' % ','.join(self.extras)
2734+
extras = ','.join(self.extras)
2735+
s += f' [{extras}]'
27372736
return s
27382737

27392738
def __repr__(self) -> str:
2740-
return "EntryPoint.parse(%r)" % str(self)
2739+
return f"EntryPoint.parse({str(self)!r})"
27412740

27422741
@overload
27432742
def load(
@@ -3049,9 +3048,7 @@ def version(self):
30493048
version = self._get_version()
30503049
if version is None:
30513050
path = self._get_metadata_path_for_display(self.PKG_INFO)
3052-
msg = ("Missing 'Version:' header and/or {} file at path: {}").format(
3053-
self.PKG_INFO, path
3054-
)
3051+
msg = f"Missing 'Version:' header and/or {self.PKG_INFO} file at path: {path}"
30553052
raise ValueError(msg, self) from e
30563053

30573054
return version
@@ -3107,9 +3104,7 @@ def requires(self, extras: Iterable[str] = ()) -> list[Requirement]:
31073104
try:
31083105
deps.extend(dm[safe_extra(ext)])
31093106
except KeyError as e:
3110-
raise UnknownExtra(
3111-
"%s has no such extra feature %r" % (self, ext)
3112-
) from e
3107+
raise UnknownExtra(f"{self} has no such extra feature {ext!r}") from e
31133108
return deps
31143109

31153110
def _get_metadata_path_for_display(self, name):
@@ -3150,19 +3145,15 @@ def activate(self, path: list[str] | None = None, replace: bool = False) -> None
31503145

31513146
def egg_name(self):
31523147
"""Return what this distribution's standard .egg filename should be"""
3153-
filename = "%s-%s-py%s" % (
3154-
to_filename(self.project_name),
3155-
to_filename(self.version),
3156-
self.py_version or PY_MAJOR,
3157-
)
3148+
filename = f"{to_filename(self.project_name)}-{to_filename(self.version)}-py{self.py_version or PY_MAJOR}"
31583149

31593150
if self.platform:
31603151
filename += '-' + self.platform
31613152
return filename
31623153

31633154
def __repr__(self) -> str:
31643155
if self.location:
3165-
return "%s (%s)" % (self, self.location)
3156+
return f"{self} ({self.location})"
31663157
else:
31673158
return str(self)
31683159

@@ -3172,7 +3163,7 @@ def __str__(self) -> str:
31723163
except ValueError:
31733164
version = None
31743165
version = version or "[unknown version]"
3175-
return "%s %s" % (self.project_name, version)
3166+
return f"{self.project_name} {version}"
31763167

31773168
def __getattr__(self, attr: str):
31783169
"""Delegate all unrecognized public attributes to .metadata provider"""
@@ -3200,17 +3191,17 @@ def from_filename(
32003191
def as_requirement(self):
32013192
"""Return a ``Requirement`` that matches this distribution exactly"""
32023193
if isinstance(self.parsed_version, packaging.version.Version):
3203-
spec = "%s==%s" % (self.project_name, self.parsed_version)
3194+
spec = f"{self.project_name}=={self.parsed_version}"
32043195
else:
3205-
spec = "%s===%s" % (self.project_name, self.parsed_version)
3196+
spec = f"{self.project_name}==={self.parsed_version}"
32063197

32073198
return Requirement.parse(spec)
32083199

32093200
def load_entry_point(self, group: str, name: str) -> _ResolvedEntryPoint:
32103201
"""Return the `name` entry point of `group` or raise ImportError"""
32113202
ep = self.get_entry_info(group, name)
32123203
if ep is None:
3213-
raise ImportError("Entry point %r not found" % ((group, name),))
3204+
raise ImportError(f"Entry point {(group, name)!r} not found")
32143205
return ep.load()
32153206

32163207
@overload
@@ -3327,8 +3318,8 @@ def check_version_conflict(self):
33273318
):
33283319
continue
33293320
issue_warning(
3330-
"Module %s was already imported from %s, but %s is being added"
3331-
" to sys.path" % (modname, fn, self.location),
3321+
f"Module {modname} was already imported from {fn}, "
3322+
f"but {self.location} is being added to sys.path",
33323323
)
33333324

33343325
def has_version(self) -> bool:
@@ -3512,7 +3503,7 @@ def __hash__(self) -> int:
35123503
return self.__hash
35133504

35143505
def __repr__(self) -> str:
3515-
return "Requirement.parse(%r)" % str(self)
3506+
return f"Requirement.parse({str(self)!r})"
35163507

35173508
@staticmethod
35183509
def parse(s: str | Iterable[str]) -> Requirement:

pkg_resources/tests/test_pkg_resources.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -214,8 +214,8 @@ def test_get_metadata__bad_utf8(tmpdir):
214214
"codec can't decode byte 0xe9 in position 1: "
215215
'invalid continuation byte in METADATA file at path: '
216216
)
217-
assert expected in actual, 'actual: {}'.format(actual)
218-
assert actual.endswith(metadata_path), 'actual: {}'.format(actual)
217+
assert expected in actual, f'actual: {actual}'
218+
assert actual.endswith(metadata_path), f'actual: {actual}'
219219

220220

221221
def make_distribution_no_version(tmpdir, basename):
@@ -252,11 +252,11 @@ def test_distribution_version_missing(
252252
"""
253253
Test Distribution.version when the "Version" header is missing.
254254
"""
255-
basename = 'foo.{}'.format(suffix)
255+
basename = f'foo.{suffix}'
256256
dist, dist_dir = make_distribution_no_version(tmpdir, basename)
257257

258-
expected_text = ("Missing 'Version:' header and/or {} file at path: ").format(
259-
expected_filename
258+
expected_text = (
259+
f"Missing 'Version:' header and/or {expected_filename} file at path: "
260260
)
261261
metadata_path = os.path.join(dist_dir, expected_filename)
262262

ruff.toml

-3
Original file line numberDiff line numberDiff line change
@@ -35,9 +35,6 @@ ignore = [
3535
"TRY003", # raise-vanilla-args, avoid multitude of exception classes
3636
"TRY301", # raise-within-try, it's handy
3737
"UP015", # redundant-open-modes, explicit is preferred
38-
"UP030", # temporarily disabled
39-
"UP031", # temporarily disabled
40-
"UP032", # temporarily disabled
4138
"UP038", # Using `X | Y` in `isinstance` call is slower and more verbose https://github.com/astral-sh/ruff/issues/7871
4239
# Only enforcing return type annotations for public functions
4340
"ANN202", # missing-return-type-private-function

setuptools/__init__.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -181,9 +181,7 @@ def _ensure_stringlike(self, option, what, default=None):
181181
setattr(self, option, default)
182182
return default
183183
elif not isinstance(val, str):
184-
raise DistutilsOptionError(
185-
"'%s' must be a %s (got `%s`)" % (option, what, val)
186-
)
184+
raise DistutilsOptionError(f"'{option}' must be a {what} (got `{val}`)")
187185
return val
188186

189187
def ensure_string_list(self, option: str) -> None:
@@ -210,7 +208,7 @@ def ensure_string_list(self, option: str) -> None:
210208
ok = False
211209
if not ok:
212210
raise DistutilsOptionError(
213-
"'%s' must be a list of strings (got %r)" % (option, val)
211+
f"'{option}' must be a list of strings (got {val!r})"
214212
)
215213

216214
@overload

setuptools/_core_metadata.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,7 @@ def write_pkg_file(self, file): # noqa: C901 # is too complex (14) # FIXME
150150
version = self.get_metadata_version()
151151

152152
def write_field(key, value):
153-
file.write("%s: %s\n" % (key, value))
153+
file.write(f"{key}: {value}\n")
154154

155155
write_field('Metadata-Version', str(version))
156156
write_field('Name', self.get_name())
@@ -178,8 +178,8 @@ def write_field(key, value):
178178
if license:
179179
write_field('License', rfc822_escape(license))
180180

181-
for project_url in self.project_urls.items():
182-
write_field('Project-URL', '%s, %s' % project_url)
181+
for label, url in self.project_urls.items():
182+
write_field('Project-URL', f'{label}, {url}')
183183

184184
keywords = ','.join(self.get_keywords())
185185
if keywords:
@@ -209,7 +209,7 @@ def write_field(key, value):
209209

210210
long_description = self.get_long_description()
211211
if long_description:
212-
file.write("\n%s" % long_description)
212+
file.write(f"\n{long_description}")
213213
if not long_description.endswith("\n"):
214214
file.write("\n")
215215

setuptools/_imp.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ def find_module(module, paths=None):
2929
"""Just like 'imp.find_module()', but with package support"""
3030
spec = find_spec(module, paths)
3131
if spec is None:
32-
raise ImportError("Can't find %s" % module)
32+
raise ImportError(f"Can't find {module}")
3333
if not spec.has_location and hasattr(spec, 'submodule_search_locations'):
3434
spec = importlib.util.spec_from_loader('__init__.py', spec.loader)
3535

@@ -76,12 +76,12 @@ def find_module(module, paths=None):
7676
def get_frozen_object(module, paths=None):
7777
spec = find_spec(module, paths)
7878
if not spec:
79-
raise ImportError("Can't find %s" % module)
79+
raise ImportError(f"Can't find {module}")
8080
return spec.loader.get_code(module)
8181

8282

8383
def get_module(module, paths, info):
8484
spec = find_spec(module, paths)
8585
if not spec:
86-
raise ImportError("Can't find %s" % module)
86+
raise ImportError(f"Can't find {module}")
8787
return module_from_spec(spec)

setuptools/archive_util.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ def unpack_archive(
6262
else:
6363
return
6464
else:
65-
raise UnrecognizedFormat("Not a recognized archive type: %s" % filename)
65+
raise UnrecognizedFormat(f"Not a recognized archive type: {filename}")
6666

6767

6868
def unpack_directory(filename, extract_dir, progress_filter=default_filter) -> None:
@@ -71,7 +71,7 @@ def unpack_directory(filename, extract_dir, progress_filter=default_filter) -> N
7171
Raises ``UnrecognizedFormat`` if `filename` is not a directory
7272
"""
7373
if not os.path.isdir(filename):
74-
raise UnrecognizedFormat("%s is not a directory" % filename)
74+
raise UnrecognizedFormat(f"{filename} is not a directory")
7575

7676
paths = {
7777
filename: ('', extract_dir),
@@ -101,7 +101,7 @@ def unpack_zipfile(filename, extract_dir, progress_filter=default_filter) -> Non
101101
"""
102102

103103
if not zipfile.is_zipfile(filename):
104-
raise UnrecognizedFormat("%s is not a zip file" % (filename,))
104+
raise UnrecognizedFormat(f"{filename} is not a zip file")
105105

106106
with zipfile.ZipFile(filename) as z:
107107
_unpack_zipfile_obj(z, extract_dir, progress_filter)
@@ -198,7 +198,7 @@ def unpack_tarfile(filename, extract_dir, progress_filter=default_filter) -> boo
198198
tarobj = tarfile.open(filename)
199199
except tarfile.TarError as e:
200200
raise UnrecognizedFormat(
201-
"%s is not a compressed or uncompressed tar file" % (filename,)
201+
f"{filename} is not a compressed or uncompressed tar file"
202202
) from e
203203

204204
for member, final_dst in _iter_open_tar(

setuptools/command/alias.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ def run(self) -> None:
5555
print("setup.py alias", format_alias(alias, aliases))
5656
return
5757
else:
58-
print("No alias definition found for %r" % alias)
58+
print(f"No alias definition found for {alias!r}")
5959
return
6060
else:
6161
alias = self.args[0]
@@ -73,5 +73,5 @@ def format_alias(name, aliases):
7373
elif source == config_file('local'):
7474
source = ''
7575
else:
76-
source = '--filename=%r' % source
76+
source = f'--filename={source!r}'
7777
return source + name + ' ' + command

setuptools/command/bdist_egg.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ def __bootstrap__():
6969

7070

7171
class bdist_egg(Command):
72-
description = "create an \"egg\" distribution"
72+
description = 'create an "egg" distribution'
7373

7474
user_options = [
7575
('bdist-dir=', 'b', "temporary directory for creating the distribution"),
@@ -263,7 +263,7 @@ def zap_pyfiles(self):
263263
pattern = r'(?P<name>.+)\.(?P<magic>[^.]+)\.pyc'
264264
m = re.match(pattern, name)
265265
path_new = os.path.join(base, os.pardir, m.group('name') + '.pyc')
266-
log.info("Renaming file from [%s] to [%s]" % (path_old, path_new))
266+
log.info(f"Renaming file from [{path_old}] to [{path_new}]")
267267
try:
268268
os.remove(path_new)
269269
except OSError:

setuptools/command/bdist_wheel.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -184,9 +184,7 @@ class bdist_wheel(Command):
184184
(
185185
"compression=",
186186
None,
187-
"zipfile compression (one of: {}) [default: 'deflated']".format(
188-
", ".join(supported_compressions)
189-
),
187+
f"zipfile compression (one of: {', '.join(supported_compressions)}) [default: 'deflated']",
190188
),
191189
(
192190
"python-tag=",

0 commit comments

Comments
 (0)