[Python-Dev] syntactic sugar idea for {static,class}methods

Michael Hudson mwh@python.net
12 Feb 2002 17:05:02 +0000


Some time ago, Gareth McCaughan suggested a syntax for staticmethods.
You'd write

class C(object):
    def static(arg) [staticmethod]:
        return 1 + arg

C.static(2)
   => 3

The way this works is that the above becomes syntactic sugar for
roughly:

class C(object):
    def $temp(arg):
        return 1 + arg
    static = staticmethod($temp)

Anyway, I thought this was a reasonably pythonic idea, so I
implemented it, and thought I'd mention it here.  Patch at:

    http://starship.python.net/crew/mwh/hacks/meth-syntax-sugar.diff

Some other things that become possible:

>>> class D(object):
...     def x(self) [property]:
...         return "42"
...
hello!
>>> D().x
'42'

(the hello! is a debugging printf I haven't taken out yet...)

>>> def published(func):
...     func.publish = 1
...     return func
...
>>> def m() [published]:
...     print "hiya!"
...
hello!
>>> m.publish
1

>>> def hairy_constant() [apply]:
...     return math.cos(1 + math.log(34))
...
hello!
>>> hairy_constant
-0.18495734252481616

>>> def memoize(func):
...     cache = {}
...     def f(*args):
...         try:
...            return cache[args]
...         except:
...            return cache.setdefault(args, func(*args))
...     return f
...
>>> def fib(a) [memoize]:
...     if a < 2: return 1
...     return fib(a-1) + fib(a-2)
...
hello!
>>> fib(40)
165580141 # fairly quickly


I'm not sure all of these are Good Things (esp. the [apply] one...).
OTOH, I think the idea is worth discussion (or squashing by Guido :).

Cheers,
M.

-- 
  For every complex problem, there is a solution that is simple,
  neat, and wrong.                                    -- H. L. Mencken