Skip to content

bug: format(fsize, "") returns K-unit value instead of str(fsize) #3

@underwoo

Description

@underwoo

Summary

_RE_FORMAT_SPEC matches the empty string (every part of the pattern is optional). When __format__ is called with format_spec="", the match succeeds and the default unit="K" applies, returning a K-converted value. Python's data model specifies that format(x, "") must equal str(x).

Reproduction

from fsize import FSize

x = FSize(1_048_576)

str(x)          # '1048576.0'
format(x, "")  # '1024'        ← wrong: should equal str(x)
f"{x}"          # '1024'        ← wrong: f-strings with no spec call __format__("")

Impact

Any generic code that embeds an FSize in an f-string without a format spec silently gets a K-converted value instead of the raw byte count. The discrepancy between str(x) and f"{x}" is particularly surprising.

Root cause

src/fsize/__init__.py, lines 177–185:

match = _RE_FORMAT_SPEC.match(format_spec)
if match:
    # all groups are None when format_spec == ""
    # unit stays at the default "K"
    ...

Fix

Add an early return for the empty format spec:

if not format_spec:
    return str(self)

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