how are dictionary literals handled by the interpreter?

akameswaran at gmail.com akameswaran at gmail.com
Wed Sep 13 18:33:40 EDT 2006


sjdevnull at yahoo.com wrote:
> akameswaran at gmail.com wrote:
> > 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
>
> Have you considered eliminating the exec() wart just doing:

thr dict wart was added - needlessly simply to see if there was a
difference.  case4 was a reaction to the odd timings.  I wouldn't use
it ever in the real world as it is totally unnecessary.

>
>     self.caseDict = {'a'='a', 'b'='b'}
> ....
>     def doIt(self, a):
>         return self.caseDict[a]
>
> (or the get call)
> Or for more complex cases going with something like:
>
> class caseFunction(object):
>     def __init__(self):
>         self.caseDict = {'a':self.do_a, 'b':self.do_b}
>     def do_a(self):
>         return 'a'
>     def do_b(self):
>         return 'b'
>     def doIt(self, a):
>         return self.caseDict[a]()
>
> or eliminating the init and
>     def doIt(self, a):
>         return getattr(self, "do_"+a)()
>

This is clever, but really only works for this contrived example.  If I
wanted to base my cases on an object.... Still I like it's elimination
of seemingly redundant dictionary.  The original purpose of all of this
was to get a feel for performance differences between endless if/else
statements and a dictionary for performing switch/case type stuff.

The upshot of all of this, is I will probably stick to the if/else
construct except for fairly complex cases for two reasons

1) only in the most braindead version of an if/else construction  is
dictionary faster for small (ie less than 20) different cases.
2) dictionary method won't work if I want an switch could match
multiple case conditions




> ?  Obviously with these two you might want a bit more complexity for a
> default if the attribute/dict entry is missing, but the simple case
> shows the idea.




More information about the Python-list mailing list