Python Decorator: Exercises, Solutions, and Practice
Python Decorator [ 12 exercises with solution ]
[An editor is available at the bottom of the page to write and execute the scripts. Go to the editor]
Python decorators are a way to modify a function or class's behavior without directly modifying its code. They allow you to wrap a function or class around another function, adding additional functionality before, after, or around the original function's execution. Decorators are denoted by the @ symbol followed by the name of the decorator function. They provide a concise and reusable way to extend Python code functionality. They are commonly used for logging, authentication, caching, and more.
1. Write a Python program to create a decorator that logs the arguments and return value of a function.
Click me to see the sample solution
2. Write a Python program to create a decorator function to measure the execution time of a function.
Click me to see the sample solution
3. Write a Python program to create a decorator to convert the return value of a function to a specified data type.
Click me to see the sample solution
4. Write a Python program that implements a decorator to cache the result of a function.
Click me to see the sample solution
5. Write a Python program that implements a decorator to validate function arguments based on a given condition.
Click me to see the sample solution
6. Write a Python program that implements a decorator to retry a function multiple times in case of failure.
Click me to see the sample solution
7. Write a Python program that implements a decorator to enforce rate limits on a function.
Click me to see the sample solution
8. Write a Python program that implements a decorator to add logging functionality to a function.
Click me to see the sample solution
9. Write a Python program that implements a decorator to handle exceptions raised by a function and provide a default response.
Click me to see the sample solution
10. Write a Python program that implements a decorator to enforce type checking on the arguments of a function.
Click me to see the sample solution
11. Write a Python program that implements a decorator to measure the memory usage of a function.
Click me to see the sample solution
12. Write a Python program that implements a decorator to provide caching with expiration time for a function.
Click me to see the sample solution
Python Code Editor:
More to Come !
Do not submit any solution of the above exercises at here, if you want to contribute go to the appropriate exercise page.
Test your Python skills with w3resource's quiz
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/python-exercises/decorator/index.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics