[Python-Dev] PEP 318: Let's propose some useful built-in decorators

Raymond Hettinger python at rcn.com
Sat Apr 3 04:27:52 EST 2004


> While I ponder the decorator syntax, let's propose some built-in
> decorators.

Okay, I'll play (despite my thumbs down on the pep and especially the
syntax using a list prefixing the function).

Several people have emphasized that the timing of decorator application
is only an implementation detail.  So, that leaves open the possibility
of using function decorators as compilation pragmas.

One possible pragma tells the compiler that the function may assume that
specified global variables are constant and already known.  This allows
the globals to be loaded in the constant table and accessed with
LOAD_GLOBAL instead of LOAD_CONSTANT.

Another pragma tells the compiler to assume that specified attribute
lookup targets won't change outside the function.  This allows the
lookups to be precomputed as soon as the root is available or whenever
it changes.


Example
-------
X = 20

[earlybind(int, X),
 cacheattr("mylist.append", "result.append", "random.random",
"self.score")]
def meth(self, data) 
    result = []
    for sub in data:
        mylist = []
        for elem in sub:
            if int(elem) == X:
                mylist.append(elem)
            else:
                elem += random.random()
                self.score(elem)
        result.append(mylist)
    return result



Transformation
--------------
def meth(self, data, int=int, X=20)
    _rr = random.random
    _ss = self.score
    result = []
    _ra = result.append
    for sub in data:
        mylist = []
        _ma = mylist.append
        for elem in sub:
            if int(elem) == X:
                _ma(elem)
            else:
                elem += _rr()
                _ss(elem)
        _ra(mylist)
    return result


Adding the decorator line is sufficient to localize everything in the
function, eliminate all lookups from the inner loop, and still keep the
code clean and readable.


with-this-much-weirdness-who-needs-to-go-pysco-ly yours,



Raymond Hettinger




More information about the Python-Dev mailing list