I am trying to write a program that checks for an operation in a dictionary and calls a function matching the 'key'.
this program will parse the line based on what the 'key' is.
My question is, how to pass a string into the function called by the dictionary so the function can parse it since the string will not always be the same and neither will how the string is parsed.
def format1(opline): # r-type: rd, rs, rt
opline = opline.split('', 1)[1] # removes instruction
rd, rs, rt = opline.split() # splits into 3 registers
return rd, rs, rt # returns all registers
inst_match = {'add' : format1} # dictionary (more.
# key/funct pairs
# will be added
instruction_storage = 'add 9 0 255'
instructions = instruction_storage.split()[0] # get key from string
inst_match[instructions](instruction_storage) # passes key to search and string to pass into function
^ the above code is just a test. I will eventually be reading "instruction_storage" in from a file of multiple lines.
It's not real clear to me exactly what you're after, but here's a guess:
def format1(opline, string):
print('format1({!r}, {!r})'.format(opline, string))
opline = opline.split(' ', 1)[1]
rd, rs, rt = opline.split()
return rd, rs, rt
def format2(opline, string):
print('format2({!r}, {!r})'.format(opline, string))
opline = opline.split(' ', 1)[1]
rd, rs, rt = opline.split()
return rd, rs, rt
inst_match = {'add': format1,
'sub': format2}
instruction_storage = [('add 9 0 255', 'string1'),
('sub 10 1 127', 'string2')]
for instruction in instruction_storage:
opline, string = instruction
opcode = opline.split()[0]
try:
inst_match[opcode](opline, string)
except KeyError:
print('unknown instruction: {!r}'.format(opcode))
Output:
format1('add 9 0 255', 'string1')
format2('sub 10 1 127', 'string2')