list/dictionary as case statement ?

Hendrik van Rooyen mail at microcorp.co.za
Wed Jan 3 07:21:46 CET 2007


"Stef Mientki" <S.Mientki-nospam at mailbox.kun.nl> wrote:

> 
> If I'm not mistaken, I read somewhere that you can use 
> function-names/references in lists and/or dictionaries, 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 ?

the short answer is : "Yes"

a slightly longer answer depends on what you want to do

If you want to write a simple assembler, your dict will look something like:

Mnemonics_to_Opcodes = 
{"MOV": [Functionnameforopcodeandtwooperands,movopcode],
"NOP":[Functionnameforopcodeonly,nopopcode],
"SETB":[Functionnameforopcodeandoneoperand,setbopcode],
"JMP":[Functionnameforopcodeandoneoperand,jmpopcode],
...
}

if you want to write a simulator only that "executes" the hex or binary,
then your dict needs to be something like this:

Opcodes =
{movopcode:[MovFunction,movinstructionlen],
nopopcod:[NopFunction,nopinstructionlen],
setbopcode:[SetbFunction,setbinstructionlen],
jmpopcode:[JmpFunction,jmpinstructionlen],
...
}

and then you write an "instruction fetcher" based on the
Program Counter that uses the length data in the dict and
calls the various functions with the operands as fetched from
memory. The easiest is to make the PC a global...

It works well - and it is surprisingly fast too...
And its easy if the opcodes are all say one byte,
else you need an opcode length field too, and fancier
parsing.

This is not the hassle with this kind of thing - the hassle comes
in trying to simulate the behaviour of the I/O of a real system...

hth - Hendrik





More information about the Python-list mailing list