AlexT
AlexT

Reputation: 609

Python - Construct a variable name based on function argument

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?

Upvotes: 1

Views: 980

Answers (2)

kmario23
kmario23

Reputation: 61355

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

Upvotes: 2

Chris
Chris

Reputation: 22953

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.

Upvotes: 1

Related Questions