Editor

Write a Validation Decorator

Advanced · Write the code · from Python Decorators Explained: A Step-by-Step Guide

From the lesson: What Are the Most Useful Real-World Decorators?

Decorators shine in real-world applications. Here are three patterns you'll see constantly: timing, caching, and validation.

Read this part of the lesson

Write a decorator validate_positive that checks if all positional arguments to the decorated function are positive numbers (> 0). If any argument is not positive, print 'Error: all arguments must be positive' and return None. Otherwise, call and return the function normally.

@validate_positive
def multiply(a, b):
    return a * b

print(multiply(3, 4))   # 12
print(multiply(-1, 5))  # Error: all arguments must be positive \n None
from functools import wraps
def validate_positive(func):
# Write your decorator here
pass
@validate_positive
def multiply(a, b):
return a * b
print(multiply(3, 4))
print(multiply(-1, 5))

More Decorator exercises

All Python exercises · 50 practice problems · Advanced Python quiz