C-style static variables in Python?

Patrick Maupin pmaupin at gmail.com
Mon Apr 5 20:46:02 EDT 2010


On Apr 5, 6:50 pm, Ethan Furman <et... at stoneleaf.us> wrote:

(Posted some code with a timeit...)

Well, I'm not going to debug this, but with the *original* thing you
posted, and the thing I posted, with a call and everything (more
realistic scenario), the exception version seems slower on my machine:

#!/usr/bin/env python

import timeit

def frobnicate(a,b,c,d):
    pass

def heavy_lifting_at_runtime():
    print 'heavy'

class spam_except(object):
     def __call__(self, x, y, z):
         try:
             mongo = self.mongo
         except AttributeError:
             mongo = self.mongo = heavy_lifting_at_runtime()
         return frobnicate(x, y, z, mongo)
se = spam_except()


class spam_if(object):
     def __getattr__(self, name):
         if name != 'mongo':
             raise AttributeError
         self.mongo = heavy_lifting_at_runtime()
         return self.mongo
     def __call__(self, x, y, z):
         return frobnicate(x, y, z, self.mongo)
si = spam_if()

tse = timeit.Timer('se(1,2,3)', "from __main__ import se")
tsi = timeit.Timer('si(1,2,3)', "from __main__ import si")

for i in range(5):
    ve = tse.timeit(10000000)
    vi = tsi.timeit(10000000)
    print ve, vi, '%.1f' % ((ve-vi) / vi * 100)

------

heavy
heavy
5.45695090294 5.10844397545 6.8
5.43381404877 5.01345705986 8.4
5.42474508286 5.02641201019 7.9
5.40713405609 5.04178905487 7.2
5.38063693047 4.96194696426 8.4

The output indicates that the exception one is, on average, around
7.5% slower.

Regards,
Pat



More information about the Python-list mailing list