0

So I use a bunch of files. Each file will trigger when lets say variable x = function. I know this is confusing but pretty much I need to be able to use a variable name which depending on what the variable is equal to will call that function. I am using python for this.

11
  • 1
    Please add you code. The issue is not clear. Commented Aug 7, 2020 at 21:22
  • I don't have code. What I am trying to do is call a function with the string in a variable. Commented Aug 7, 2020 at 21:24
  • 1
    You don't want to do that. You want to use a dict that maps from some string name to the corresponding function. Commented Aug 7, 2020 at 21:25
  • 1
    You better have something if you are asking for help here. Commented Aug 7, 2020 at 21:25
  • 1
    I would suggest the OP read this guide (stackoverflow.com/help/how-to-ask) for pointers on what the community needs in order to offer good answers. I also feel the need to point out while there may be means to embed a function call directly into the contents of a string variable, this comes with security concerns and can make your code difficult to maintain. I would strongly recommend studying Python Dictionaries, as recommended by Mr. Knechtel. Commented Aug 7, 2020 at 23:15

1 Answer 1

1

Based on your question, it looks like you want some sort of factory where the function to call is determined by the value of the variable passed in.

Here's a simple way of doing it:

x = 2  # determines which function to call

# possible functions to call 
def f0(p): print('called f0',p)
def f1(p): print('called f1',p)
def f2(p): print('called f2',p)
def f3(p): print('called f3',p)

lstFunc = [f0, f1 ,f2, f3]  # create list of functions

lstFunc[x]('test')  # x=2, call function at index 2 (f2)

Output

called f2 test

For something more complicated, you would use a function which returns another function based on the variable value. In this example, I'm just using a list of functions.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.