laspal
laspal

Reputation: 25

need help for calling function

List_of_subject = ['add user', 'modify user', delete user'] and so on

I have a variable called subject. so depending upon the subject other function are called. like add_user, modify_user, delete_user and so on.

So when my subject is 'add_user' I want to call add_user function. I can call it like a normal function call. But my list_of_subject is keep growing.

Can I DO :

List_of_subject.index(subject)

I get the index. So I want something like when index is 1 call add_user function. Basically I want to link my function to list_of_subject list. or it is ok to do this:`

if subject in list_of_subject:
  if subject == 'add user' :
        user = add_user()
  else if subject == ' modify user' 
        user = modify_user()

thanks.

thanks.

Upvotes: 1

Views: 103

Answers (2)

NPE
NPE

Reputation: 500227

In Python, functions are first-class objects, so you can put them into a dictionary:

fn = {'add user': add_user, 'modify user': modify_user}

To then call the relevant function, use:

user = fn[subject]()

Upvotes: 8

Emile
Emile

Reputation: 2971

A (relatively) unsafe way of doing it would be

def add_user():
    (...)

list_of_subject = ['add_user', 'modify_user', 'delete_user']

if subject in list_of_subject:
    exec(subject + "()")

Upvotes: 0

Related Questions