[Python-Dev] classmethod() and staticmethod()

Ka-Ping Yee ping@lfw.org
Mon, 13 Aug 2001 15:33:19 -0700 (PDT)

I'm very happy with the design for type-class unification -- it looks
like an excellent move towards making Python more consistent and flexible.

However, the mechanism for declaring class and static methods:

    class MyClass:
        def method(x, y):                      # part 1

        method = staticmethod(method)          # part 2

...sticks out as awkward and strange to read.  Kevin Smith and Paul
Prescod commented earlier on this, and i agree with their opinion that
a more direct declaration would be a better way to do this.

I don't especially care what keyword or syntax is used to declare a
static method, just that we require it to occur right where the method
is being declared, and that it not be a "normal" expression (i.e. it
must be invalid syntax in Python versions < 2.2).

The two-part declaration above is unfortunate because:

    (a) A human reader doesn't immediately see what kind of method
        is being declared, and has to read ahead to figure out.

    (b) An automated documentation or syntax checking utility can't
        immediately see what kind of method is being declared, and
        has to scan ahead to figure out.  Same thing for colourizing
        editors, IDEs that try to help you fix errors, etc.

    (c) It is possible for deceptive code to come about by accident.
        In much the same way that braces and indentation can get out
        of sync and confuse a reader, the appearance of parts 1 and 2
        can get out of sync with the semantics of the code.

        (If someone forgets to write part 2, or inadvertently forgets
        to type in "self" as the first argument to an instance method,
        then part 1 will look like a static method even though it's
        an instance method.  If someone writes part 2, but by habit
        forgets to omit "self" as the first argument, then part 1 will
        look like an instance method even though it's a static method.
        It would be much better to design this in the first place so
        that such mess-ups are not possible.)

    (d) The new declaration is syntactically correct in older Pythons.
        Someone unfamiliar with this new static-method mechanism will
        not be given very useful ideas about what is wrong.  With an old
        version of Python, they'll get an error seeming to indicate
        that "staticmethod" is an undeclared function, and wonder what
        they need to import.  I think it would be better for them to get
        a syntax error on the line where the method is declared, clearly
        indicating that a fundamentally new feature is being used and
        a new version of Python is required.

-- ?!ng