|
| 1 | + |
| 2 | + |
| 3 | +import sys |
| 4 | + |
| 5 | +# x positional-only (default 0), e positional-or-keyword (default 1) |
| 6 | +custom_power = lambda x=0, /, e=1: x ** e |
| 7 | + |
| 8 | + |
| 9 | +def custom_equation( |
| 10 | + x: int = 0, |
| 11 | + y: int = 0, |
| 12 | + /, |
| 13 | + a: int = 1, |
| 14 | + b: int = 1, |
| 15 | + *, |
| 16 | + c: int = 1, |
| 17 | +) -> float: |
| 18 | + """ |
| 19 | + Calculate (x**a + y**b) / c. |
| 20 | +
|
| 21 | + :param x: first base (positional-only) |
| 22 | + :type x: int |
| 23 | + :param y: second base (positional-only) |
| 24 | + :type y: int |
| 25 | + :param a: exponent of x (positional-or-keyword) |
| 26 | + :type a: int |
| 27 | + :param b: exponent of y (positional-or-keyword) |
| 28 | + :type b: int |
| 29 | + :param c: divisor (keyword-only) |
| 30 | + :type c: int |
| 31 | + :return: the value of (x**a + y**b) / c |
| 32 | + :rtype: float |
| 33 | + """ |
| 34 | + return (x ** a + y ** b) / c |
| 35 | + |
| 36 | + |
| 37 | +_call_counts: dict[str, int] = {} |
| 38 | +_total_calls: int = 0 |
| 39 | + |
| 40 | + |
| 41 | +def fn_w_counter() -> (int, dict[str, int]): |
| 42 | + """ |
| 43 | + Count the calls made to this function together with caller information. |
| 44 | +
|
| 45 | + :return: total number of calls and a dictionary mapping each caller's |
| 46 | + ``__name__`` to the number of calls made from that caller |
| 47 | + :rtype: tuple[int, dict[str, int]] |
| 48 | + """ |
| 49 | + global _total_calls |
| 50 | + caller = sys._getframe(1).f_globals.get("__name__", "<unknown>") |
| 51 | + _total_calls += 1 |
| 52 | + _call_counts[caller] = _call_counts.get(caller, 0) + 1 |
| 53 | + return _total_calls, dict(_call_counts) |
| 54 | + |
| 55 | + |
| 56 | +if __name__ == "__main__": |
| 57 | + assert custom_power(2) == 2 |
| 58 | + assert custom_power(2, 3) == 8 |
| 59 | + assert custom_power(2, e=2) == 4 |
| 60 | + |
| 61 | + assert custom_equation(2, 3) == 5.0 |
| 62 | + assert custom_equation(2, 3, 2) == 7.0 |
| 63 | + assert custom_equation(2, 3, 2, 3) == 31.0 |
| 64 | + assert custom_equation(3, 5, a=2, b=3, c=4) == 33.5 |
| 65 | + assert custom_equation(3, 5, 2, b=3, c=4) == 33.5 |
| 66 | + assert custom_equation(3, 5, 2, 3, c=4) == 33.5 |
| 67 | + |
| 68 | + for i in range(10): |
| 69 | + fn_w_counter() |
| 70 | + assert fn_w_counter() == (11, {'__main__': 11}) |
| 71 | + print("All examples passed.") |
0 commit comments