OOP & Advanced Python

Python Decorators

01 · What is a Decorator? File · Decorators · 1 of 13

What is a Decorator?

A decorator is a function that adds extra functionality to another function without changing the original function's code.

Think of it like decorating a plain cake:

Original cake → Add cream → Add chocolate → Decorated Cake

The cake is still the same cake. We just added extra features.

Original function → Decorator → Function + Extra Behavior

Python
def withdraw_money():
  print("Money Withdrawn")
Later you may want to add login validation, logging, execution time, authorization or error handling.
Instead of modifying withdraw_money() every time, we can create decorators.
02 · Functions as Objects File · Decorators · 2 of 13

Functions are First-Class Objects

In Python, functions are first-class objects. This means:

  1. We can store a function in a variable
  2. We can pass a function as an argument
  3. We can return a function from another function
Python
def greet():
  print("Good morning")

x = greet
x()
Output
Good morning
Notice: x = greet (we did not write x = greet())
greet means the function itself
greet() means execute the function
03 · Passing Functions File · Decorators · 3 of 13

Passing a Function to Another Function

Python
def greet():
  return "Good Morning"

def display(func):
  print(func())   # executes the function that was passed

display(greet)     # passes the greet function itself
Output
Good Morning
This concept is the foundation of decorators.
04 · Nested Functions File · Decorators · 4 of 13

Function Inside Another Function

Python allows nested functions.

Python
def outer():
  def inner():
    print("Inside inner function")
  inner()

outer()
Output
Inside inner function
Decorators commonly use this nested-function structure.
05 · Returning Functions File · Decorators · 5 of 13

Returning a Function

A function can also return another function.

Python
def outer():
  def inner():
    print("Hello from inner function")
  return inner

x = outer()   # outer() has finished, but inner() is still available
x()
Output
Hello from inner function
This is closely related to closures.
06 · Closures File · Decorators · 6 of 13

What is a Closure?

A closure happens when an inner function remembers information from its outer function even after the outer function has completed.

Python
def outer(name):
  def inner():
    print("Hello", name)
  return inner

x = outer("Koti")
x()
Output
Hello Koti
Even though outer() has already completed, inner() remembers name = "Koti".
Decorators heavily use closures.
07 · First Decorator (Manual) File · Decorators · 7 of 13

First Decorator without @

Python
def decorator_function(func):
  def wrapper():
    print("Before function execution")
    func()
    print("After function execution")
  return wrapper

def greet():
  print("Good morning")

greet = decorator_function(greet)
greet()
Output
Before function execution
Good morning
After function execution
Behind the scenes:
greet → decorator_function(greet) → wrapper → wrapper executes → before → greet() → after
08 · Using @ Syntax File · Decorators · 8 of 13

Using the @ Decorator Syntax

@decorator_function is equivalent to greet = decorator_function(greet)

Python
@decorator_function
def greet():
  print("Good morning")

greet()
Output
Before function execution
Good morning
After function execution
09 · Real-life Example File · Decorators · 9 of 13

Simple Real-life Example

Imagine a cinema ticket checker. Before entering the movie, someone checks whether you have a ticket.

Python
def ticket_check(func):
  def wrapper():
    print("checking ticket....")
    func()
  return wrapper

@ticket_check
def watch_movie():
  print("Enjoy the movie")

watch_movie()
Output
checking ticket....
Enjoy the movie
The decorator added ticket checking without modifying the original function logic.
10 · Decorator with Arguments File · Decorators · 10 of 13

Decorator with Function Arguments

Python
def my_decorator(func):
  def wrapper(name):
    print("Before function")
    func(name)
    print("After function")
  return wrapper

@my_decorator
def greet(name):
  print("Hello", name)

greet("Narayan")
Output
Before function
Hello Narayan
After function
11 · *args and **kwargs File · Decorators · 11 of 13

Universal Decorator with *args and **kwargs

Different functions can have different numbers of arguments. We solve this with *args and **kwargs.

Python
def my_decorator(func):
  def wrapper(*args, **kwargs):
    print("Before function")
    result = func(*args, **kwargs)
    print("After function")
    return result
  return wrapper

@my_decorator
def add(a, b):
  return a + b

result = add(10, 30)
print(result)
Output
Before function
After function
40
Always return the result of the original function, otherwise the return value is lost.
12 · Logging Decorator File · Decorators · 12 of 13

Logging Decorator

Imagine you have many banking functions and you want to log every function execution.

Python
def log_activity(func):
  def wrapper(*args, **kwargs):
    print(f"{func.__name__} started")
    result = func(*args, **kwargs)
    print(f"{func.__name__} completed")
    return result
  return wrapper

@log_activity
def transfer(amount):
  print(f"Transferring ${amount}")

transfer(5000)
Output
transfer started
Transferring $5000
transfer completed
13 · Authentication Decorator File · Decorators · 13 of 13

Authentication Decorator

Suppose only logged-in users can access a bank dashboard.

Python
logged_in = True

def login_required(func):
  def wrapper(*args, **kwargs):
    if logged_in:
      return func(*args, **kwargs)
    else:
      print("please login first")
  return wrapper

@login_required
def dashboard():
  print("Welcome to your banking dashboard")

dashboard()
Output
Welcome to your banking dashboard
If logged_in = False, the original function will not run and the user will see the message “please login first”.
Home Python Decorators

Python Decorators

Add extra functionality to functions without changing their original code.

Select any topic from the left sidebar to begin.


Start Learning →