-1

I am using Python in another program that sends and receives many similar messages. Essentially, the program sends an "address" and a "value". To be as concise as possible, I made a dictionary to act as a switch / case statement. However, before I go to far in my code I want to make sure I am writing the most efficient code I can.

Many of the messages are very similar (with only the last digit being different) and I am wondering if there is somehow a way for me to concatenate the observe_volume_(digit) cases. There are going to be perhaps hundreds of messages told and it seems a little ridiculous to add each one to the dictionary as it is already getting long with six messages.

def observe_volume_0(v):
    op('constant4').par.value0 = float(v[0])

def observe_volume_1(v):
    op('constant4').par.value1 = float(v[0])

def observe_volume_2(v):
    op('constant4').par.value2 = float(v[0])

def track_0_name(v):
    op('text1').par.text = v[0]
    print(v[0])

def track_1_name(v):
    op('text1').par.text = v[0]
    print(v[0])

def track_2_name(v):
    op('text1').par.text = v[0]
    print(v[0])


incoming = {
    '/track_0_name/x': track_0_name,
    '/track_1_name/x': track_1_name,
    '/track_2_name/x': track_2_name,
    '/observe_volume_0/x': observe_volume_0,
    '/observe_volume_1/x': observe_volume_1,
    '/observe_volume_2/x': observe_volume_2,
}

def receive(message, args):
full = message.split()
target = full[0]
incoming[target](args)
return
Startec
  • 12,496
  • 23
  • 93
  • 160

1 Answers1

0

Instead of having lots of functions like observe_volume_0, observe_volume_1..., you can pass the integer as an argument and have a exec inside it like -

def observe_volume(num, v):
    exec("op('constant4').par.value" + str(num) + " = float(v[0])")

def track_name(num, v):
    exec("op('text1').par.text = v[0]")
    print(v[0])

And now in place of your dict, you can have method like these replacing the dict -

import re
l = lambda x:  'track_name' if x.startswith("/track") else 'observe_volume'
number = lambda x : re.findall(r'\d+', x)[0]
target = '/observe_volume_0/x'
function_name = l(target)
num = number(target)

And now you can call like - locals()[function_name](num, args) or you may even put the two functions observe_volume and track_name inside a class and call as explained here

Community
  • 1
  • 1
hyades
  • 3,110
  • 1
  • 17
  • 36