Lesson guide
What this Python exercise practices
Apply @syntax to Wrap a Function is a beginner practice lesson that focuses on functions, parameters, return values. It is designed to be solved in about 8 minutes with examples, starter code, and test feedback.
Prerequisites
- Python variables
- Function parameters
- Return values
Difficulty and time
- Level
- Beginner
- Estimated time
- 8 minutes
Practice path
Related public exercises
Summary
Use @decorator syntax and functools.wraps to wrap functions while preserving metadata.
Problem statement
Create a decorator called make_upper that: - Converts the string returned by the wrapped function to uppercase. - Uses functools.wraps to preserve the wrapped function's __name__ and __doc__. - Raises a TypeError if the wrapped function returns a non-string result. Apply this decorator using the @syntax to the provided example functions. Ensure the decorator works for functions with and without parameters.
Task
Implement a decorator make_upper that converts string results from a wrapped function to uppercase and preserves the function's __name__ and __doc__.
Examples
Uppercasing a greeting
Input
greet('world')
Output
HELLO WORLD
Explanation
greet returns 'hello world'; the decorator converts it to 'HELLO WORLD'.
Input format
A call expression or attribute access on a decorated function, e.g. greet('name') or greet.__name__
Output format
The return value of the decorated function or a preserved attribute like __name__ or __doc__.
Constraints
- Use functools.wraps in the decorator. - The decorator should accept functions that take any arguments. - If the wrapped function returns a non-string, raise TypeError. - Preserve function metadata (__name__, __doc__).
Samples
Sample input 0
greet('Ada')
Sample output 0
HELLO ADA
Explanation 0
Greeting is returned then uppercased.
AI assistant
Ask me anything!
Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.
Chat history is temporary and will not be saved.
Free preview includes 1 Teach Theory response and 1 AI hint on each of the first 3 lessons in this module.