Skip to content

Commit fdc1aba

Browse files
committed
Replace typing.cast with explicit type definitions and ignore TC006
1 parent 99dc086 commit fdc1aba

File tree

6 files changed

+45
-36
lines changed

6 files changed

+45
-36
lines changed

beets/autotag/hooks.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818

1919
import re
2020
from functools import total_ordering
21-
from typing import TYPE_CHECKING, Any, Callable, NamedTuple, TypeVar, cast
21+
from typing import TYPE_CHECKING, Any, Callable, NamedTuple, TypeVar
2222

2323
from jellyfish import levenshtein_distance
2424
from unidecode import unidecode
@@ -474,7 +474,6 @@ def _eq(self, value1: re.Pattern[str] | Any, value2: Any) -> bool:
474474
matched against `value2`.
475475
"""
476476
if isinstance(value1, re.Pattern):
477-
value2 = cast(str, value2)
478477
return bool(value1.match(value2))
479478
return value1 == value2
480479

beets/autotag/match.py

Lines changed: 17 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,9 @@
2020

2121
import datetime
2222
import re
23-
from collections.abc import Iterable, Sequence
2423
from enum import IntEnum
2524
from functools import cache
26-
from typing import TYPE_CHECKING, Any, NamedTuple, TypeVar, cast
25+
from typing import TYPE_CHECKING, Any, NamedTuple, TypeVar
2726

2827
import lap
2928
import numpy as np
@@ -40,6 +39,8 @@
4039
from beets.util import plurality
4140

4241
if TYPE_CHECKING:
42+
from collections.abc import Iterable, Sequence
43+
4344
from beets.library import Item
4445

4546
# Artist signals that indicate "various artists". These are used at the
@@ -241,12 +242,14 @@ def distance(
241242
# Album.
242243
dist.add_string("album", likelies["album"], album_info.album)
243244

245+
preferred_config = config["match"]["preferred"]
244246
# Current or preferred media.
245247
if album_info.media:
246248
# Preferred media options.
247-
patterns = config["match"]["preferred"]["media"].as_str_seq()
248-
patterns = cast(Sequence[str], patterns)
249-
options = [re.compile(r"(\d+x)?(%s)" % pat, re.I) for pat in patterns]
249+
media_patterns: Sequence[str] = preferred_config["media"].as_str_seq()
250+
options = [
251+
re.compile(r"(\d+x)?(%s)" % pat, re.I) for pat in media_patterns
252+
]
250253
if options:
251254
dist.add_priority("media", album_info.media, options)
252255
# Current media.
@@ -258,7 +261,7 @@ def distance(
258261
dist.add_number("mediums", likelies["disctotal"], album_info.mediums)
259262

260263
# Prefer earliest release.
261-
if album_info.year and config["match"]["preferred"]["original_year"]:
264+
if album_info.year and preferred_config["original_year"]:
262265
# Assume 1889 (earliest first gramophone discs) if we don't know the
263266
# original year.
264267
original = album_info.original_year or 1889
@@ -282,9 +285,8 @@ def distance(
282285
dist.add("year", 1.0)
283286

284287
# Preferred countries.
285-
patterns = config["match"]["preferred"]["countries"].as_str_seq()
286-
patterns = cast(Sequence[str], patterns)
287-
options = [re.compile(pat, re.I) for pat in patterns]
288+
country_patterns: Sequence[str] = preferred_config["countries"].as_str_seq()
289+
options = [re.compile(pat, re.I) for pat in country_patterns]
288290
if album_info.country and options:
289291
dist.add_priority("country", album_info.country, options)
290292
# Country.
@@ -447,9 +449,8 @@ def _add_candidate(
447449
return
448450

449451
# Discard matches without required tags.
450-
for req_tag in cast(
451-
Sequence[str], config["match"]["required"].as_str_seq()
452-
):
452+
required_tags: Sequence[str] = config["match"]["required"].as_str_seq()
453+
for req_tag in required_tags:
453454
if getattr(info, req_tag) is None:
454455
log.debug("Ignored. Missing required tag: {0}", req_tag)
455456
return
@@ -462,8 +463,8 @@ def _add_candidate(
462463

463464
# Skip matches with ignored penalties.
464465
penalties = [key for key, _ in dist]
465-
ignored = cast(Sequence[str], config["match"]["ignored"].as_str_seq())
466-
for penalty in ignored:
466+
ignored_tags: Sequence[str] = config["match"]["ignored"].as_str_seq()
467+
for penalty in ignored_tags:
467468
if penalty in penalties:
468469
log.debug("Ignored. Penalty: {0}", penalty)
469470
return
@@ -499,8 +500,8 @@ def tag_album(
499500
"""
500501
# Get current metadata.
501502
likelies, consensus = current_metadata(items)
502-
cur_artist = cast(str, likelies["artist"])
503-
cur_album = cast(str, likelies["album"])
503+
cur_artist: str = likelies["artist"]
504+
cur_album: str = likelies["album"]
504505
log.debug("Tagging {0} - {1}", cur_artist, cur_album)
505506

506507
# The output result, keys are the MB album ID.

beets/autotag/mb.py

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,8 @@
1919
import re
2020
import traceback
2121
from collections import Counter
22-
from collections.abc import Iterator, Sequence
2322
from itertools import product
24-
from typing import Any, cast
23+
from typing import TYPE_CHECKING, Any
2524
from urllib.parse import urljoin
2625

2726
import musicbrainzngs
@@ -37,6 +36,9 @@
3736
spotify_id_regex,
3837
)
3938

39+
if TYPE_CHECKING:
40+
from collections.abc import Iterator, Sequence
41+
4042
VARIOUS_ARTISTS_ID = "89ad4ac3-39f7-470e-963a-56509c546377"
4143

4244
BASE_URL = "https://musicbrainz.org/"
@@ -178,23 +180,26 @@ def _preferred_alias(aliases: list):
178180
return matches[0]
179181

180182

181-
def _preferred_release_event(release: dict[str, Any]) -> tuple[str, str]:
183+
def _preferred_release_event(
184+
release: dict[str, Any],
185+
) -> tuple[str | None, str | None]:
182186
"""Given a release, select and return the user's preferred release
183187
event as a tuple of (country, release_date). Fall back to the
184188
default release event if a preferred event is not found.
185189
"""
186-
countries = config["match"]["preferred"]["countries"].as_str_seq()
187-
countries = cast(Sequence, countries)
190+
preferred_countries: Sequence[str] = config["match"]["preferred"][
191+
"countries"
192+
].as_str_seq()
188193

189-
for country in countries:
194+
for country in preferred_countries:
190195
for event in release.get("release-event-list", {}):
191196
try:
192197
if country in event["area"]["iso-3166-1-code-list"]:
193198
return country, event["date"]
194199
except KeyError:
195200
pass
196201

197-
return (cast(str, release.get("country")), cast(str, release.get("date")))
202+
return release.get("country"), release.get("date")
198203

199204

200205
def _multi_artist_credit(
@@ -589,7 +594,9 @@ def album_info(release: dict) -> beets.autotag.hooks.AlbumInfo:
589594
if not release_date:
590595
# Fall back if release-specific date is not available.
591596
release_date = release_group_date
592-
_set_date_str(info, release_date, False)
597+
598+
if release_date:
599+
_set_date_str(info, release_date, False)
593600
_set_date_str(info, release_group_date, True)
594601

595602
# Label name.

beets/dbcore/db.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626
from collections import defaultdict
2727
from collections.abc import Generator, Iterable, Iterator, Mapping, Sequence
2828
from sqlite3 import Connection
29-
from typing import TYPE_CHECKING, Any, AnyStr, Callable, Generic, TypeVar, cast
29+
from typing import TYPE_CHECKING, Any, AnyStr, Callable, Generic, TypeVar
3030

3131
from unidecode import unidecode
3232

@@ -126,8 +126,8 @@ def _get_formatted(self, model: Model, key: str) -> str:
126126
value = value.decode("utf-8", "ignore")
127127

128128
if self.for_path:
129-
sep_repl = cast(str, beets.config["path_sep_replace"].as_str())
130-
sep_drive = cast(str, beets.config["drive_sep_replace"].as_str())
129+
sep_repl: str = beets.config["path_sep_replace"].as_str()
130+
sep_drive: str = beets.config["drive_sep_replace"].as_str()
131131

132132
if re.match(r"^\w:", value):
133133
value = re.sub(r"(?<=^\w):", sep_drive, value)

beetsplug/replaygain.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
from dataclasses import dataclass
2929
from multiprocessing.pool import ThreadPool
3030
from threading import Event, Thread
31-
from typing import TYPE_CHECKING, Any, Callable, TypeVar, cast
31+
from typing import TYPE_CHECKING, Any, Callable, TypeVar
3232

3333
from beets import ui
3434
from beets.plugins import BeetsPlugin
@@ -576,7 +576,7 @@ def __init__(self, config: ConfigView, log: Logger):
576576
}
577577
)
578578

579-
self.command = cast(str, config["command"].as_str())
579+
self.command: str = config["command"].as_str()
580580

581581
if self.command:
582582
# Explicit executable path.
@@ -1225,7 +1225,7 @@ def __init__(self):
12251225

12261226
# FIXME: Consider renaming the configuration option and deprecating the
12271227
# old name 'overwrite'.
1228-
self.force_on_import = cast(bool, self.config["overwrite"].get(bool))
1228+
self.force_on_import: bool = self.config["overwrite"].get(bool)
12291229

12301230
# Remember which backend is used for CLI feedback
12311231
self.backend_name = self.config["backend"].as_str()
@@ -1491,7 +1491,7 @@ def close_pool(self):
14911491

14921492
def import_begin(self, session: ImportSession):
14931493
"""Handle `import_begin` event -> open pool"""
1494-
threads = cast(int, self.config["threads"].get(int))
1494+
threads: int = self.config["threads"].get(int)
14951495

14961496
if (
14971497
self.config["parallel_on_import"]
@@ -1526,9 +1526,7 @@ def command_func(
15261526

15271527
# Bypass self.open_pool() if called with `--threads 0`
15281528
if opts.threads != 0:
1529-
threads = opts.threads or cast(
1530-
int, self.config["threads"].get(int)
1531-
)
1529+
threads: int = opts.threads or self.config["threads"].get(int)
15321530
self.open_pool(threads)
15331531

15341532
if opts.album:

pyproject.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -263,6 +263,10 @@ select = [
263263
"TCH", # flake8-type-checking
264264
"W", # pycodestyle
265265
]
266+
ignore = [
267+
"TC006" # no need to quote 'cast's since we use 'from __future__ import annotations'
268+
]
269+
266270
[tool.ruff.lint.per-file-ignores]
267271
"beets/**" = ["PT"]
268272
"test/test_util.py" = ["E501"]

0 commit comments

Comments
 (0)