Is there a way to use a string text as the input of a method in python?

Question:

I have a method, which takes a lot arguments as input.
Something like this, but with more args:

foo.add(a=True, b=0, c='z', d=(1, 0, 0), e=2, f='g')
foo.add(a=False, b=3, c='z', d=(1, 0, 2), e=2, f='z')
foo.add(a=True, b=10, c='h', d=(1, 3, 0), e=2, f='2')

I decided to make a dictionary and add each line’s args into that. But I can not use it like this:

foo_dict = {
    "a": "a=True, b=0, c='z', d=(1, 0, 0), e=2, f='g'",
    "b": "a=False, b=3, c='z', d=(1, 0, 2), e=2, f='z'",
    "c": "a=True, b=10, c='h', d=(1, 3, 0), e=2, f='2'",
}
foo.add(foo_dict["a"])
foo.add(foo_dict["b"])
foo.add(foo_dict["c"])

What is the best way to pass the args from another variable and not getting error?

Asked By: Nima

||

Answers:

Make each value a dict, then you can unpack it with **.

foo_dict = {
    "a": {'a':True, 'b':0, 'c':'z', 'd':(1, 0, 0), 'e':2, 'f':'g'},
    "b": {'a':False, 'b':3, 'c':'z', 'd':(1, 0, 2), 'e':2, 'f':'z'},
    "c": {'a':True, 'b':10, 'c':'h', 'd':(1, 3, 0), 'e':2, 'f':'2'},
}
for v in foo_dict.values():
    foo.add(**v)
Answered By: Unmitigated

The best way to pass arguments from a dictionary is to unpack them. You can use the ** operator to unpack the values of the dictionary as keyword arguments:

foo_dict = {
"a": {"a": True, "b": 0, "c": "z", "d": (1, 0, 0), "e": 2, "f": "g"},
"b": {"a": False, "b": 3, "c": "z", "d": (1, 0, 2), "e": 2, "f": "z"},
"c": {"a": True, "b": 10, "c": "h", "d": (1, 3, 0), "e": 2, "f": "2"},
}

foo.add(**foo_dict["a"])
foo.add(**foo_dict["b"])
foo.add(**foo_dict["c"])

If foo dict values are long, you can use the ast module to convert a string representation of the arguments into a dictionary. Here’s an example:

import ast

foo_dict = {
"a": "a=True, b=0, c='z', d=(1, 0, 0), e=2, f='g'",
"b": "a=False, b=3, c='z', d=(1, 0, 2), e=2, f='z'",
"c": "a=True, b=10, c='h', d=(1, 3, 0), e=2, f='2'",
}

for key in foo_dict:
args = ast.literal_eval("{" + foo_dict[key] + "}")
foo.add(**args)
Answered By: Apex
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.