CodingNic

Intermediate Python

Decorators

Intermediate Python 34 min read

Decorators

Decorators

Sometimes you want to add extra behavior to a function without changing the function itself.

Python gives us decorators for this.

Decorators are common in real Python projects and frameworks.

What Is a Decorator?

A decorator is a function that wraps another function and adds extra behavior.

Examples:

  • logging
  • timing
  • access checks
  • validation
  • formatting output

Why Decorators Matter

Decorators help you:

  • reuse code
  • keep functions clean
  • separate extra logic
  • apply the same behavior to many functions

Functions Are Objects

In Python, functions can be stored in variables and passed to other functions.

python
def hello():
    print("Hello")

greet = hello
greet()

Output

text
Hello

This is why decorators are possible.

Basic Decorator Example

python
def decorator(func):
    def wrapper():
        print("Before")
        func()
        print("After")
    return wrapper

def greet():
    print("Hello")

greet = decorator(greet)

greet()

Output

text
Before
Hello
After

Using @ Syntax

Python gives a cleaner way.

python
def decorator(func):
    def wrapper():
        print("Before")
        func()
        print("After")
    return wrapper

@decorator
def greet():
    print("Hello")

greet()

Output

text
Before
Hello
After

Decorator with Arguments

python
def decorator(func):
    def wrapper(name):
        print("Start")
        func(name)
        print("End")
    return wrapper

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

greet("Tom")

Output

text
Start
Hello Tom
End

Real Example: Simple Logger

python
def log_call(func):
    def wrapper():
        print("Function running")
        func()
    return wrapper

@log_call
def save():
    print("Saved")

save()

Output

text
Function running
Saved

Code Along

Create a decorator that prints:

  • Start
  • then runs function
  • then prints Done

Mini Challenge

Create a decorator named stars.

Tasks:

When used on a function, print:

text
*****
Hello
*****

Expected output:

text
*****
Hello
*****

Real World Use Case

Decorators are used in web frameworks, authentication, caching, logging, and testing tools.

Quiz

  1. What is a decorator?
  2. Why are decorators useful?
  3. What does @decorator_name do?
  4. Can decorators add behavior before and after a function?

Assignment

Create a decorator that prints Running... before a function executes.

Summary

You learned how decorators wrap functions and add reusable behavior without changing the original function.