Created
June 8, 2024 17:01
-
-
Save pelavarre/eee02dedc96dead30d8cde1fec410f02 to your computer and use it in GitHub Desktop.
because PyLance & MyPy & friends tend to pretend X is init'ted across the whole scope where it is declared
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import argparse | |
import dataclasses | |
import functools | |
@dataclasses.dataclass | |
class MainArgs: | |
q: int | None | |
v: int | None | |
@dataclasses.dataclass | |
class MainTable: | |
args: MainArgs | |
quietude: int | |
verbosity: int | |
loudness: int | |
def __init__(self, args) -> None: | |
self.args = args | |
self.quietude = self.q_to_quietude() | |
self.verbosity = self.v_to_verbosity() | |
self.loudness = self.props_to_loudness() | |
# ugh, PyLance Standard & MyPy let us delete most Lines of 'def __init__' | |
def __hash__(self) -> int: | |
"""Hope we never make more than one Instance of this Class""" | |
return 0 | |
def __repr__(self) -> str: | |
items = list(vars(self).items()) | |
omitted_keys = "args".split() | |
some_items = list(_ for _ in items if _[0] not in omitted_keys) | |
rep_some_items = list(f"{k}={v}" for k, v in some_items) | |
rep = "MainTable({})".format(", ".join(rep_some_items)) | |
return rep | |
@functools.lru_cache(maxsize=None) | |
def q_to_quietude(self) -> int: | |
q = self.args.q | |
quietude = q or 0 # as if not very hard, but nothing like as easy as this | |
return quietude | |
@functools.lru_cache(maxsize=None) | |
def v_to_verbosity(self) -> int: | |
v = self.args.v | |
verbosity = v or 0 # same deal as with 'quietude =' | |
return verbosity | |
@functools.lru_cache(maxsize=None) | |
def props_to_loudness(self) -> int: # as if lots of complex slow work | |
quietude = self.quietude | |
verbosity = self.verbosity | |
loudness = max(0, min(3, verbosity - quietude)) | |
return loudness | |
def main() -> None: | |
# Auto-complete intensely abbreviated Input | |
args = parse_args_or_quit() # often prints help and exits | |
print(args) | |
mtable = MainTable(args) | |
print(mtable) | |
# Work up recommendations from complete Input | |
way_way_way_verbose = mtable.loudness >= 3 | |
print(f"{way_way_way_verbose=}") | |
def parse_args_or_quit() -> MainArgs: | |
parser = argparse.ArgumentParser() | |
parser.add_argument("-q", action="count", help="say less") | |
parser.add_argument("-v", action="count", help="say more") | |
ns = parser.parse_args() # often prints help and exits | |
args = MainArgs( | |
q=ns.q, | |
v=ns.v, | |
) | |
return args | |
# often prints help and exits | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment