Skip to content

Commit 48749ce

Browse files
Refactor fn_w_counter to improve call tracking
Refactor counter function to track calls and callers.
1 parent a481448 commit 48749ce

1 file changed

Lines changed: 19 additions & 13 deletions

File tree

‎Week04/functions_aleyna_gultekin.py‎

Lines changed: 19 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -23,20 +23,26 @@ def custom_equation(x: int = 0, y: int = 0, /, a: int = 1, b: int = 1, *, c: int
2323
return float((first_term + second_term) / c)
2424

2525

26-
def _make_counter():
27-
calls = {"count": 0}
28-
by_caller = {}
26+
def fn_w_counter() -> tuple[int, dict[str, int]]:
27+
if not hasattr(fn_w_counter, "call_count"):
28+
fn_w_counter.call_count = 0
29+
fn_w_counter.callers = {}
2930

30-
def fn_w_counter() -> (int, dict[str, int]):
31-
name = fn_w_counter.__module__
32-
calls["count"] += 1
33-
if name in by_caller:
34-
by_caller[name] += 1
35-
else:
36-
by_caller[name] = 1
37-
return calls["count"], by_caller
31+
try:
32+
raise Exception
33+
except Exception as error:
34+
caller = error.__traceback__.tb_frame.f_back.f_globals["__name__"]
3835

39-
return fn_w_counter
36+
fn_w_counter.call_count += 1
37+
if caller in fn_w_counter.callers:
38+
fn_w_counter.callers[caller] += 1
39+
else:
40+
fn_w_counter.callers[caller] = 1
4041

42+
return fn_w_counter.call_count, fn_w_counter.callers
4143

42-
fn_w_counter = _make_counter()
44+
45+
if __name__ == "__main__":
46+
for _ in range(10):
47+
fn_w_counter()
48+
print(fn_w_counter())

0 commit comments

Comments
 (0)