Skip to content

refactor: __format__ unit dispatch duplicates _UNIT_POWERS mapping #5

@underwoo

Description

@underwoo

Summary

_UNIT_POWERS already encodes the mapping from unit letter to power-of-convert:

_UNIT_POWERS: dict[str, int] = {"K": 1, "M": 2, "G": 3, "T": 4, "P": 5, "E": 6}

The __format__ method ignores this and reimplements the same mapping as a six-branch if/elif chain that dispatches to the six to_x() methods. Adding a new unit (e.g. zettabyte "Z") requires edits in at least two places: _UNIT_POWERS (or the to_x() method) and the if/elif chain in __format__. If the chain is not updated the new unit silently falls through to the default "K".

Location

src/fsize/__init__.py, lines 194–205:

n = self.real
if unit == "K":
    n = self.to_k()
elif unit == "M":
    n = self.to_m()
elif unit == "G":
    n = self.to_g()
elif unit == "T":
    n = self.to_t()
elif unit == "P":
    n = self.to_p()
elif unit == "E":
    n = self.to_e()

Fix

Unify via a dispatch dict (or reuse _UNIT_POWERS directly with self.real / self._convert ** _UNIT_POWERS[unit]):

n = self.real / self._convert ** _UNIT_POWERS[unit]

This eliminates the redundant mapping and makes adding a new unit a single-site change.

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