classmethods, staticmethods, and decorators

Paul Morrow pm_mon at yahoo.com
Thu Aug 19 09:24:06 EDT 2004


Probably the best-loved features of Python are the shortcuts.  The fact 
that you don't have to explicitly declare very much and that the 
language supports clear, shorthand syntax for frequently used operations...

     x = [1,2,3]

     y = r[2:9]

     def __foo():

That's the good stuff of Python.

I believe that identifying staticmethods and classmethods is an 
operation that is (or will be) frequently used as compared to the other 
decorators.  So it would be great if there was an obvious, shorthand way 
for doing that as well.

Even better (IMO) would be a solution that didn't really add any new 
keywords to the language, but instead simply formalized widely-used 
coding conventions, as was done to denote code block boundaries.

The use of indentation to identify code blocks is a wonderful example of 
Python shorthand.  It works (some even call it 'genius') because it 
leverages a coding convention shared by a majority of programmers.

A week or so ago on this forum, Stefan Eischet suggested that the type 
(static|class|instance) of a method should be inferred through 
examination of its first parameter.  I agree with his assessment.

The vast majority of instance methods I've seen all use 'self' as the 
first parameter.  Likewise, most class methods use 'cls' or 'klass' as 
their first parameter.  If we exploit these conventions, we end up with 
a simple, clear, obvious mechanism for denoting (this aspect of) a 
method's type.

     class Foo(Object):
         def m1(self, a, b):    # this is an instance method of Foo
             pass

         def m2(cls, a, b):     # this is a class method of Foo
             pass

         def m3(a, b):          # this is a static method of Foo
             pass

And for backwards compatibility, a special Object (capital 'O') class 
could work this magic so that old code didn't break.

I know that this is odd.  But then so are most of the great things about 
Python.

Paul





More information about the Python-list mailing list