music-tag developer on retainer: f[‘tracktitle’].value returns None for untagged files — developer calls None.upper() for title normalisation — AttributeError caught broadly — 20 000 files skipped silently per month — music players show blank titles — 3 weeks — music-tag developer on monthly retainer
music_tag 0.4.3 • Python 3.9; f['tracktitle'].value returns None for files with no title tag; None.upper() raises AttributeError; broad except Exception: continue silently skips file and never calls f.save(); 20% of files untagged in source libraries • Westfield Musictag Ltd. (music library migration; 500 client libraries; 100,000 files/month; 20,000 files skipped silently; blank titles in music players; 3 weeks; fix: title = f['tracktitle'].value or ''; 1.5h retainer engagement)
Westfield Musictag Ltd. built a music library migration service for 500 clients that normalised audio file metadata — title capitalisation, artist name standardisation, tracknumber padding — and re-tagged 100,000 audio files per month as part of moving client libraries from mixed legacy formats to standardised ID3v2.4 (MP3), VorbisComment (FLAC), and iTunes tags (M4A). After the first migration run, music player clients reported that 20% of tracks across all libraries displayed blank titles. Tracks were playable but showed only artist and album information — no track title — in every music player tested (iTunes, Foobar2000, VLC, Roon).
music_tag 0.4.3 load_file(path) returns a MusicTagFile object. Calling f['tracktitle'] always returns a MetaValue object — the bracket accessor does not raise KeyError for absent tags and does not return None directly. The MetaValue’s .value property returns a Python string if the tracktitle tag is present in the file, or None if the tag is absent. Twenty percent of the source library files had no existing title tag: ripped CDs where the CD ripper was not connected to a metadata database at rip time, and downloaded audio files that were never tagged. For these files, f['tracktitle'].value evaluated to None. The developer’s migration loop contained: f['tracktitle'] = f['tracktitle'].value.upper(). For files where .value returned a non-None string, .value.upper() correctly produced the uppercased title. For files where .value returned None, None.upper() raised AttributeError: ‘NoneType’ object has no attribute ‘upper’. The processing loop’s exception handler was except Exception: continue — intended to handle I/O errors on locked or corrupt files — and it caught the AttributeError and silently skipped the file. f.save() was never called for the skipped files; they were left with their original (absent) title tag in the destination.
The annotated buggy and fixed migration loop, with per-exception-type counters and post-run audit:
# Westfield Musictag Ltd. — music_tag 0.4.3 None.upper() fix
# music_tag 0.4.3; Python 3.9
# Music library migration; 500 clients; 100,000 files/month (MP3, FLAC, M4A)
#
# Problem: f['tracktitle'].value returns None for files with no title tag
# f['tracktitle'].value.upper() raises AttributeError for None values
# broad except Exception: continue silently skips file
# f.save() never called for skipped files
# 20% of files (20,000/month) silently unprocessed
# music players show blank titles for 20,000 tracks
# Fix: title = f['tracktitle'].value or ''
# explicit None handling; skip counter with alert threshold
import logging
from pathlib import Path
import music_tag
logger = logging.getLogger(__name__)
# ── BUGGY migration loop ──────────────────────────────────────────────────────
def normalise_titles_buggy(audio_paths: list[Path]) -> None:
"""Normalise track titles to upper-case — BUGGY: None.upper() silently skipped."""
for path in audio_paths:
try:
f = music_tag.load_file(str(path))
# BUG: f['tracktitle'].value returns None if no title tag is set
# None.upper() raises AttributeError
# except Exception catches AttributeError; file silently skipped
f['tracktitle'] = f['tracktitle'].value.upper()
f.save()
except Exception:
continue # silently swallows AttributeError AND IOError AND everything else
# ── FIXED migration loop ──────────────────────────────────────────────────────
class MigrationStats:
processed: int = 0
skipped_io: int = 0
skipped_other: int = 0
untagged_title: int = 0
def normalise_titles(
audio_paths: list[Path],
alert_skip_pct: float = 0.01,
) -> MigrationStats:
"""Normalise track titles — FIXED: explicit None check; typed skip counters."""
stats = MigrationStats()
total = len(audio_paths)
for path in audio_paths:
try:
f = music_tag.load_file(str(path))
# FIX: read .value and handle None explicitly before any string method
existing_title = f['tracktitle'].value # str or None
if existing_title is None:
# File has no title tag — record it and write empty string
# so the tag exists in the destination (music players prefer '' to absent)
stats.untagged_title += 1
new_title = ''
else:
new_title = existing_title.upper()
f['tracktitle'] = new_title
f.save()
stats.processed += 1
except (OSError, PermissionError, FileNotFoundError) as exc:
logger.warning("I/O error processing %s: %s", path, exc)
stats.skipped_io += 1
except Exception as exc:
# Catch-all for unexpected errors — log type explicitly for diagnosis
logger.error(
"Unexpected error processing %s: %s: %s",
path, type(exc).__name__, exc,
)
stats.skipped_other += 1
# Alert if unexpected skip rate exceeds threshold
unexpected_skip_rate = stats.skipped_other / max(1, total)
if unexpected_skip_rate > alert_skip_pct:
raise RuntimeError(
f"Migration aborted: unexpected skip rate {unexpected_skip_rate:.1%} "
f"({stats.skipped_other} files) exceeds threshold {alert_skip_pct:.1%}. "
"Check skipped_other logs for AttributeError, ValueError, or KeyError — "
"likely a tag .value operation on None or an unexpected tag key name. "
f"Stats: processed={stats.processed}, "
f"skipped_io={stats.skipped_io}, "
f"untagged_title={stats.untagged_title}."
)
logger.info(
"Migration complete: processed=%d, untagged_title=%d, "
"skipped_io=%d, skipped_other=%d (of %d total)",
stats.processed, stats.untagged_title,
stats.skipped_io, stats.skipped_other, total,
)
return stats
def post_migration_audit(
audio_paths: list[Path],
stats: MigrationStats,
) -> None:
"""Verify every processed file has a non-None tracktitle value after migration."""
blank_titles = []
for path in audio_paths:
try:
f = music_tag.load_file(str(path))
val = f['tracktitle'].value
if val is None:
blank_titles.append((path, 'None'))
except Exception as exc:
blank_titles.append((path, str(exc)))
if blank_titles:
raise RuntimeError(
f"Post-migration audit: {len(blank_titles)} files have None tracktitle "
f"after migration (expected 0 — all should be str or ''). "
f"First 5: {blank_titles[:5]}. "
"Check that f.save() is called for every file, including those where "
"existing_title was None and new_title was set to ''."
)
How a broad except Exception: continue that was intended for I/O errors silently swallows AttributeError from None.upper(), a validation script that cannot distinguish absent tags from empty strings, and 20% untagged source files combine to produce three weeks of blank music player titles — and the correct value or ‘’ pattern for music_tag None handling
The core failure combines three independent factors: Python’s broad exception catching (except Exception) silently swallows any exception type including AttributeError, making it impossible to distinguish legitimate I/O failures (the intended catch) from programming errors like None.upper(); the validation script checked f['tracktitle'].value after migration and interpreted a None return as a valid post-migration state rather than evidence of a skipped file — it did not assert that every file had been touched; and 20% of real-world music library files have no title tag, a higher rate than developers typically expect when building from a small test corpus of their own well-tagged music. The correct fix is existing_title = f['tracktitle'].value or '': Python’s or operator returns the right operand when the left evaluates to falsy, handling both None (absent tag) and '' (empty string tag) in one expression. The exception handler was split into typed branches: except (OSError, PermissionError, FileNotFoundError) for the I/O errors that the original handler was designed for, and a narrow catch-all except Exception that logs the exception type explicitly and increments a typed skip counter that triggers an alert if the unexpected skip rate exceeds 1%. The post-migration audit was extended to verify that every file had a non-None tracktitle.value in the destination, asserting that the processed + untagged_title count equalled the total file count. The recovery required re-running the corrected migration on the 20,000 silently skipped files; the retainer engagement was 1.5h: 0.5h triage (add except Exception as exc: print(type(exc), exc) to the loop; 20,000 AttributeError: ‘NoneType’ object has no attribute ‘upper’ per run; untagged file rate confirmed at 20%); 0.25h root cause (f['tracktitle'].value returns None for absent tags; None.upper() raises AttributeError; fix: value or ''); 0.5h fix (typed exception handlers; skip counter with alert threshold; post-migration audit); 0.25h validation (100-file test including 20 untagged files; all files processed; titles correct or empty-string; skip counter 0; 1.5h total). Hours logged to HourTab with per-session breakdown.
Related retainer posts
- mutagen developer on retainer — mutagen 1.46.0; Python 3.9; ID3 tags may be absent entirely on ripped files; MP3File['TIT2'] raises KeyError; broad except skips 25% of library; titles not migrated; music players show filename as title — 1.5h
- tinytag developer on retainer — tinytag 1.8.1; Python 3.9; TinyTag.get() returns tag object where unset fields are None not empty string; developer builds CSV export with tag.title + ',' delimiter; None + ',' raises TypeError; CSV export fails for 30% of library — 1.5h
- eyeD3 developer on retainer — eyeD3 0.9.6; Python 3.9; tag.artist returns None for files without artist frame; str(None) = 'None' in f-string; artist field set to literal string 'None'; library shows 'None' as artist for 15% of tracks — 2.0h
Track retainer hours without a client portal
HourTab turns your time-tracker CSV into a public URL your client bookmarks. No login. No portal. CSV in, URL out.
See pricing →