Skip to content

Instantly share code, notes, and snippets.

@nanoman657
Created September 1, 2023 18:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nanoman657/93abb6c81dbf81e78f7c6847d5c1818a to your computer and use it in GitHub Desktop.
Save nanoman657/93abb6c81dbf81e78f7c6847d5c1818a to your computer and use it in GitHub Desktop.
Python Type Checking with Command Line Inputs
from sys import argv
from typing import TypeAlias, Literal, Union, get_args
singular_word: TypeAlias = Literal["pie", "pastry"]
plural_word: TypeAlias = Literal["pies", "pastries"]
def pluralize(word: singular_word, quantity: int) -> str:
plural_map: dict = dict(zip(get_args(singular_word), get_args(plural_word)))
return f"{quantity} {plural_map[word] if quantity != 1 else word}"
raw_word: Union[singular_word, str] = argv[1]
raw_num: str = argv[2]
if raw_word in get_args(singular_word):
processed_word: singular_word = raw_word
processed_num: int = int(raw_num)
print(pluralize(processed_word, processed_num))
else:
raise ValueError("Unknown word requested for pluralization")
from argparse import ArgumentParser, Namespace
from typing import TypeAlias, Literal, get_args
SingularWord: TypeAlias = Literal["pie", "pastry"]
PluralWord: TypeAlias = Literal["pies", "pastries"]
class PluralizeNamespace(Namespace):
word: SingularWord
quantity: int
def pluralize(word: SingularWord, quantity: int) -> str:
plural_map: dict = dict(zip(get_args(SingularWord), get_args(PluralWord)))
return f"{quantity} {plural_map[word] if quantity != 1 else word}"
parser: ArgumentParser = ArgumentParser(
description="Converts a word and quantity to plural statement"
)
parser.add_argument("word", choices=get_args(SingularWord))
parser.add_argument("quantity", type=int)
arguments = parser.parse_args(namespace=PluralizeNamespace)
word_: SingularWord = arguments.word
quantity_: int = arguments.quantity
plural_statement: str = pluralize(word_, quantity_)
print(plural_statement)
from argparse import ArgumentParser
from typing import TypeAlias, Literal, get_args
SingularWord: TypeAlias = Literal["pie", "pastry"]
PluralWord: TypeAlias = Literal["pies", "pastries"]
def pluralize(word: SingularWord, quantity: int) -> str:
plural_map: dict = dict(zip(get_args(SingularWord), get_args(PluralWord)))
return f"{quantity} {plural_map[word] if quantity != 1 else word}"
parser: ArgumentParser = ArgumentParser(
description="Converts a word and quantity to plural statement"
)
parser.add_argument("word", choices=get_args(SingularWord))
parser.add_argument("quantity", type=int)
arguments = parser.parse_args()
word_: SingularWord = arguments.word
quantity_: int = arguments.quantity
plural_statement: str = pluralize(word_, quantity_)
print(plural_statement)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment