3

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.

Mangu Singh Rajpurohit
  • 10,806
  • 4
  • 68
  • 97

2 Answers2

3

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.

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

gzc
  • 8,180
  • 8
  • 42
  • 62
0

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)
Mangu Singh Rajpurohit
  • 10,806
  • 4
  • 68
  • 97