Behavior of staticmethod in Python 3

Peter Otten __peter__ at web.de
Sat Nov 23 10:01:45 CET 2013


Marco Buttu wrote:

> In Python 3 the following two classes should be equivalent:

Says who?

> $ cat foo.py
> class Foo:
>      def foo():
>          pass
>      print(callable(foo))
> 
> class Foo:
>      @staticmethod
>      def foo():
>          pass
>      print(callable(foo))
> 
> But they do not:
> 
> $ python3 foo.py
> True
> False
> 
> How come the metaclass does not skip the staticmethod decorator?

What? Your print()s are executed inside the class body, so the classes don't 
come into play at all.

Your script is saying that a staticmethod instance is not a callable object. 
It need not be because

Foo.foo()

doesn't call the Foo.foo attribute directly, it calls

Foo.foo.__get__(None, Foo)()

>>> class D:
...     def __get__(self, *args): print(args)
... 
>>> class Foo:
...     foo = D()
... 
>>> Foo.foo()
(None, <class '__main__.Foo'>)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable

Look for "descriptor protocol" to learn the details.




More information about the Python-list mailing list