how are dictionary literals handled by the interpreter?
sjdevnull at yahoo.com
sjdevnull at yahoo.com
Wed Sep 13 17:56:19 EDT 2006
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:
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