fix: use importlib to avoid torchaudio local variable scoping bug#1243
fix: use importlib to avoid torchaudio local variable scoping bug#1243POWERFULMOVES wants to merge 2 commits intofishaudio:mainfrom
Conversation
`import torchaudio.io._load_audio_fileobj` inside ReferenceLoader.__init__ creates a local `torchaudio` binding that shadows the module-level global for the entire method (Python determines variable scope at compile time). When this code runs inside an embedding context that swaps sys.modules (e.g., Ultimate-TTS-Studio's S1/S2 module isolation), line 39's `torchaudio.list_audio_backends()` fails with: "local variable 'torchaudio' referenced before assignment" Fix: use `importlib.import_module()` which doesn't create local bindings.
for more information, see https://pre-commit.ci
JiwaniZakir
left a comment
There was a problem hiding this comment.
The fix correctly addresses a real Python scoping gotcha — import torchaudio.io._load_audio_fileobj inside a function body binds torchaudio as a local name, which can shadow the module-level import for any subsequent use of torchaudio within __init__. Using importlib.import_module sidesteps this cleanly.
However, import importlib is placed inside the try block in reference_loader.py, which is unnecessary and slightly misleading. Since importlib is a Python standard library module that is always available, it belongs at the top of the file with the other imports rather than being re-imported conditionally on every call. As written, it's also technically inside the except (ImportError, ModuleNotFoundError) guard, meaning if something went wrong with the importlib import itself (contrived, but possible in unusual environments), it would silently fall through to self.backend = "soundfile" rather than raising.
It's also worth verifying whether any other import torchaudio.* submodule statements exist elsewhere in this file or the broader codebase that could trigger the same scoping issue — a single fix here doesn't preclude the same bug being latent in other locations.
Summary
import torchaudio.io._load_audio_fileobjinReferenceLoader.__init__creates a localtorchaudiobinding that shadows the module-level global for the entire methodtorchaudio.list_audio_backends()) tries to access the unbound local instead of the module globallocal variable 'torchaudio' referenced before assignmentwhen the module is loaded in contexts that swapsys.modules(e.g., multi-engine TTS frameworks)Fix
Replace
import torchaudio.io._load_audio_fileobjwithimportlib.import_module('torchaudio.io._load_audio_fileobj')which achieves the same effect without creating a local name binding.Test plan
Generated with Claude Code