Skip to main content
edited tags; edited title
Link
200_success
  • 145.6k
  • 22
  • 191
  • 481

How can I parse out these arguments better? Parsing input and output currency names

Tweeted twitter.com/StackCodeReview/status/1413513298608234503
Became Hot Network Question
Source Link

How can I parse out these arguments better?

The input for price() would be STRINGS, as you see below. If the string starts with "-" I would like what follows to be stored in fiat_name and then retrieve the symbol from _KNOWN_FIAT_SYMBOLS. "--rub" (EXAMPLE) could be at any position in the list passed through price()

If the optional fiat_name does not exist in _KNOWN_FIAT_SYMBOLS i would like it to default to USD/$

I would like the code optimized and cleaned/minimized. I am trying to practice clean and read-able code.

import re

_KNOWN_FIAT_SYMBOLS = {"USD":"$", "RUB":"₽"} # this will be populated with more symbols/pairs later


def price(*arguments):
    # default to USD/$
    fiat_name = "USD"

    arguments = list(arguments)
    cryptos = []

    for arg in arguments:
        arg = arg.strip()
            
        if not arg:
            continue

        for part in arg.split(","):
            if part.startswith("-"):

                fiat_name = part.upper().lstrip("-")
                    
                continue
                
            crypto = re.sub("[^a-z0-9]", "", part.lower())
                
            if crypto not in cryptos:
                cryptos.append(crypto)

    if not cryptos:
        cryptos.append("btc")
            
    fiat_symbol = _KNOWN_FIAT_SYMBOLS.get(fiat_name)
        
    if not fiat_symbol:
        fiat_name = "USD"
        fiat_symbol = "$"

    print(f"{cryptos} to: {fiat_name}{fiat_symbol}")


price("usd", "usdc", "--rub") # ['usd', 'usdc'] to: RUB₽ (becuase of the optional --rub)
price("usd,usdc,eth", "btc", "-usd") # ['usd', 'usdc', 'eth', 'btc'] to: USD$ (becuase of the optional --usd)
price("usd", "usdc,btc", "-xxx") #['usd', 'usdc', 'btc'] to: USD$ (because xxx does not exist in _KNOWN_FIAT_SYMBOLS
price("usd,usdc,eth", "btc") # ['usd', 'usdc', 'eth', 'btc'] to: USD$ (becuase no optional fiat_name was given)
price("usd,--rub,eth", "btc") # ['usd', 'eth', 'btc'] to: RUB₽ (becuase of the optional --rub)
price("--rub") # ['btc'] to: RUB₽ (becuase of the optional --rub and the cryptos is empty)
price("") # ['btc'] to: USD$ (becuase of the default USD and the cryptos is empty)