Python decorator function flow

I am trying to understand the following example, which I found explaining decorators:

#!/usr/bin/python

def get_text(name):
   return "lorem ipsum, {0} dolor sit amet".format(name)

def p_decorate(func):
    def func_wrapper(name):
        return "<p>{0}</p>".format(func(name))
    #return "1"
     return func_wrapper


get_text = p_decorate(get_text)

print get_text("John")

The result of this:

<p>lorem ipsum, John dolor sit amet</p>

I decided to try changing this feature and commenting return func_wrapperand replacing it with return "1".

When I do this, I get an error message:

TypeError: 'str' object is not callable

I have 2 questions:

  • When the line

    print get_text("John") 
    
    Performed

    def func_wrapper(name):
    

    initialized with "John"? What is the sequence of events after executing this line?

  • Why am I getting this error because, in the end, it ultimately doesn't come back string?

If anyone could explain the flow of events with this code, I would really appreciate it.

+4
source share
2 answers

You named the decorator here:

get_text = p_decorate(get_text)

(, ) , .

p_decorate() "1", , "" get_text, . , .

p_decorate() func_wrapper(), get_text , . get_text('John') . func_wrapper() 'John' , . - , , , Python, .

func_wrapper(), , , func(), p_decorate(). , - , , p_decorate(get_text), func, get_text. func() .

Python Tutor.

+2

.

, :

def decorator(func):
    def wrapper(*args, **kwargs):
        print('My args:', *args, **kwargs)
        return func(*args, **kwargs)
    return wrapper

, :

def my_function(*args, **kwargs):
    pass
my_function = decorator(my_function)
+1

All Articles