Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Decorated staticmethod receives non-callable method

Tags:

People also ask

What is Staticmethod decorator in Python?

The @staticmethod is a built-in decorator that defines a static method in the class in Python. A static method doesn't receive any reference argument whether it is called by an instance of a class or by the class itself.

What does Staticmethod mean?

A static method (or static function) is a method defined as a member of an object but is accessible directly from an API object's constructor, rather than from an object instance created via the constructor.

What is need of static method in Python?

Static methods have a limited use case because, like class methods or any other methods within a class, they cannot access the properties of the class itself. However, when you need a utility function that doesn't access any properties of a class but makes sense that it belongs to the class, we use static functions.

What is Staticmethod Django?

A @staticmethod allows you to stick a function on the class namespace without it actually being tied to the class. You still have to call that function.


I'm having a little problem decorating a static method in Python. I think the following code best represents my problem:

def decorator(func):
    print callable(func)
    return func

class Foo():
    @decorator
    @staticmethod
    def bar():
        return

# outputs False

print callable(Foo.bar) 
# outputs True

This seems to be a bug. I imagine it arises because when the method Foo.bar is passed to the decorator, it is a function, not a method. That is the only reason I can see for it not being callable, for if we decorate a standard function, it is not callable, as shown below.

@staticmethod
def function():
    return

print callable(function) 
# outputs False

So is this a true bug in implementation of the staticmethod decorator, and/or are there any simple workarounds? I did think of writing a decorator to asign a __call__ attribute, but I don't know how callable is implemented, so I can't gauge the sucess of such a method.