Created
February 13, 2026 13:07
-
-
Save sunmeat/b9af78316c18b326f807cc603ac4ede5 to your computer and use it in GitHub Desktop.
приклад AOP в пайтон
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 time | |
| # декоратор: логування в консоль (через print) | |
| def log_to_console(func): | |
| def wrapper(*args, **kwargs): | |
| print(f"[log console] виклик {func.__name__} | args: {args} | kwargs: {kwargs}") | |
| try: | |
| result = func(*args, **kwargs) | |
| print(f"[log console] {func.__name__} > {result}") | |
| return result | |
| except Exception as e: | |
| print(f"[log console] помилка в {func.__name__}: {type(e).__name__} - {e}") | |
| raise | |
| wrapper.__name__ = func.__name__ # зберігаємо ім'я функції | |
| wrapper.__doc__ = func.__doc__ # зберігаємо документацію | |
| return wrapper | |
| # декоратор: логування в файл (через print + запис у файл) | |
| def log_to_file(func): | |
| def wrapper(*args, **kwargs): | |
| with open('app.log', 'a', encoding='utf-8') as f: | |
| f.write(f"[log file] виклик {func.__name__} | args: {args} | kwargs: {kwargs}\n") | |
| try: | |
| result = func(*args, **kwargs) | |
| f.write(f"[log file] {func.__name__} > {result}\n") | |
| return result | |
| except Exception as e: | |
| f.write(f"[log file] помилка в {func.__name__}: {type(e).__name__} - {e}\n") | |
| raise | |
| wrapper.__name__ = func.__name__ | |
| wrapper.__doc__ = func.__doc__ | |
| return wrapper | |
| # декоратор: вимірювання часу виконання | |
| def monitor_performance(func): | |
| def wrapper(*args, **kwargs): | |
| start = time.time() | |
| result = func(*args, **kwargs) | |
| elapsed = time.time() - start | |
| print(f"[performance] {func.__name__} виконано за {elapsed:.4f} с") | |
| return result | |
| wrapper.__name__ = func.__name__ | |
| wrapper.__doc__ = func.__doc__ | |
| return wrapper | |
| # декоратор: глобальна обробка винятків | |
| def handle_exceptions(func): | |
| def wrapper(*args, **kwargs): | |
| try: | |
| return func(*args, **kwargs) | |
| except Exception as e: | |
| print(f"[error handler] {func.__name__} > {type(e).__name__}: {e}") | |
| raise # можна замінити на return None, якщо потрібно "проковтнути" помилку | |
| wrapper.__name__ = func.__name__ | |
| wrapper.__doc__ = func.__doc__ | |
| return wrapper | |
| @log_to_console | |
| @log_to_file | |
| @monitor_performance | |
| @handle_exceptions | |
| def add_numbers(a, b): | |
| return a + b | |
| @log_to_console | |
| @log_to_file | |
| @monitor_performance | |
| @handle_exceptions | |
| def slow_divide(x, y): | |
| time.sleep(1.5) | |
| return x / y | |
| ################################################################################# | |
| if __name__ == "__main__": | |
| result = add_numbers(7, 12) | |
| print(f"результат: {result}\n") | |
| try: | |
| result = slow_divide(100, 0) | |
| print(f"результат: {result}") | |
| except ZeroDivisionError: | |
| print("ділення на нуль успішно перехоплене в зовнішньому блоці") | |
| print("\nкінець. перевірте файл app.log") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment