Skip to content

Instantly share code, notes, and snippets.

@toby-p
Last active October 29, 2020 19:01
Show Gist options
  • Save toby-p/a1e7efe327e68399a72a5cd976c9be1e to your computer and use it in GitHub Desktop.
Save toby-p/a1e7efe327e68399a72a5cd976c9be1e to your computer and use it in GitHub Desktop.
Decorator to print custom messages when executing functions, followed by a check mark when it completes.
# Class:
class PrintCheck:
"""Decorator to print a custom message when calling a function, followed by
a check/tick mark on the same line when the computation finishes. If the
function returns an integer it will be printed in parentheses with the check
mark along with the `item_name` argument, pluralized if greater than 1."""
def __init__(self, msg: str = None, print_items: bool = True,
item_name: str = "item"):
"""
Args:
msg: statement which will be printed before executing function.
print_items: whether or not to print the number returned by the
function (if an integer) in parentheses after the check mark.
item_name: custom name for the items returned by the function
printed in parentheses if `print_items` if True.
"""
if msg and not msg.endswith(" "):
msg = f"{msg} "
self.msg = msg
self.print_items = print_items
self.item_name = item_name
def check(self, n: int = None):
if isinstance(n, int) and self.print_items:
plural = "s" if (n > 1) and (not self.item_name.endswith("s")) else ""
parentheses = f"{n} {self.item_name}{plural}"
print(f"\u2714 ({parentheses})", flush=True)
else:
print(f"\u2714", flush=True)
def __call__(self, func):
def withprint(*arg, **kwarg):
if self.msg:
print(self.msg, end="", flush=True)
f = func(*arg, **kwarg)
self.check(f)
return f
return withprint
# Example usage:
import time
@PrintCheck("Custom messsage when doing something ", item_name="thing")
def do_something(x, y):
time.sleep(1)
return x ** y
result = do_something(2, 3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment