0

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)
AmirY
  • 57
  • 3
  • 14
Raff
  • 27
  • 1
  • 5
  • 2
    You should not do this. Put variables in a dictionary instead `d = {'var1': arr1, 'var2': arr2, 'var3': arr3}` – Psidom Oct 28 '17 at 15:30
  • Where are you getting a list of variable names in the first place? – chepner Oct 28 '17 at 15:33
  • I use the list to create subsets of features (different and unique combinations of features) – Raff Oct 28 '17 at 15:39
  • Does this answer your question? [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables) – wjandrea Jul 02 '20 at 01:28

2 Answers2

0

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"

Ajax1234
  • 69,937
  • 8
  • 61
  • 102
0

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.

Igor
  • 3,129
  • 1
  • 21
  • 32