Skip to content

refactor: match.group() called twice per field in __format__ #6

@underwoo

Description

@underwoo

Summary

In __format__, each named group is fetched from the regex match twice — once to test truthiness, once to use the value:

fill = match.group("fill") if match.group("fill") else fill
align = match.group("align") if match.group("align") else align
width = int(match.group("width")) if match.group("width") else width
grouping = match.group("grouping") if match.group("grouping") else grouping
unit = match.group("unit").upper() if match.group("unit") else unit

Location

src/fsize/__init__.py, lines 179–185.

Issues

  1. Each group lookup is performed twice (5 lines × 2 calls = 10 total vs. 5 needed).
  2. If a group name is ever misspelled, both the condition and the value evaluate to None/falsy, and the default silently applies — no IndexError until a separate code path.

Fix

Use or to fetch once:

fill = match.group("fill") or fill
align = match.group("align") or align
width = int(match.group("width")) if match.group("width") else width
grouping = match.group("grouping") or grouping
unit = (match.group("unit") or unit).upper()

(width still needs the conditional form because int(None) raises, but all others work cleanly with or.)

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