Hib6498

python_decorator

Nov 21st, 2025
208
0
6 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.32 KB | Source Code | 0 0
  1. import logging
  2. from time import perf_counter
  3. from functools import wraps
  4.  
  5. logging.basicConfig(
  6.     format="%(asctime)s - %(levelname)s - %(message)s",
  7.     level=logging.DEBUG,
  8.     datefmt="%Y-%m-%d %H:%M:%S"
  9. )
  10.  
  11. def timer(func):
  12.     @wraps(func)
  13.     def _timer(*args, **kwargs):
  14.         logging.info(f"Executing {func.__name__}.")
  15.         start = perf_counter()
  16.         result = func(*args, **kwargs)
  17.         end = perf_counter()
  18.         logging.info(f"Executed {func.__name__} in {start-end: .6f} seconds.")
  19.         return result
  20.     return _timer
  21.  
  22. @timer
  23. def elementwise_unsafe_divide(array, divisor):
  24.     if not all((divisor, isinstance(divisor, int))):
  25.         logging.critical("Invalid divisor provided:", divisor)
  26.         exit(1)
  27.        
  28.     result = []
  29.     invalid_operations = 0
  30.  
  31.     for elem in array:
  32.         try:
  33.             result.append(elem / divisor)
  34.         except (ZeroDivisionError, TypeError):
  35.             invalid_operations += 1
  36.             result.append(elem)
  37.             continue
  38.  
  39.     logging.warning(f"Encountered {invalid_operations} invalid operations")
  40.     return result
  41.  
  42. def main():
  43.     arr = [1, 2, 4, "hi", "bye"]
  44.     print("Array:", arr)
  45.     result = elementwise_unsafe_divide(arr, 4)
  46.     print("arr / 4(elementwise):", result)
  47.    
  48. if __name__ == "__main__":
  49.     main()
Advertisement
Add Comment
Please, Sign In to add comment