Last active
March 25, 2023 10:43
-
-
Save FuruNov/04cc46a57eceadc561bd7fc3fd45428a to your computer and use it in GitHub Desktop.
関数の呼び出しに用いた引数をロギングする Python プログラム
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
| import inspect | |
| def log_arguments(func): | |
| def wrapper(*args, **kwargs): | |
| signature = inspect.signature(func) | |
| bound_arguments = signature.bind(*args, **kwargs) | |
| bound_arguments.apply_defaults() | |
| args_list = [] | |
| for name, value in bound_arguments.arguments.items(): | |
| arg_type = ( | |
| signature.parameters[name].annotation.__name__ | |
| if signature.parameters[name].annotation != inspect.Parameter.empty | |
| else type(value).__name__ | |
| ) | |
| args_list.append(f"{name}:{arg_type}={value!r}") | |
| print(f"Calling {func.__name__}({', '.join(args_list)})") | |
| return func(*args, **kwargs) | |
| return wrapper | |
| @log_arguments | |
| def my_function(x: int, y: float, z: str = "default"): | |
| return x + y * len(z) | |
| result = my_function(2, y=3.0) | |
| print(result) # 8 | |
| result = my_function(2, y=3.0, z="test") | |
| print(result) # 11 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment