Python – How to use a staticmethod in a class as a decorator in Python?

How to use a staticmethod in a class as a decorator in Python?… here is a solution to the problem.

How to use a staticmethod in a class as a decorator in Python?

I came across an interesting scene while creating decorators in python. Here 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 the code above, I created a decorator (which is a static method in the class) that checks if the “obj_user” is passed as a parameter to the decorator function. I decorated the function find_father, but I get the following error message:- ‘staticmethod' object is not callable.

How can I use the static utility method shown above, as a decorator in Python?

Thanks in advance.

Solution

staticmethod is a descriptor. @staticmethod returns a descriptor object instead of a function. That’s why it triggers staticmethod' object is not callable.

My answer is to avoid that. I don’t think it’s necessary to make user_arg_required a static method.

After some experimentation, I found that if you still want to use static methods as decorators, here’s the hack.

@staticmethod
@user_arg_required.__get__(0)
def find_father(**search_params):
    return RelationShipSearchMgr.search(Relation.RELATION_FATHER, **search_params)

This document will tell you what a descriptor is.

https://docs.python.org/2/howto/descriptor.html

Related Problems and Solutions