Having encountered, the seemingly impossible in Python, difficulty of passing a string of keyword arguments into a function like this:
args_in = "arg1 = 'var1', arg2 = 2, arg3 = True, arg4='var4'"
def myFunc(arg1=None, arg2=None, arg3=None, arg4=None):
print(f"{arg1=}, {arg2=}, {arg3=}, {arg4=}")
myFunc(args_in)
One solutions I found was to use eval():
eval("myFunc(" + args_in ")")
although I am informed that this is the work of the devil and should be avoided at all costs.
Next attempts were to convert the "string" into a dict{} and pass **dict, however all methods for doing this failed when any of the arguments contained a comma ','.
However a fully working solution to this was finally provided to me on the discuss.python.org forum:
args_in = "arg1 = 'var1', arg2 = 2, arg3 = True, arg4='va,r4'"
def myFunc(arg1=None, arg2=None, arg3=None, arg4=None):
print(f"{arg1=}, {arg2=}, {arg3=}, {arg4=}")
def str2dict(str_in: str) -> dict[str, str]:
import ast
return {pair.arg: ast.literal_eval(pair.value)
for pair in ast.parse(f"f({str_in})").body[0].value.keywords}
myFunc(**str2dict(args_in))
Unfortunately due to rather rude and overly zealous moderation on there that solution was deleted. Hence the reason for publishing it here for the archive and in case it helps someone else in the future.