[Python-ideas] staticmethod and classmethod should be callable

Steven D'Aprano steve at pearwood.info
Wed Jun 20 07:43:36 EDT 2018


On Wed, Jun 20, 2018 at 11:56:05AM +0200, Jeroen Demeyer wrote:
[...]
> Since it makes sense to merge the classes "classmethod" and 
> "classmethod_descriptor" (PEP 579, issue 8), one of the above behaviors 
> should be changed. Given that adding features is less likely to break 
> stuff, I would argue that classmethod instances should become callable.
[...]
> Are there any reasons to *not* make staticmethod and classmethod callable?

(The classes themselves are callable -- you're talking about the 
instances.)

+1 yes please!

The fact that classmethods and especially staticmethod instances aren't 
callable has been a long-running niggling pain for me. Occasionally I 
want to do something like this:

class Spam:
    @staticmethod
    def utility(arg):
        # something which is conceptually related to the Spam class
        # but doesn't need a cls/self argument.
        ...

    value = utility(arg)

but it doesn't work as staticmethod objects aren't callable until after 
they've gone through the descriptor protocol.


I'm not the only one bitten by this:

https://stackoverflow.com/questions/45375944/python-static-method-is-not-always-callable

https://mail.python.org/pipermail/python-list/2011-November/615069.html

Part of that thread, see links and discussion here:

https://mail.python.org/pipermail/python-list/2011-November/615077.html


I thought I had raised a bug report for this on the tracker, but my 
google-fu is failing me and I can't find it. But my recollection is that 
the simple fix is to make staticmethod.__call__ simply delegate to the 
underlying decorated function. And similar for classmethod.

(Of course calling classmethod instances directly won't work unless you 
provide the class argument. But that's just a simple matter of bound 
versus unbound methods.)


-- 
Steve


More information about the Python-ideas mailing list