Skip to content

Commit c0c1b8b

Browse files
Enforce ruff/pyupgrade rule UP032
UP032 Use f-string instead of `format` call
1 parent f28308a commit c0c1b8b

38 files changed

+196
-241
lines changed

pkg_resources/__init__.py

Lines changed: 18 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -492,7 +492,7 @@ def compatible_platforms(provided: str | None, required: str | None) -> bool:
492492
provDarwin = darwinVersionString.match(provided)
493493
if provDarwin:
494494
dversion = int(provDarwin.group(1))
495-
macosversion = "{}.{}".format(reqMac.group(1), reqMac.group(2))
495+
macosversion = f"{reqMac.group(1)}.{reqMac.group(2)}"
496496
if (
497497
dversion == 7
498498
and macosversion >= "10.3"
@@ -1316,7 +1316,7 @@ def __iadd__(self, other: Distribution | Environment) -> Self:
13161316
for dist in other[project]:
13171317
self.add(dist)
13181318
else:
1319-
raise TypeError("Can't add {!r} to environment".format(other))
1319+
raise TypeError(f"Can't add {other!r} to environment")
13201320
return self
13211321

13221322
def __add__(self, other: Distribution | Environment) -> Self:
@@ -1699,7 +1699,7 @@ def get_metadata(self, name: str) -> str:
16991699
except UnicodeDecodeError as exc:
17001700
# Include the path in the error message to simplify
17011701
# troubleshooting, and without changing the exception type.
1702-
exc.reason += ' in {} file at path: {}'.format(name, path)
1702+
exc.reason += f' in {name} file at path: {path}'
17031703
raise
17041704

17051705
def get_metadata_lines(self, name: str) -> Iterator[str]:
@@ -2018,15 +2018,15 @@ def _zipinfo_name(self, fspath):
20182018
return ''
20192019
if fspath.startswith(self.zip_pre):
20202020
return fspath[len(self.zip_pre) :]
2021-
raise AssertionError("{} is not a subpath of {}".format(fspath, self.zip_pre))
2021+
raise AssertionError(f"{fspath} is not a subpath of {self.zip_pre}")
20222022

20232023
def _parts(self, zip_path):
20242024
# Convert a zipfile subpath into an egg-relative path part list.
20252025
# pseudo-fs path
20262026
fspath = self.zip_pre + zip_path
20272027
if fspath.startswith(self.egg_root + os.sep):
20282028
return fspath[len(self.egg_root) + 1 :].split(os.sep)
2029-
raise AssertionError("{} is not a subpath of {}".format(fspath, self.egg_root))
2029+
raise AssertionError(f"{fspath} is not a subpath of {self.egg_root}")
20302030

20312031
@property
20322032
def zipinfo(self):
@@ -2729,15 +2729,15 @@ def __init__(
27292729
self.dist = dist
27302730

27312731
def __str__(self) -> str:
2732-
s = "{} = {}".format(self.name, self.module_name)
2732+
s = f"{self.name} = {self.module_name}"
27332733
if self.attrs:
27342734
s += ':' + '.'.join(self.attrs)
27352735
if self.extras:
27362736
s += ' [{}]'.format(','.join(self.extras))
27372737
return s
27382738

27392739
def __repr__(self) -> str:
2740-
return "EntryPoint.parse({!r})".format(str(self))
2740+
return f"EntryPoint.parse({str(self)!r})"
27412741

27422742
@overload
27432743
def load(
@@ -3049,9 +3049,7 @@ def version(self):
30493049
version = self._get_version()
30503050
if version is None:
30513051
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-
)
3052+
msg = (f"Missing 'Version:' header and/or {self.PKG_INFO} file at path: {path}")
30553053
raise ValueError(msg, self) from e
30563054

30573055
return version
@@ -3108,7 +3106,7 @@ def requires(self, extras: Iterable[str] = ()) -> list[Requirement]:
31083106
deps.extend(dm[safe_extra(ext)])
31093107
except KeyError as e:
31103108
raise UnknownExtra(
3111-
"{} has no such extra feature {!r}".format(self, ext)
3109+
f"{self} has no such extra feature {ext!r}"
31123110
) from e
31133111
return deps
31143112

@@ -3150,19 +3148,15 @@ def activate(self, path: list[str] | None = None, replace: bool = False) -> None
31503148

31513149
def egg_name(self):
31523150
"""Return what this distribution's standard .egg filename should be"""
3153-
filename = "{}-{}-py{}".format(
3154-
to_filename(self.project_name),
3155-
to_filename(self.version),
3156-
self.py_version or PY_MAJOR,
3157-
)
3151+
filename = f"{to_filename(self.project_name)}-{to_filename(self.version)}-py{self.py_version or PY_MAJOR}"
31583152

31593153
if self.platform:
31603154
filename += '-' + self.platform
31613155
return filename
31623156

31633157
def __repr__(self) -> str:
31643158
if self.location:
3165-
return "{} ({})".format(self, self.location)
3159+
return f"{self} ({self.location})"
31663160
else:
31673161
return str(self)
31683162

@@ -3172,7 +3166,7 @@ def __str__(self) -> str:
31723166
except ValueError:
31733167
version = None
31743168
version = version or "[unknown version]"
3175-
return "{} {}".format(self.project_name, version)
3169+
return f"{self.project_name} {version}"
31763170

31773171
def __getattr__(self, attr: str):
31783172
"""Delegate all unrecognized public attributes to .metadata provider"""
@@ -3200,17 +3194,17 @@ def from_filename(
32003194
def as_requirement(self):
32013195
"""Return a ``Requirement`` that matches this distribution exactly"""
32023196
if isinstance(self.parsed_version, packaging.version.Version):
3203-
spec = "{}=={}".format(self.project_name, self.parsed_version)
3197+
spec = f"{self.project_name}=={self.parsed_version}"
32043198
else:
3205-
spec = "{}==={}".format(self.project_name, self.parsed_version)
3199+
spec = f"{self.project_name}==={self.parsed_version}"
32063200

32073201
return Requirement.parse(spec)
32083202

32093203
def load_entry_point(self, group: str, name: str) -> _ResolvedEntryPoint:
32103204
"""Return the `name` entry point of `group` or raise ImportError"""
32113205
ep = self.get_entry_info(group, name)
32123206
if ep is None:
3213-
raise ImportError("Entry point {!r} not found".format((group, name)))
3207+
raise ImportError(f"Entry point {(group, name)!r} not found")
32143208
return ep.load()
32153209

32163210
@overload
@@ -3327,8 +3321,8 @@ def check_version_conflict(self):
33273321
):
33283322
continue
33293323
issue_warning(
3330-
"Module {} was already imported from {}, but {} is being added"
3331-
" to sys.path".format(modname, fn, self.location),
3324+
f"Module {modname} was already imported from {fn}, but {self.location} is being added"
3325+
" to sys.path",
33323326
)
33333327

33343328
def has_version(self) -> bool:
@@ -3512,7 +3506,7 @@ def __hash__(self) -> int:
35123506
return self.__hash
35133507

35143508
def __repr__(self) -> str:
3515-
return "Requirement.parse({!r})".format(str(self))
3509+
return f"Requirement.parse({str(self)!r})"
35163510

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

pkg_resources/tests/test_pkg_resources.py

Lines changed: 4 additions & 6 deletions
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,12 +252,10 @@ 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
260-
)
258+
expected_text = (f"Missing 'Version:' header and/or {expected_filename} file at path: ")
261259
metadata_path = os.path.join(dist_dir, expected_filename)
262260

263261
# Now check the exception raised when the "version" attribute is accessed.

ruff.toml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +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-
"UP032", # temporarily disabled
3938
"UP038", # Using `X | Y` in `isinstance` call is slower and more verbose https://github.com/astral-sh/ruff/issues/7871
4039
# Only enforcing return type annotations for public functions
4140
"ANN202", # missing-return-type-private-function

setuptools/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -182,7 +182,7 @@ def _ensure_stringlike(self, option, what, default=None):
182182
return default
183183
elif not isinstance(val, str):
184184
raise DistutilsOptionError(
185-
"'{}' must be a {} (got `{}`)".format(option, what, val)
185+
f"'{option}' must be a {what} (got `{val}`)"
186186
)
187187
return val
188188

@@ -210,7 +210,7 @@ def ensure_string_list(self, option: str) -> None:
210210
ok = False
211211
if not ok:
212212
raise DistutilsOptionError(
213-
"'{}' must be a list of strings (got {!r})".format(option, val)
213+
f"'{option}' must be a list of strings (got {val!r})"
214214
)
215215

216216
@overload

setuptools/_core_metadata.py

Lines changed: 2 additions & 2 deletions
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("{}: {}\n".format(key, value))
153+
file.write(f"{key}: {value}\n")
154154

155155
write_field('Metadata-Version', str(version))
156156
write_field('Name', self.get_name())
@@ -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{}".format(long_description))
212+
file.write(f"\n{long_description}")
213213
if not long_description.endswith("\n"):
214214
file.write("\n")
215215

setuptools/_imp.py

Lines changed: 3 additions & 3 deletions
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 {}".format(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 {}".format(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 {}".format(module))
86+
raise ImportError(f"Can't find {module}")
8787
return module_from_spec(spec)

setuptools/archive_util.py

Lines changed: 4 additions & 4 deletions
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: {}".format(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("{} is not a directory".format(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("{} is not a zip file".format(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-
"{} is not a compressed or uncompressed tar file".format(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

Lines changed: 2 additions & 2 deletions
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}".format(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}'.format(source)
76+
source = f'--filename={source!r}'
7777
return source + name + ' ' + command

setuptools/command/bdist_egg.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -264,7 +264,7 @@ def zap_pyfiles(self):
264264
m = re.match(pattern, name)
265265
path_new = os.path.join(base, os.pardir, m.group('name') + '.pyc')
266266
log.info(
267-
"Renaming file from [{}] to [{}]".format(path_old, path_new)
267+
f"Renaming file from [{path_old}] to [{path_new}]"
268268
)
269269
try:
270270
os.remove(path_new)

setuptools/command/build_clib.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -29,9 +29,9 @@ def build_libraries(self, libraries) -> None:
2929
sources = build_info.get('sources')
3030
if sources is None or not isinstance(sources, (list, tuple)):
3131
raise DistutilsSetupError(
32-
"in 'libraries' option (library '{}'), "
32+
f"in 'libraries' option (library '{lib_name}'), "
3333
"'sources' must be present and must be "
34-
"a list of source filenames".format(lib_name)
34+
"a list of source filenames"
3535
)
3636
sources = sorted(list(sources))
3737

@@ -43,9 +43,9 @@ def build_libraries(self, libraries) -> None:
4343
obj_deps = build_info.get('obj_deps', dict())
4444
if not isinstance(obj_deps, dict):
4545
raise DistutilsSetupError(
46-
"in 'libraries' option (library '{}'), "
46+
f"in 'libraries' option (library '{lib_name}'), "
4747
"'obj_deps' must be a dictionary of "
48-
"type 'source: list'".format(lib_name)
48+
"type 'source: list'"
4949
)
5050
dependencies = []
5151

@@ -54,9 +54,9 @@ def build_libraries(self, libraries) -> None:
5454
global_deps = obj_deps.get('', list())
5555
if not isinstance(global_deps, (list, tuple)):
5656
raise DistutilsSetupError(
57-
"in 'libraries' option (library '{}'), "
57+
f"in 'libraries' option (library '{lib_name}'), "
5858
"'obj_deps' must be a dictionary of "
59-
"type 'source: list'".format(lib_name)
59+
"type 'source: list'"
6060
)
6161

6262
# Build the list to be used by newer_pairwise_group
@@ -67,9 +67,9 @@ def build_libraries(self, libraries) -> None:
6767
extra_deps = obj_deps.get(source, list())
6868
if not isinstance(extra_deps, (list, tuple)):
6969
raise DistutilsSetupError(
70-
"in 'libraries' option (library '{}'), "
70+
f"in 'libraries' option (library '{lib_name}'), "
7171
"'obj_deps' must be a dictionary of "
72-
"type 'source: list'".format(lib_name)
72+
"type 'source: list'"
7373
)
7474
src_deps.extend(extra_deps)
7575
dependencies.append(src_deps)

0 commit comments

Comments
 (0)