Function Decorators in Python

Gurpreet Dhami
Lets Learn Python
Published in
2 min readMay 27, 2024

--

First function decorator without arguments

def say_hi(func):
def inner_wrapper():
print("hi from decorator")
func()

return inner_wrapper


@say_hi
def actual_func():
print("I am the actual function")


actual_func()
OUTPUT: 
>>> hi from decorator
I am the actual function

Now, With fixed arguments

def validate_age(func):
def validator(age: int):
if age > 140 or age < 0:
print("age is invalid")
else:
print("age is valid")

return validator


@validate_age
def set_age(input_age: int):
age = input_age


set_age(150)
set_age(50)
OUTPUT:
age is invalid
age is valid

Now, With variable number of arguments

You may first read this article which explained the use of *args and **kwargs. Because this concepts is used in decorators.

https://medium.com/lets-learn-python/use-of-args-and-kargs-3e3bf25853ff

This decorator function validates the paramaters of the report card of a school student.

  • It validated if the name is in string format.
  • It validated age to be >0 and <140
  • It validated marks to be >0 and <100.

--

--