Advertisement
go6odn28

decorator_example

Jun 18th, 2024
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.55 KB | None | 0 0
  1. my_list = []
  2.  
  3.  
  4. def decorator(func):
  5.     def wrapper(some_item):
  6.         if isinstance(some_item, str):
  7.             result = func(some_item)
  8.             print(f"{some_item} added to the list")
  9.             return result
  10.         else:
  11.             print(f"Error: {some_item} is not a string and won't be added to the list.")
  12.             return None
  13.     return wrapper
  14.  
  15.  
  16. @decorator
  17. def add_to_list(item):
  18.     my_list.append(item)
  19.  
  20.  
  21. add_to_list("hello")
  22. add_to_list(123)  # not added
  23. add_to_list("world")
  24.  
  25. print(my_list)  #  ['hello', 'world']
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement