Skip to content

Instantly share code, notes, and snippets.

@kidig
Created June 15, 2022 15:46
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 kidig/a0cd54ac183652232f40f56a489ad730 to your computer and use it in GitHub Desktop.
Save kidig/a0cd54ac183652232f40f56a489ad730 to your computer and use it in GitHub Desktop.
from collections import Counter
from typing import NamedTuple
class Stats(NamedTuple):
success: int
fails: int
def count(func):
counter = Counter({"success": 0, "fails": 0})
def wrapper(*args, **kwargs):
try:
res = func(*args, **kwargs)
counter["success"] += 1
except Exception as e:
counter["fails"] += 1
raise e
def stats():
return Stats(**counter)
wrapper.stats = stats
return wrapper
@count
def bar(x=1):
return 10/x
@count
def foo(y):
return y**2
try:
bar()
bar(50)
bar(0)
except:
pass
try:
foo(1)
foo(0)
except:
pass
print("bar:", bar.stats())
print("foo:", foo.stats())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment