Menu

Sign in to track your progress and unlock all features.

Theme style

Log in
01. Implement a Basic Function DecoratorE02. Apply @syntax to Wrap a FunctionE03. Preserve Function Metadata with functools.wrapsE

Problem No 2

Apply @syntax to Wrap a Function

Easy

8 minute session

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.

Code editor
Loading editor…

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.

09:16 AM

Free preview includes 1 Teach Theory response and 1 AI hint on each of the first 3 lessons in this module.