🐍

Python Decorators Lecture Notes

Jul 11, 2024

Python Decorators Lecture Notes

Introduction

  • Speaker: Devin Wendy
  • Topic: Decorators in Python

Functions Recap

  • Purpose: Perform specific tasks
  • Example: Division function
    • Function: def division(a, b): return a / b
    • Usage: print(division(4, 2)) outputs 2.0
    • Expected Result: print(division(2, 4)) outputs 0.5

Problem Statement

  • Requirement: Ensure numerator is always greater than or equal to denominator
  • Solution Proposal: Automatically swap values if numerator < denominator

Initial Code Modification

  • Logic: Swap logic
    • Before modification: def division(a, b): return a / b
    • After modification: def division(a, b): if a < b: a, b = b, a return a / b
    • Output: division(2, 4) returns 2.0

Problem with Direct Modification

  • Scenario: Existing function in another file
    • No access to modify original function code

Introducing Decorators

  • Purpose: Add functionality to existing function without modifying it
  • Definition: A decorator is a function that takes another function and extends its behavior

Creating a Decorator

  • Decorator Function: def smart_div(func): def inner(a, b): if a < b: a, b = b, a return func(a, b) return inner
  • Usage: @smart_div def division(a, b): return a / b
    • Call: print(division(2, 4)) should output 2.0

Key Points

  • Function as Parameter: Decorators take a function as an argument
  • Function Inside Function: Can define a function within another function
  • Returning Functions: The decorator returns the inner, modified function
  • Assigning New Function:
    • Example: division = smart_div(division)

Benefits of Decorators

  • Modifies behavior without altering original function
  • Compilation Time Changes: Behavior is modified at compile-time

Summary

  • Decorators: Enhance or modify functionality of functions
  • Use Cases: Useful when original function cannot be modified or should remain unchanged
  • Python Decorators: Demonstrates Python's ability to handle function-based programming paradigms

Conclusion

  • Feedback: Encouraged to ask questions and subscribe for more content