Skip to content

wave: setframerate() accepts invalid frame rate values that round to zero #144975

@mbeijen

Description

@mbeijen

Bug report

Bug description:

The wave.Wave_write.setframerate() method currently validates the frame rate before rounding it to an integer. This allows invalid values like 0.5 to pass validation (since 0.5 > 0), but then get rounded to 0, resulting in an invalid frame rate being stored internally.

This causes a confusing user experience: setframerate(0.5) succeeds silently, but later operations fail with the misleading error message "sampling rate not specified" instead of raising a clear error at the point where the bad value was provided.

It was found in the PR review for #132448 by @picnixz but as that PR is not merged and might not get merged, I think it makes sense to raise this separately.

current behavior

import wave
import io

f = wave.open(io.BytesIO(), 'wb')
f.setnchannels(1)
f.setsampwidth(2)
f.setframerate(0.5)  # No error raised!
print(f.getframerate())  # Outputs: 0

# Later, when trying to write:
f.writeframes(b'\x00\x00\x00\x00')
# wave.Error: sampling rate not specified  <-- Confusing delayed error!

The value 0.5 passes the framerate <= 0 check because 0.5 > 0, but int(round(0.5)) evaluates to 0. This creates a confusing user experience where:

  1. setframerate(0.5) succeeds with no error
  2. The error only appears later during writeframes()
  3. The error message is misleading: "not specified" when a value was specified

expected behavior

setframerate(0.5) should immediately raise wave.Error('bad frame rate') because the rounded value is 0, which is invalid. This provides clear, immediate feedback at the point where the error occurs, rather than a confusing delayed error.

I understand that wave files with such low framerates are not usable, but the bug fix is trivial so we should just as well fix this.

CPython versions tested on:

CPython main branch

Operating systems tested on:

Linux

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions