Skip to content

Conversation

@tdhopper
Copy link
Collaborator

@tdhopper tdhopper commented Dec 17, 2025

Type checkers report "invalid-context-manager" errors when using AudioFile as a context manager because the AudioFile class stub doesn't have __enter__ and __exit__ methods defined, even though all subclasses (ReadableAudioFile, WriteableAudioFile) and the runtime implementation do support the context manager protocol.

Add __enter__ and __exit__method stubs to the AudioFile base class. The __enter__ method returns Union[ReadableAudioFile, WriteableAudioFile] to match the existing __new__ overloads, allowing type checkers to understand that AudioFile instances are valid context managers.

Problem

Type checkers (mypy, pyright) report "invalid-context-manager" errors
when using AudioFile as a context manager because the AudioFile class
stub doesn't have __enter__ and __exit__ methods defined, even though
all subclasses (ReadableAudioFile, WriteableAudioFile) and the runtime
implementation do support the context manager protocol.

Solution

Add __enter__ and __exit__ method stubs to the AudioFile base class.
The __enter__ method returns Union[ReadableAudioFile, WriteableAudioFile]
to match the existing __new__ overloads, allowing type checkers to
understand that AudioFile instances are valid context managers.

Result

Type checkers will no longer report errors when using AudioFile
as a context manager with `with AudioFile(...) as f:` syntax.
psobot

This comment was marked as outdated.

those classes below for documentation.
"""

def __enter__(self) -> typing.Union[ReadableAudioFile, WriteableAudioFile]:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks like this may be tripping up Pyright, used in tests:

with pedalboard.io.AudioFile(stream, "w", 44100, 2, format=extension) as af:  # type: ignore
    af.write(cached_rand(1, 2))

...this code now seems to make Pyright think that the af could be a ReadableAudioFile, which doesn't have a write method, so we get:

/home/runner/work/pedalboard/pedalboard/tests/test_io.py
  /home/runner/work/pedalboard/pedalboard/tests/test_io.py:621:16 - error: Cannot access attribute "write" for class "ReadableAudioFile"
    Attribute "write" is unknown (reportAttributeAccessIssue)

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, yeah. I'm not sure how to make everybody happy.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants