2

Let us say I have a function like this:

def helloWorld(**args):
    for arg in args:
        print(args[arg])

To call this function is easy:

helloWorld(myMsg = 'hello, world')
helloWorld(anotherMessages = 'no, no this is hard')

But the hard part is that I want to dynamically name the args from variables coming from a list or somewhere else. And I'd want for myMsg and anotherMessages to be passed from a list (for example, the hard part that I am clueless and I need help with is how to take strings into variables to be inputs of a function).

list_of_variable_names = ['myMsg','anotherMessages']
for name in list_of_variable_names:
    helloWorld(name = 'ooops, this is not easy, how do I pass a variable name that is stored as a string in a list? No idea! help!')

2 Answers 2

3

You can create a dict using the variable and then unpack while passing it to the function:

list_of_variable_names = ['myMsg','anotherMessages']
for name in list_of_variable_names:
    helloWorld(**{name: '...'})
Sign up to request clarification or add additional context in comments.

1 Comment

interesting, let me try it out
3

The ** syntax is a dictionary unpacking. So in your function, args (which is usually kwargs) is a dictionary.

Therefore, you need to pass an unpacked dictionary to it, which is what is done when f(a=1, b=2) is called.

For instance:

kwargs = {'myMsg': "hello, world", 'anotherMessages': "no, no this is hard"}
helloWorld(**kwargs)

Then, you will get kwargs as a dictionary.

def f(**kwargs):
    for k, v in kwargs.items():
        print(k, v)

>>> kwargs = {'a': 1, 'b': 2}
>>> f(**kwargs)
a 1
b 2

If you want to do so, you can call the function once for every name as well, by creating a dictionary on the fly and unpacking it, as Moses suggested.

def f(**kwargs):
    print("call to f")
    for k, v in kwargs.items():
        print(k, v)

>>> for k, v in {'a': 1, 'b': 2}:
...     kwargs = {k: v}
...     f(**kwargs)
...
call to f
a 1
call to f
b 2

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.