Home > Mobile >  Can I select whether I want to use a function by itself or with its decorator function?
Can I select whether I want to use a function by itself or with its decorator function?

Time:07-24

Consider this code:

def hello_decorator(func):
    def inner1(*args, **kwargs):
        
        print("before Execution")
        
        # getting the returned value
        returned_value = func(*args, **kwargs)
        print("after Execution")
        
        # returning the value to the original frame
        return returned_value
        
    return inner1


    # adding decorator to the function
    @hello_decorator
    def sum_two_numbers(a, b):
        print("Inside the function")
        return a   b
    
    a, b = 1, 2
    
    # getting the value through return of the function
    print("Sum =", sum_two_numbers(a, b))

Is there a way to use sum_two_numbers(a,b) without also having to invoke its decorator? Is there some keyword, or other way to do this?

CodePudding user response:

You can define your function without the decorator and define a different function with the decorator.

def sum_two_numbers(a, b):
    print("Inside the function")
    return a   b

sum_with_decorator = hellodecorator(sum_two_numbers)

When you define a function using the decorator

@decorator
def some_function:
   ...

you are actually defining some_function as the result of the decorator applied to the original definition of the function. This is explained in the python documentation of functions.

CodePudding user response:

You can add an argument to the wrapped function :

def hello_decorator(func):
    def inner1(*args, simple_run=False, **kwargs):
        if simple_run:
            return func(*args, **kwargs)
        else:
            print("before Execution")

            # getting the returned value
            returned_value = func(*args, **kwargs)
            print("after Execution")

            # returning the value to the original frame
            return returned_value

    return inner1


# adding decorator to the function
@hello_decorator
def sum_two_numbers(a, b):
    print("Inside the function")
    return a   b


a, b = 1, 2

# getting the value through return of the function
print("Sum =", sum_two_numbers(a, b, simple_run=True))

And if you have imported the decorator, you can do this way :

from whatever import hello_decorator


def my_hello_decorator(func):
    def inner(*args, simple_run=False, **kwargs):
        if simple_run:
            return func(*args, **kwargs)
        else:
            return hello_decorator(func)(*args, **kwargs)

    return inner


# adding decorator to the function
@my_hello_decorator
def sum_two_numbers2(a, b):
    print("Inside the function")
    return a   b


print("Sum =", sum_two_numbers2(a, b, simple_run=True))

Or as said keylongx3x0 you can create 2 different functions with and without decoration

  • Related