1
def my_func(arg):
    ...
    x = foo(var_arg)
    ...

With many variables saved as var_1, var_2, var_3 I would be able to pass one of them based on the foo function's argument. So if I call my_func(2), in the function x will equal the result of foo(var_2). Is it possible to construct a variable name like you would with strings?

2
  • Possible duplicate of: stackoverflow.com/questions/1373164/… Commented Oct 12, 2018 at 1:45
  • Not exactly @JustinWager. The OP seems to already have the variables. They just need a good way to pair certain variables with certain options. Commented Oct 12, 2018 at 1:46

2 Answers 2

2

How about using a dictionary for storing the variables and then dynamically constructing variable names based on the arguments passed and then accessing the corresponding values, which can then be passed on as argument to function foo

In [13]: variables = {"var_1" : 11, "var_2": 22, "var_3": 33} 
    ...:  
    ...: def my_func(arg): 
    ...:     full_var = "var_" + str(arg)
    ...:     print(variables[full_var])
    ...:     # or call foo(variables[full_var])    
In [14]: my_func(1)                                                      
11

In [15]: my_func(2)
22

In [16]: my_func(3)
33
Sign up to request clarification or add additional context in comments.

Comments

1

What I recommend you do is to use dictionaries. In my view, that would be the most efficient option. For example, pretend var_1, var_2, and var_3 equal 'a', 'b', and 'c' respectively. You'd then write:

d = {1: 'a', 2: 'b', 3: 'c'}

def foo(var):
    return d[var]

def my_func(arg):
    x = foo(var_arg)
    return x

my_func(1) # returns: 'a'

As you can see, you really don't even need variables when using the dictionary. Just use the value directly.

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.