Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Create a Decorator That Blocks Negative Inputs

Write a decorator that prevents functions from running if any numeric argument is negative.

Python practice15 minDecorators FundamentalsIntermediateLast updated April 15, 2026

Problem statement

Decorators can be used to enforce validation policies across many functions. Your task is to build a decorator named block_negative_values that, when applied to any function, checks all supplied positional and keyword arguments. If any argument is a numeric type (int or float) and is strictly less than 0, your decorator must short-circuit and return the exact string "Negative values not allowed" without calling the wrapped function. If no numeric negative values are present, call and return the wrapped function's result as-is. The decorator must handle: - Positional arguments (*args) - Keyword arguments (**kwargs) - Default values passed via keywords - Variable-length positional arguments Non-numeric arguments (strings, lists, dicts, objects, etc.) should be ignored by the negative check. Booleans follow Python's type hierarchy (they are subclasses of int) and will be treated as numbers (False==0, True==1).

Task

Implement a decorator @block_negative_values that inspects all positional and keyword arguments and returns a clear message if any numeric argument is negative; otherwise it should call the wrapped function and return its result.

Examples

Simple allowed call

Input

add(2, 3)

Output

5

Both arguments are non-negative integers, so the original function runs and returns their sum.

Input format

A single function call expression such as add(2, 3).

Output format

Return value of the function call. If a negative numeric argument is detected, return the exact string: "Negative values not allowed".

Constraints

Only consider int and float instances for negativity checks. Do not call the wrapped function if a negative numeric value is found. Use functools.wraps to preserve metadata.

Samples

Sample 1

Input

add(5, 7)

Output

12

Neither argument is negative; the decorator allows the call and the function returns 12.