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()
source share