Home > Back-end >  use of function , in python decorator
use of function , in python decorator

Time:05-02

can someone explain how this code is working?

I mean I didn't execute the inner() function after I defined it. So how was it executed?

I mean I did execute the hi() function, but how does it translate to the inner() function being executed?

def outer(msg):
    text = msg

    def inner():
        print(text)
    return inner

hi = outer('hi')



hi()

CodePudding user response:

Your outer function returns inner. Hence hi = inner, and when you call hi() you're calling inner().

CodePudding user response:

You have to realise that functions often have a return at the end. In this case your outer() function has: return inner which is the inner function defined there.

Also you must know that when you call a function which has a return, you can get hold of what is returned by assigning a variable to take that value.

Your code does this also with: hi = outer('hi'). Now your hi variable holds the reference to inner, which being a function can be called.

Your code does this also with: hi() which invokes inner() which executes and calls print(text).

CodePudding user response:

The function outer is basically building a new function called inner (with a proloaded text message), and returning its handle. This construction is sometimes called "factory", because you are creating a new function with pre-loaded arguments.

The code is perfectly functional. However, it's usually considered better to define a class initialized with all the desired parameters, such as text. This helps others to understand the code better, and it looks more professional.

PS. Beware that factory functions, such as outer->inner, can easily introduce bugs. For example, consider this code:

def outer(msg):
    text = msg
    def inner():
        print(text)
    text = 'bug'
    return inner
hi = outer('hi')
hi()
# prints "bug"

The meaning of text was changed after the function inner was created, but it was still affected. This is because the variable text is read from the dictionary of variables defined for the parent function (outer) at runtime. Thus, in complex applications, it can be stressing to ensure that a function such as inner is working properly.

  • Related