1. Home
  2. Coding Hub
  3. Coding Notes
  4. Python
  5. Decorators
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
05Hrs
34Mins
51Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Python
  5. Decorators

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
05Hrs
34Mins
51Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
Python IntroductionInterpreter & BytecodeSyntax & IndentationDynamic VariablesPrimitive TypesType CastingInput & Output
Arithmetic OperatorsLogical & Bitwise Operatorsis vs ==if / elsematch / casefor Loopswhile LoopsLoop Control (break, continue)
String IndexingString SlicingString MethodsF-StringsRegex Basics
List BasicsList OperationsList ComprehensionsTuplesSetsDictionary BasicsDictionary MethodsDict Comprehensionscollections Moduleheapq & bisectUnpacking Operators (*, **)
Function Basics*args & **kwargsLEGB ScopeLambda Functionsmap, filter, zipClosuresDecoratorsType Hinting
Classes & Objects__init__ & selfClass Methods & Static MethodsInheritance & super()Duck TypingEncapsulation & PropertiesDunder MethodsData Classes
Memory ManagementShallow vs Deep Copytry / exceptCustom ExceptionsContext Managers (with)File & JSON Operations
IteratorsGenerators & yieldVirtual EnvironmentsGIL & Threadingasyncio Basics
Python

Decorators

Overview

Decorators are an advanced application of Closures. They allow you to dynamically modify or wrap the behavior of a function without permanently modifying the function's source code. You pass the target function into the decorator, the decorator wraps it in extra logic (like logging, authentication, or timing), and returns the enhanced function. The @ symbol is just elegant syntactic sugar that applies the decorator instantly.

Syntax

python
import time

# 1. The Decorator Definition
def timer_decorator(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        
        # Execute the original function
        result = func(*args, **kwargs) 
        
        end = time.time()
        print(f"[{func.__name__}] executed in {end - start:.4f}s")
        return result
        
    return wrapper

# 2. Applying the Decorator
@timer_decorator
def heavy_computation():
    return sum(i**2 for i in range(1_000_000))

# The timer logic wraps the computation seamlessly
heavy_computation()

Common Pitfalls

  • Forgetting to include *args, **kwargs in the inner wrapper function. If omitted, the decorated function will crash if it tries to accept any arguments.
  • Losing function metadata. Wrapping a function replaces its name and docstring with the wrapper's name. Always use @functools.wraps(func) on the wrapper to preserve the original function's identity.

Interview Questions

What does the @decorator syntax actually do under the hood?

It is pure syntactic sugar. Writing @my_decorator above def my_func(): is exactly equivalent to writing my_func = my_decorator(my_func) after the function is defined.

Real-World Example

Authentication checking in web frameworks like Flask or Django.

example
python
import functools

def require_admin(func):
    @functools.wraps(func)
    def wrapper(user, *args, **kwargs):
        if user.role != "admin":
            raise PermissionError("Access Denied: Admins Only")
        # Proceed if authorized
        return func(user, *args, **kwargs)
    return wrapper

@require_admin
def delete_database(user):
    print("Database deleted.")

Check Your Knowledge

Test your understanding of Decorators with these quick questions.

Question 1

Why is `@functools.wraps(func)` highly recommended when writing custom decorators?

Take Python Quiz
Outline
Python IntroductionInterpreter & BytecodeSyntax & IndentationDynamic VariablesPrimitive TypesType CastingInput & Output
Arithmetic OperatorsLogical & Bitwise Operatorsis vs ==if / elsematch / casefor Loopswhile LoopsLoop Control (break, continue)
String IndexingString SlicingString MethodsF-StringsRegex Basics
List BasicsList OperationsList ComprehensionsTuplesSetsDictionary BasicsDictionary MethodsDict Comprehensionscollections Moduleheapq & bisectUnpacking Operators (*, **)
Function Basics*args & **kwargsLEGB ScopeLambda Functionsmap, filter, zipClosuresDecoratorsType Hinting
Classes & Objects__init__ & selfClass Methods & Static MethodsInheritance & super()Duck TypingEncapsulation & PropertiesDunder MethodsData Classes
Memory ManagementShallow vs Deep Copytry / exceptCustom ExceptionsContext Managers (with)File & JSON Operations
IteratorsGenerators & yieldVirtual EnvironmentsGIL & Threadingasyncio Basics
Python

Decorators

Overview

Decorators are an advanced application of Closures. They allow you to dynamically modify or wrap the behavior of a function without permanently modifying the function's source code. You pass the target function into the decorator, the decorator wraps it in extra logic (like logging, authentication, or timing), and returns the enhanced function. The @ symbol is just elegant syntactic sugar that applies the decorator instantly.

Syntax

python
import time

# 1. The Decorator Definition
def timer_decorator(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        
        # Execute the original function
        result = func(*args, **kwargs) 
        
        end = time.time()
        print(f"[{func.__name__}] executed in {end - start:.4f}s")
        return result
        
    return wrapper

# 2. Applying the Decorator
@timer_decorator
def heavy_computation():
    return sum(i**2 for i in range(1_000_000))

# The timer logic wraps the computation seamlessly
heavy_computation()

Common Pitfalls

  • Forgetting to include *args, **kwargs in the inner wrapper function. If omitted, the decorated function will crash if it tries to accept any arguments.
  • Losing function metadata. Wrapping a function replaces its name and docstring with the wrapper's name. Always use @functools.wraps(func) on the wrapper to preserve the original function's identity.

Interview Questions

What does the @decorator syntax actually do under the hood?

It is pure syntactic sugar. Writing @my_decorator above def my_func(): is exactly equivalent to writing my_func = my_decorator(my_func) after the function is defined.

Real-World Example

Authentication checking in web frameworks like Flask or Django.

example
python
import functools

def require_admin(func):
    @functools.wraps(func)
    def wrapper(user, *args, **kwargs):
        if user.role != "admin":
            raise PermissionError("Access Denied: Admins Only")
        # Proceed if authorized
        return func(user, *args, **kwargs)
    return wrapper

@require_admin
def delete_database(user):
    print("Database deleted.")

Check Your Knowledge

Test your understanding of Decorators with these quick questions.

Question 1

Why is `@functools.wraps(func)` highly recommended when writing custom decorators?

Take Python Quiz

Python coding notes for Indian students — 58 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Python

  1. Python Introduction
  2. Interpreter & Bytecode
  3. Syntax & Indentation
  4. Dynamic Variables
  5. Primitive Types
  6. Type Casting
  7. Input & Output
  8. Arithmetic Operators
  9. Logical & Bitwise Operators
  10. is vs ==
  11. if / else
  12. match / case
  13. for Loops
  14. while Loops
  15. Loop Control (break, continue)
  16. String Indexing
  17. String Slicing
  18. String Methods
  19. F-Strings
  20. Regex Basics
  21. List Basics
  22. List Operations
  23. List Comprehensions
  24. Tuples
  25. Sets
  26. Dictionary Basics
  27. Dictionary Methods
  28. Dict Comprehensions
  29. collections Module
  30. heapq & bisect
  31. Unpacking Operators (*, **)
  32. Function Basics
  33. *args & **kwargs
  34. LEGB Scope
  35. Lambda Functions
  36. map, filter, zip
  37. Closures
  38. Decorators
  39. Type Hinting
  40. Classes & Objects
  41. __init__ & self
  42. Class Methods & Static Methods
  43. Inheritance & super()
  44. Duck Typing
  45. Encapsulation & Properties
  46. Dunder Methods
  47. Data Classes
  48. Memory Management
  49. Shallow vs Deep Copy
  50. try / except
  51. Custom Exceptions
  52. Context Managers (with)
  53. File & JSON Operations
  54. Iterators
  55. Generators & yield
  56. Virtual Environments
  57. GIL & Threading
  58. asyncio Basics

Study next

  • All coding notes
  • Python notes home
  • Python certification quiz
  • Online compiler
  • Interview Q&A

Python coding notes for Indian students — 58 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Python

  1. Python Introduction
  2. Interpreter & Bytecode
  3. Syntax & Indentation
  4. Dynamic Variables
  5. Primitive Types
  6. Type Casting
  7. Input & Output
  8. Arithmetic Operators
  9. Logical & Bitwise Operators
  10. is vs ==
  11. if / else
  12. match / case
  13. for Loops
  14. while Loops
  15. Loop Control (break, continue)
  16. String Indexing
  17. String Slicing
  18. String Methods
  19. F-Strings
  20. Regex Basics
  21. List Basics
  22. List Operations
  23. List Comprehensions
  24. Tuples
  25. Sets
  26. Dictionary Basics
  27. Dictionary Methods
  28. Dict Comprehensions
  29. collections Module
  30. heapq & bisect
  31. Unpacking Operators (*, **)
  32. Function Basics
  33. *args & **kwargs
  34. LEGB Scope
  35. Lambda Functions
  36. map, filter, zip
  37. Closures
  38. Decorators
  39. Type Hinting
  40. Classes & Objects
  41. __init__ & self
  42. Class Methods & Static Methods
  43. Inheritance & super()
  44. Duck Typing
  45. Encapsulation & Properties
  46. Dunder Methods
  47. Data Classes
  48. Memory Management
  49. Shallow vs Deep Copy
  50. try / except
  51. Custom Exceptions
  52. Context Managers (with)
  53. File & JSON Operations
  54. Iterators
  55. Generators & yield
  56. Virtual Environments
  57. GIL & Threading
  58. asyncio Basics

Study next

  • All coding notes
  • Python notes home
  • Python certification quiz
  • Online compiler
  • Interview Q&A