Possible PEP: Improve classmethod/staticmethod syntax
Kevin Smith
Kevin.Smith at sas.com
Tue Jun 3 16:45:18 EDT 2003
The current way of declaring a method to be a class method or a static
method leaves much to be desired. While it is flexible in the sense
that new types of method modifiers can be created without any
syntactical backwards incompatibilities, it just isn't that user-
friendly (and, in turn, not Pythonic).
A new proposed syntax for method modifiers is as follows:
def classmethod foo(cls):
<code goes here>
def staticmethod bar():
<code goes here>
An optional keyword is added before the function name itself. This
keyword is simply a reference to a function that will be applied to the
method once the method is compiled. In essence, the above syntax
expands to:
def foo(cls):
<code goes here>
foo = classmethod(foo)
def bar():
<code goes here>
bar = staticmethod(bar)
The motivation here isn't so much terseness as it is understandability.
The call to classmethod() or staticmethod() in this short example is
very close to the original 'def', so it is easy to follow. However, if
the method is any more than about 15 lines of code, the transformation
to a class method or static method isn't obvious. The proposed syntax
puts the class/static method conversion at the point of definition where
it makes the most sense. This placement also makes it easier for
documentation generators or IDEs to give visual cues when class or
static methods are used.
I am not familiar with how the classmethod() or staticmethod() functions
actually work and if they would support this, but a possible extension
to the original syntax would be to add multiple modifiers before the
method name.
def protected classmethod foo(cls):
<code goes here>
This would expand to:
def foo(cls):
<code goes here>
foo = protected(classmethod(foo))
What all this boils down to is that any function that can return a new
function reference (i.e. classmethod()/staticmethod()/protected()) when
given a function reference (i.e. foo/bar) could be used as a modifier.
If it is technically feasible, it would be nice if multiple modifiers
were allowed. The proposed syntax does not cause any backwards
incompatibilities since it is simply uses the existing function
modifiers and they can still be used the way they were originally
designed.
--
Kevin Smith
Kevin.Smith at sas.com
More information about the Python-list
mailing list