You are not logged in.

#1 2005-11-25 13:32:00

Cam
Member
From: Brisbane, Aus
Registered: 2004-12-21
Posts: 658
Website

python - callback functions

Hey,

I have this list:

  menu = [ ('Playlist', playlist_menu),
           ('Play/Pause', playpause) ]

At the moment to avoid errors when I run it I've made empty functions for playlist_menu and playpause but further down I have some code which will check a value and decide which function needs to be run but I'm not sure how I can run them. I could use exec() but is there a better way? This is where I do the work:

while 1:
  cmd = dev.listen(sock)
  if cmd == '*EAAI':
    menu()
  elif 'EAMI' in cmd:
    sel = re.findall('*EAMI: ([0-9]+)', var)[0]

After that last line I'd like to run the function name in menu[sel][1], is there a "proper" way to do this or is exec() the way to go?

Any opinions appreciated smile

Offline

#2 2005-11-25 16:19:21

Dusty
Schwag Merchant
From: Medicine Hat, Alberta, Canada
Registered: 2004-01-18
Posts: 5,986
Website

Re: python - callback functions

Um.... can you use a dictionary instead of a list of tuples?

menu = { 'Playlist', playlist_menu }

then you can do something like:

menu['Playlist']()

or
func = menu['Playlist']
func()

to execute the function

Dusty

Offline

#3 2005-11-26 00:19:05

Cam
Member
From: Brisbane, Aus
Registered: 2004-12-21
Posts: 658
Website

Re: python - callback functions

items = { 1 : ('Playlist', playlist_menu),
          2 : ('Play/Pause', playpause) }

while 1:
  cmd = dev.listen(sock)
  if cmd == '*EAAI':
    menu(items)
  elif 'EAMI' in cmd:
    sel = re.findall('*EAMI: ([0-9]+)', cmd)[0]
    items[ int(sel) ][1](c)

Okay awesome! That works good smile Thanks Dusty

Offline

Board footer

Powered by FluxBB