-1

I would like to run a function with a list parameter :

param = ['a', 'b', 'c']
myFunction(param)

But a, b and c must be dynamic so I would like to remove the quotes to get this :

param = [a, b, c]
myFunction(param)

How can I do that ?

PS : I tried the solutions of this question but it didn't work Removing quotation marks from list items

norok2
  • 25,683
  • 4
  • 73
  • 99
Charles R
  • 1,621
  • 1
  • 8
  • 25

2 Answers2

3

If I understood correctly, you want to actually call myFunction with parameters a, b and c (assuming these are actually being defined earlier).

One way of doing this is:

a, b, c = 1, 2, 3
param = ['a', 'b', 'c']

def myFunction(x, y, z):
    return x + y + z

myFunction(*[globals()[s] for s in param])
# returns: 6

EDIT:

As people have suggested, a safe way of doing this would be through globals() (or locals() using a slightly different construct). Otherwise, you could use eval() which is more powerful, but also potentially less safe.

norok2
  • 25,683
  • 4
  • 73
  • 99
  • 2
    *Please* don't use `eval` when `globals` would be sufficient. Beginners will copy your `eval` without thinking and open themselves up to code injection. – Aran-Fey Oct 04 '18 at 12:44
  • In my case, there is no code injection issue, good for me ;) – Charles R Oct 04 '18 at 12:46
  • @CharlesR this still is very bad practice, have a look at the duplicate, use `locals()`. It is exactly what it is meant for – Olivier Melançon Oct 04 '18 at 12:48
  • @Aran-Fey you are right, I just typed faster than I should have. @OlivierMelançon `locals()` would not work inside the list comprehension. – norok2 Oct 04 '18 at 12:51
1

'str''s cannot be converted to variable names, however if you do have th variables and your goal is to pass each variable to a function this is possible

def addition(x):
    return x + 1

a = 1 b = 2 c = 3

param = [a, b, c] 
print([addition(i) for i in param])
# [2, 3, 4]

The entire list could be passed as well like so

def addition(x):
    return sum(x)

a = 1
b = 2
c = 3

param = [a, b, c]
print(addition(param))
# 6
vash_the_stampede
  • 4,590
  • 1
  • 8
  • 20
  • 1
    It is wrong that a string cannot be converted to variable. You can use `locals()['a']`. Although, I agree OP just should not rely on strings – Olivier Melançon Oct 04 '18 at 12:46
  • @OlivierMelançon noted, every lookup I did involved a tedious process to convert a `str` to variable name will look into this, ty – vash_the_stampede Oct 04 '18 at 12:48