Classmethods are evil

Carl Banks pavlovevidence at gmail.com
Sat May 17 01:25:50 EDT 2008


On May 17, 12:01 am, Ivan Illarionov <ivan.illario... at gmail.com>
wrote:
> After re-reading "Python is not Java" I finally came to conclusion that
> classmethods in Python are a very Bad Thing.
>
> I can't see any use-case of them that couldn't be re-written more clearly
> with methods of metaclass or plain functions.

I am probably one of the bigger advocates of metaclasses here, but
given a problem that could equally well be solved by the two I would
choose classmethods every time.  Classmethods are more
straightforward, easier to follow (especially by people who aren't
used to working with metaclasses), and they hinder reusability less.

Classmethods have practical advantages.  One thing you can do with a
classmethod that you can't directly do with a metaclass instancemethod
is to call it with an instance:

 Python 2.5 (r25:51908, Apr 19 2007, 15:29:43)
 [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
 Type "help", "copyright", "credits" or "license" for more
information.
 >>> class A(type):
 ...     def hello(self):
 ...             print "hello"
 ...
 >>> class B(object):
 ...     __metaclass__ = A
 ...     @classmethod
 ...     def world(self):
 ...             print "world"
 ...
 >>> b = B()
 >>> b.world()
 world
 >>> b.hello()
 Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
 AttributeError: 'B' object has no attribute 'hello'

Though I can imagine some people would argue this is an advantage of
metaclasses.


> They have the following issues:
> 1. You mix instance-level and class-level functionality in one place
> making your code a mess.
> 2. They are slower than metaclass methods or plain functions.
>
> I really want to hear your opinions on the subject.

I think neither of these reasons are very compelling.  I don't even
agree with the premise of #1, but even granting that it's messy to do
that, I disagree that the mess would outweigh the drawbacks in
complexity and reusability that a metaclass would bring.  As for #2, I
don't believe "class-level functionality" is often found in bottleneck
situations, so what does it matter what speed it is?


Carl Banks



More information about the Python-list mailing list