Skip to content

refactor: n = self.real in __format__ is a dead initialization #4

@underwoo

Description

@underwoo

Summary

In __format__, n is initialized to self.real (raw bytes) before the unit dispatch block, but every reachable code path overwrites n before it is used. The initialization is dead and misleading: it implies self.real is a meaningful fallback, but it is never the value that reaches out_format_spec.

Location

src/fsize/__init__.py, line 193:

n = self.real           # dead: always overwritten below
if unit == "K":
    n = self.to_k()
elif unit == "M":
    n = self.to_m()
# … etc. — all six units covered

unit is either one of {K, M, G, T, P, E} (from [KkMmGgTtPpEe].upper() in the regex) or the default "K". Every possible value is handled by the if/elif chain, so n = self.real is never the final value.

Risk

A future maintainer adding a "B" (pass-through bytes) unit would assume the n = self.real fallback handles it and skip adding an explicit branch. The raw byte count (potentially 10⁹+) would then be formatted at K-unit precision, producing garbage output silently.

Fix

Remove the dead initialization and make the dispatch exhaustive with an explicit else that raises AssertionError or converts bytes directly:

if unit == "K":
    n = self.to_k()
elif unit == "M":
    n = self.to_m()
# …
else:
    raise AssertionError(f"unhandled unit: {unit!r}")  # unreachable today

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions