Last active
October 4, 2024 05:26
-
-
Save yashshah1/39ab7c21b0c13104b1a51114c9455e38 to your computer and use it in GitHub Desktop.
flexiple decorators
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 my_decorator(method): | |
| def wrapper(self, *args, **kwargs): | |
| sig = inspect.signature(method) | |
| params = sig.parameters | |
| arg_to_check_index = list(params.keys()).index('arg_to_check') - 1 # first arg is self | |
| arg_to_check_value = args[arg_to_check_index] | |
| if arg_to_check_value <= 10: | |
| return # Return early if arg_to_check <= 10 | |
| return method(self, *args, **kwargs) # Call the original method if the check passes | |
| return wrapper | |
| class A: | |
| def method1(self, arg_to_check, arg1): | |
| print(f"Method1 called with arg_to_check={arg_to_check}, arg1={arg1}") | |
| def method2(self, arg1, arg2, arg3): | |
| print(f"Method2 called with arg2={arg2}, arg1={arg1}, arg3={arg3}") | |
| class B(A): | |
| @my_decorator | |
| def method1(self, arg_to_check, arg1): | |
| super().method1(arg_to_check, arg1) | |
| @my_decorator | |
| def method2(self, arg1, arg_to_check, arg3): | |
| super().method2(arg1, arg_to_check, arg3) | |
| # Example usage | |
| b = B() | |
| b.method1(5, "test") # Will not execute, returns early | |
| b.method1(15, "test") # Will execute | |
| b.method2("test", 8, 12) # Will not execute, returns early | |
| b.method2("test", 12, 12) # Will execute |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment