list/dictionary as case statement ?

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Tue Jan 2 18:14:46 EST 2007


Stef Mientki a écrit :
> 
> If I'm not mistaken, I read somewhere that you can use 
> function-names/references in lists and/or dictionaries, 

Python's functions are objects too - instances of the (builtin) class 
'function'. So yes, you can use them like any other object (store them 
in containers, pass them as arguments, return them from functions etc).


> but now I can't 
> find it anymore.
> 
> The idea is to build a simulator for some kind of micro controller (just 
> as a general practise, I expect it too be very slow ;-).
> 
> opcodes ={
>   1: ('MOV', function1, ...),
>   2: ('ADD', function2, ),
>   3: ('MUL', class3.function3, )
>   }
> 
> def function1
>   # do something complex
> 
> 
> Is this possible ?

Why don't you just try ?

def mov(what, where):
   print "mov() called with %s : %s" % (what, where)

def add(what, towhat):
   print "add() called with %s : %s" % (what, towhat)


opcodes = {
   1: ('MOV', mov),
   2: ('ADD', add),
}

opcodes[1][1](42, 'somewhere')
opcodes[2][1](11, 38)

The third example is a bit less straightforward. Unless class3.function3 
is a classmethod or staticmethod, you'll need an instance of class3, 
either before constructing the 'opcodes' dict or when actually doing the 
call.

class SomeClass(object):
   def some_method(self):
     print "some_method called, self : %s" % self

some_obj = SomeClass()

opcodes[3] = ('MUL', some_obj.some_method)
opcodes[3][1]()

FWIW, using a dict of callables is a common Python idiom to replace the 
switch statement.

HTH



More information about the Python-list mailing list