Created
April 12, 2021 13:53
-
-
Save rednafi/97c1672abe14fd1aeba8495f6f074e7d to your computer and use it in GitHub Desktop.
Run a tagged function in python
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 functools | |
import another | |
def tag(*name): | |
def outer(func): | |
func.tag = name | |
@functools.wraps(func) | |
def inner(*args, **kwargs): | |
val = func(*args, **kwargs) | |
print(f"{name}: {val}") | |
return val | |
return inner | |
return outer | |
@tag("hello") | |
def hello(name="red"): | |
return f"hello {name}" | |
def discover_tags(funcs, *tags): | |
tagged_funcs = [] | |
for func in funcs: | |
for tag in tags: | |
if tag in (func_tag := getattr(func, "tag", None)): | |
if func_tag: | |
tagged_funcs.append(func) | |
return tagged_funcs | |
class CLI: | |
"""Access and show variables using the CLI.""" | |
def __init__(self, funcs): | |
self.funcs = funcs | |
def build_parser(self): | |
parser = argparse.ArgumentParser(description="The strangely familiar CLI") | |
# Add arguments. | |
parser.add_argument("--tag", nargs="*", help="tag") | |
return parser | |
def error_handler(self, parser, args): | |
# Deal with argument dependencies. | |
pass | |
def trigger_handler(self): | |
parser = self.build_parser() | |
args = parser.parse_args() | |
return args | |
def entrypoint(self): | |
args = self.trigger_handler() | |
tagged_funcs = discover_tags(self.funcs, *list(args.tag)) | |
if tagged_funcs: | |
for func in tagged_funcs: | |
func() | |
cli = CLI(funcs=(hello,)) | |
cli.entrypoint() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment