I have encountered an interesting scenario, while creating decorator in python. Following is my code :-
class RelationShipSearchMgr(object):
@staticmethod
def user_arg_required(obj_func):
def _inner_func(**kwargs):
if "obj_user" not in kwargs:
raise Exception("required argument obj_user missing")
return obj_func(*tupargs, **kwargs)
return _inner_func
@staticmethod
@user_arg_required
def find_father(**search_params):
return RelationShipSearchMgr.search(Relation.RELATION_FATHER, **search_params)
As shown in above code, I have created a decorator(which is static method in class), which checks, if "obj_user" is passed as argument to decorated function. I have decorated function find_father
, but I am getting following error message :- 'staticmethod' object is not callable
.
How to use static utility method as shown above, as decorator in python ?
Thanks in advance.
staticmethod
is a descriptor . @staticmethod
return a descriptor object instead of a function
. That why it raises staticmethod' object is not callable
.
My answer is simply avoid doing this. I don't think it's necessary to make user_arg_required
a static method.
After some play around, I found there is hack if you still want to use static method as decorator.
@staticmethod
@user_arg_required.__get__(0)
def find_father(**search_params):
return RelationShipSearchMgr.search(Relation.RELATION_FATHER, **search_params)
This doc will tell you what is descriptor.
After digging a bit, I found that, staticmethod object has __func__
internal variable __func__
, which stores the raw function to be executed.
So, following solution worked for me :-
@staticmethod
@user_arg_required.__func__
def find_father(**search_params):
return RelationShipSearchMgr.search(Relation.RELATION_FATHER, **search_params)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.