Tuesday, August 26, 2025

🐍BASIC SYNTAX OF DECORATOR

Now that we know what decorators are, let’s learn their basic structure and how they work behind the scenes.

1) General Syntax

The most basic structure of a decorator looks like this:


def decorator_function(original_function):
    def wrapper_function():
        # Code before
        print("Something before the function runs")
        
        original_function()  # Call the original function
        
        # Code after
        print("Something after the function runs")
    return wrapper_function

Here, decorator_function takes another function as input, defines a wrapper_function that adds extra behavior, and then returns it.

2) Applying the Decorator


def decorator_function(original_function):
    def wrapper_function():
        print("Before execution")
        original_function()
        print("After execution")
    return wrapper_function

def say_hello():
    print("Hello, world!")

# Manually applying decorator
decorated = decorator_function(say_hello)
decorated()

# Using @ syntax (recommended)
@decorator_function
def say_hi():
    print("Hi there!")

say_hi()

Using the @ symbol is simply shorthand for wrapping a function manually. Both approaches produce the same result.

3) Key Points to Remember

  • The decorator itself is a function.
  • It takes another function as an argument.
  • It usually defines a wrapper function that adds behavior.
  • It returns the wrapper instead of the original function.

4) Common Beginner Errors

  • Forgetting to return the wrapper function → leads to NoneType is not callable.
  • Not calling the orighttps://youraskedu.blogspot.com/2025/08/decorators-with-arguments-in-python.htmlinal function inside wrapper → decorated function loses its original behavior.
  • Wrong indentation → decorators depend heavily on correct indentation since functions are nested.

🖥️ Practice in Browser

No comments:

Post a Comment

🐍What is scikitlearn??