Python decorator function called at compile time

I hope someone who is familiar with Python compilation / runtime procedures can shed light on my question regarding how Python compiles the decorator.

In my code example, I included a test print request in the "writeit" decorator just before the logtofile closure was defined. If you run all the code I have provided, for each @writeit decorator defined in the Customer class, the print request "test" in printit is called before writeit is ever used.

Why is logtofile called at compile time? Can anyone explain this behavior?

def writeit(func): print('testing') def logtofile(customer, *arg, **kwargs): print('logtofile') result = func(customer, *arg, **kwargs) with open('dictlog.txt','w') as myfile: myfile.write(func.__name__) return result return logtofile class Customer(object): def __init__(self,firstname,lastname,address,city,state,zipcode): self._custinfo = dict(firstname=firstname,lastname=lastname,address=address,city=city,state=state,zipcode=zipcode) @writeit def setFirstName(self,firstname): print('setFirstName') self._custinfo['firstname']=firstname @writeit def setLastName(self,lastname): print('setLastName') self._custinfo['lastname']=lastname @writeit def setAddress(self,address): print('setAddress') self._custinfo['address']=address def main(): cust1 = Customer('Joe','Shmoe','123 Washington','Washington DC','DC','12345') cust1.setFirstName('Joseph') cust1.setLastName('Shmoestein') if(__name__ == '__main__'): main() 
+4
source share
2 answers

Your code runs when the module is imported. Python executes all top-level instructions, including class definitions at this time.

The body of the class definition is executed as a function, and the local namespace becomes an attribute of the class. This means that the class bodies are executed upon import if the class is defined at the top level of the module.

When Python encounters a decorated function at runtime, it will define the class, then execute the decorator function, passing the function object and binding the return value of the decorator to the function name. Since the body of the class is executed at the time of import, this means that your decorator is being executed at this time.

+6
source

There is no compilation time. The def statement and associated decoder calls are executable operations.

Accordingly, when Python loads the module, it executes the instructions in order. When a class instruction is executed at one of the early stages, all the operators in the class are executed. As part of this, def are run to create functions, and these functions will be passed to decorators for processing.

Your print request "test" will be executed whenever the decorator is called, and not when the function that it returns is called. If you want this behavior, move the decorator to an internal function.

+1
source

Source: https://habr.com/ru/post/1495352/


All Articles