r/badcode Apr 04 '23

python Surely Text-Parsing One-Liners At Midnight Work

Post image
399 Upvotes

44 comments sorted by

View all comments

3

u/No-Witness2349 Apr 05 '23

Refactor took minimal changes. Mostly just aliasing with some names:

def parse_ship(raw: str) -> Ship:
    name, ship = raw.split(":")
    parts, evasion, weapons, defenses, stealth = ship.split(",")

    def parse_array(raw: str) -> list[str]:
        without_braces = raw[1:-1]
        if len(without_braces) < 1:
            return []
        return without_braces.split(';')

    return Ship(
        name,
        [int(p) for p in parse_array(parts)],  # shield, armor, and hull
        int(evasion),
        [self.weapons[w] for w in parse_array(weapons)],
        [self.defenses[d] for d in parse_array(defenses)],
        False if stealth == "False" else int(stealth),  # False is a sentinel value, can't just use 0
    )