Make staticmethod objects callable?

Steven Bethard steven.bethard at gmail.com
Wed Mar 1 10:32:20 EST 2006


Steven D'Aprano wrote:
> So, based on this evidence, staticmethod() inside a class definition 
> converts instance methods to functions. Outside a class definition, 
> staticmethod() does one of two things: it either converts an instance 
> method to a static method, or if the output is assigned to a class 
> attribute, it leaves it as an instance method.

This is exactly why I'm concerned about augmenting staticmethod's 
behavior.  When people run into this, it should be the opportunity to 
explain to them how descriptors work.  Descriptors are hugely important 
in the new object system, and even if we hide them by giving 
staticmethod a __call__, we'll still run into problems when people try 
to do:

     class C(object):
         @classmethod
         def foo(cls):
             print cls
         bar = foo(None)

Then, not only do we have to explain how descriptors work, but we also 
have to explain why staticmethod has a __call__, and classmethod doesn't.

(For anyone else out there reading who doesn't already know this, Steven 
D'Aprano's comments are easily explained by noting that the __get__ 
method of staticmethod objects returns functions, and classes always 
call the __get__ methods of descriptors when those descriptors are class 
attributes:

 >>> class C(object):
...     @staticmethod
...     def foo():
...         pass
...     print foo
...
<staticmethod object at 0x00E73950>
 >>> print C.foo
<function foo at 0x00E80330>
 >>> @staticmethod
... def foo():
...     pass
...
 >>> print foo
<staticmethod object at 0x00E73990>
 >>> print foo.__get__(C, None)
<function foo at 0x00E80130>

Yes, you have to explain descriptors, but at the point that you start 
trying to do funny things with staticmethods and classmethods, I think 
you need to start learning about them anyway.)

All that said, you should probably just submit a patch and see what 
happens.  I'll make a brief comment on it along the above lines, but 
since I'm not a committer, it's not really worth your time to try to 
convince me. ;)

STeVe



More information about the Python-list mailing list