how are dictionary literals handled by the interpreter?

akameswaran at gmail.com akameswaran at gmail.com
Wed Sep 13 18:39:02 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:
Sorry I misread exec as dict in my earlier reply.  I did have another
class based implementation that used functions in the class.  That was
the only one that performed well against if/else.  And only for large
number of cases.  When I compared the two implementations I stated here
- that's where I wondered about my understanding of dictionary literals
with regards to performance.  I could also rewrite the function version
to store functions in the dictionary instead of statements for exec -
but here I was just wanting to compare retrieving a dictionary class
member, vs reading a dictionary literal.  I think the code did a good
job of isolating that as the only change - and that is validated by
using the dissassembler.

>
>     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)()
>
> ?  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