Home > OS >  How to use the value of a Python variable as the callback name?
How to use the value of a Python variable as the callback name?

Time:10-22

Edit: The following is a simplified code of a more complex example.

def lottery(amount, callback=None):
    print(f'You spent {amount} on a lottery ticket.')
    if callback:
        callback(amount)

def win(amount):
    print(f'You won ${amount * 1000}!!!')

def lose(amount):
    print(f"Sorry, you spent {amount} and didn't win anything.")

Edit: The 'lottery' function is from a third-party package. I would prefer not to modify their code.

The following works, but they aren't what I am looking for.

lottery(100, win)

Output:

You spent 100 on a lottery ticket. You won $100000!!!

lottery(100, callback=win)

Output:

You spent 100 on a lottery ticket. You won $100000!!!

lottery(100, lose)

Output:

You spent 100 on a lottery ticket. Sorry, you spent 100 and didn't win anything.

lottery(100, callback=lose)

You spent 100 on a lottery ticket. Sorry, you spent 100 and didn't win anything.

What I'm looking for is to continue to use a callback and have a variable hold a value of either 'win', 'lose', [Edit: or additional functions like 'win_1', 'win_2', ..., 'win_n' or 'lose_1', 'lose_2', ..., 'lose_n'] and use that variable in the same place as the callback name.

Wishful example:

win_lose = 'win'
lottery(100, win_lose)

Edit: the string 'win' is built on the fly like:

'win'   '_'   str(index)

or

'lose'   '_'   str(index)

Wishful output:

You spent 100 on a lottery ticket. You won $100000!!!

CodePudding user response:

This should do the job:

def lottery(amount, win_lose):
    print(f'You spent {amount} on a lottery ticket.')
    if win_lose =="win":
        print(f'You won ${amount * 1000}!!!')
    if win_lose =="lose":
        print(f"Sorry, you spent {amount} and didn't win anything.")
    
#Example
win_lose = 'win'
lottery(100, win_lose)

CodePudding user response:

You know you can assign the function objects to variables, right? You could just do win_lose = win (no quotes) and the code would work. If you want a string with the name of the function, you can use its __name__ attribute: print(callback.__name__) will print " win" if that function is the passed in callback.

Otherwise, if both functions are on the same module, you can retrieve the functin object from its name by using the dictionary returned by globals() - that would do exactly what you are asking - I am just not sure if that is really what you'd need:

def lottery(amount, callback_name=None):
    callback = globals().get(callback_name)
    print(f'You spent {amount} on a lottery ticket.')
    if callback:
        callback(amount)

def win(amount):
    print(f'You won ${amount * 1000}!!!')

def lose(amount):
    print(f"Sorry, you spent {amount} and didn't win anything.")

  • Related