Disadvantages of 1.python Decorators
Adorners allow us to add additional functionality without changing the way the function or method is invoked;
As shown below, we want to increase the adorner check_is_admin before the method in which to determine whether the user executing the method of the class is the admin user;
Def check_is_admin (f): def wrapper (*args,**kwargs): if Kwargs.get (' username ')! = ' Admin ': raise Exception ("This user isn't allowed to get food") return F (*args,**kwargs) return Wrapperclass Store (object):
@check_is_admin def get_food (self,username,food): return Self.storage.get (food) @check_is_admin def put_food (self,username,food): self.storage.put (food)
However, the properties of Func_name and Func_doc are lost after the decorator-modified function.
As follows:
def foobar (username= "Someone"): "" "do Crzay staff. " " Passprint foobar.func_docprint foobar.func_name Execution result is: do Crzay Staff.foobar
What if I add an adorner to the above function?
Def is_admin (f): def wrapper (*args,**kwargs): if Kwargs.get (*args,**kwargs): Raise Exception ("This user Is isn't allowed to get food ") return F (*args,**kwargs) return wrapper@is_admindef foobar (username=" Someone "): "" "do Crazy Staff" "" passprint foobar.__doc__print foobar.__name__ Execution result is: Nonewrapper
2. Solution
Use Functools's update_wrapper function to solve the problem
As follows:
Def is_admin (f): def wrapper (*args,**kwargs): if Kwargs.get (*args,**kwargs): Raise Exception ("This user Is isn't allowed to get food ") return F (*args,**kwargs) return wrapperdef foobar (username=" Someone "):" "" Crazy Staff "" " passimport Functoolsfoobar = Functools.update_wrapper (is_admin,foobar) Print Foobar.__name__print Foobar.__doc__ execution results are as follows: Foobardo crazy Staff
The disadvantages of Python decorators and how to solve them