"optimizing out" getattr

Daishi Harada daishi at gmail.com
Thu Sep 15 04:46:44 CEST 2005


I'd like to get the 'get2' function below to
perform like the 'get1' function (I've included
timeit.py results).

I'm not sure how to write 'mkget' to do achieve
this, however, except to use 'exec' - is that what
would be necessary?

Thanks in advance,

class A:
    a = 1
    b = 2
a = A()
labels = ('a', 'b')
def get1(x):
    return (x.a, x.b)
def mkget(attrs):
    def getter(x):
        return tuple(getattr(x, label) for label in attrs)
    return getter
get2 = mkget(labels)

# % timeit.py -s "import test" "test.get1(test.a)"
# 1000000 loops, best of 3: 0.966 usec per loop
# % timeit.py -s "import test" "test.get2(test.a)"
# 100000 loops, best of 3: 4.46 usec per loop

More information about the Python-list mailing list