how are dictionary literals handled by the interpreter?

akameswaran at gmail.com akameswaran at gmail.com
Wed Sep 13 14:54:11 EDT 2006


I wrote up a quick little set of tests, I was acutally comparing ways
of doing "case" behavior just to get some performance information.  Now
two of my test cases had almost identical results which was not at all
what I expected.  Ultimately I realized I don't really know how
literals are treated within the interpreter.

The two implementations I was looking at were:

class caseFunction(object):
    def __init__(self):
        self.caseDict = {'a':"retval = 'a'",
'b':"retval='b'","c":"retval='c'","d":"retval='d'",

"e":"retval='e'","f":"retval='f'","g":"retval='g'","h":"retval='h'",
                         "i":"retval='i'"}

    def doIt(self,a):
        exec(self.caseDict.get(a))
        return retval



def caseFunc3(a):
    exec(  {'a':"retval = 'a'",
'b':"retval='b'","c":"retval='c'","d":"retval='d'",

"e":"retval='e'","f":"retval='f'","g":"retval='g'","h":"retval='h'",
                         "i":"retval='i'"}.get(a))
    return retval


I had expected caseFunc3 to be slower.  I had thought the interpreter
would be recreating the dictionary each time, but that doesn't seem to
be the case since performance of the class version and the function
version are nearly identical on most runs.  If i rewrite caseFunc3 as:

def caseFunc4(a):
    exec(  dict({'a':"retval = 'a'",
'b':"retval='b'","c":"retval='c'","d":"retval='d'",

"e":"retval='e'","f":"retval='f'","g":"retval='g'","h":"retval='h'",
                         "i":"retval='i'"}).get(a))
    return retval

now with the explicit use of dict, i see the performace of the
functional version decline as I initially expected.

So what is happeneing in caseFunc3.  It seems as though the literal is
"cached".  The other hypothesis I came up with is the name lookup for
self.caseDict takes the same amount of time as creating the dictionary
literal - but that doesn't make sense to me.

Thanks




More information about the Python-list mailing list