Created
August 23, 2025 18:42
-
-
Save mahenzon/eaa61afe82f50b28e89a2a0e81c61adc to your computer and use it in GitHub Desktop.
Python Concatenate annotation example
This file contains hidden or 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
| from functools import wraps | |
| from timeit import default_timer | |
| from typing import reveal_type, Callable, Concatenate | |
| type ExecutionTime = float | |
| def with_execution_time[**P, T]( | |
| func: Callable[P, T], | |
| ) -> Callable[P, tuple[T, ExecutionTime]]: | |
| @wraps(func) | |
| def wrapper(*args: P.args, **kwargs: P.kwargs) -> tuple[T, ExecutionTime]: | |
| start_time = default_timer() | |
| result = func(*args, **kwargs) | |
| end_time = default_timer() | |
| total_time = end_time - start_time | |
| return result, total_time | |
| return wrapper | |
| def verbose_call[**P, T]( | |
| func: Callable[P, T], | |
| ) -> Callable[Concatenate[str, P], T]: | |
| @wraps(func) | |
| def wrapper(msg: str, /, *args: P.args, **kwargs: P.kwargs) -> T: | |
| print(f"[{msg}] call {func.__name__} with {args=}, {kwargs=}") | |
| return func(*args, **kwargs) | |
| return wrapper | |
| @with_execution_time | |
| def get_powers(num: int) -> dict[int, int]: | |
| return {n: n**n for n in range(1, num + 1)} | |
| @verbose_call | |
| def square(num: int) -> int: | |
| return num**2 | |
| def main() -> None: | |
| powers, exec_time = get_powers(1_000) | |
| print(f"took {exec_time:.4f} for {len(powers)} powers") | |
| reveal_type(powers) | |
| reveal_type(exec_time) | |
| # powers, exec_time = get_powers(10_000) | |
| # print(f"took {exec_time:.4f} for {len(powers)} powers") | |
| sq5 = square("five", 5) | |
| print("5 squared:", sq5) | |
| sq3 = square("three", num=3) | |
| print("3 squared:", sq3) | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment