how are dictionary literals handled by the interpreter?

Bruno Desthuilliers onurb at xiludom.gro
Thu Sep 14 06:37:09 EDT 2006

akameswaran at 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

Err...  Why would you want to exec anything here ? Remember that
Python's functions are objects too:

def funcA(*args, **kw):
  return "funcA called with %s %s" % (str(args), kw)

def funcB(*args, **kw):
  return "funcB called with %s %s" % (str(args), kw)

def funcC(*args, **kw):
  return "funcC called with %s %s" % (str(args), kw)

def defaultFunc(*args, **kw):
  return "defaultFunc called with %s %s" % (str(args), kw)

class SwitchFunc(object):
  def __init__(self, default, **kw):
    self._default = default
    self._switch = kw

  # makes the object callable.
  def __call__(self, case, *args, **kw):
    func = self._switch.get(case, self._default)
    return func(*args, **kw)

switch = SwitchFunc(defaultFunc, a=funcA, b=funcB, c=funcC)

for case in "abcX":
  print switch(case, "foo", q=42)

bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"

More information about the Python-list mailing list