I have a list with variable names:
['var1', 'var2', 'var3']
How can I use the string variable names as variables in a function?
Example:
Use the variable in the list for:
x = np.concatenate((var1, var2, var3), axis = 1)
I have a list with variable names:
['var1', 'var2', 'var3']
How can I use the string variable names as variables in a function?
Example:
Use the variable in the list for:
x = np.concatenate((var1, var2, var3), axis = 1)
You can use **kwargs
:
def some_function(**kwargs):
var1 = kwargs.get('var1')
var2 = kwargs.get('var2')
var3 = kwargs.get('var3')
s = ['var1', 'var2', 'var3']
vals = ["someval1", "someval2", "someval3"]
some_function(**{a:b for a, b in zip(s, vals)})
Now, in the function some_function
, var1
, var2
, and var3
store "someval1"
, "someval2"
, "someval3"
To achieve this you will need to use *
or **
operator
my_func(*[a, b])
# equals to
my_func(a, b)
And the same works with dicts
my_func(**{'p1': a, 'p2': b})
# equals to
my_func(p1=a, p2=b)
The second thing you need is to get the variable by it's name. Python has a possibility to do this, but it depends on where the variable is stored.
If it's an object attribute:
my_obj.var
# can be
getattr(my_obj, 'var')
For local variables:
my_var
locals()['my_var']
locals
gives you all local variables as dict
. There is also a similar globals
function.
So far the examples above are useless, but the idea is that you use python object (list, dict or str) instead of writing down the variable name itself.
So you can combine it all to build a tuple
def my_func():
var1, var2, var3, var4 = range(10, 14)
vars = ['var1', 'var2', 'var3']
loc = locals() # var1 - var4 and vars are available as dict now
tpl = tuple(loc[k] for k in vars)
print(tpl)
print(tuple([var1, var2, var3]))
So with this you can replace
x = np.concatenate((var1, var2, var3), axis = 1)
# to
x = np.concatenate(tpl, axis=1)
NOTE
This code will be fragile - moving part of it to another func may break it. And I think that this code style is not easy to read. So in most cases I'd suggest you to search for another approach. Combining all variables in some structure (dict or object) as suggested in first comment may be much better. But I can't say it will work as I don't see the whole your code.