Passing a string containing keyword arguments to a function, combining into list comprehension

Where has that, very clever, ast.parse solution gone which was posted on here last night, seems to have disappeared? @inventshah or @tstefan if I recall correctly, or did I imagine that.

Passing a string of keyword arguments to a function sounded pretty standard to me, feel sure I have done this many times before in other languages; unfortunately didn’t prove to be in Python.

What are such languages? I feel like preferring config files over this method (which I, for one, have not heard of) is pretty standard and language-agnostic.

Is there a reason you need to pass a string containing the arguments, instead of just passing separate arguments?

Here, though, it seems like your goal is really “read the database configuration”, rather than “pass a string of keyword arguments”. Use a config file in one of the various common formats, like those already suggested. Why? Parsers already exist, meaning you don’t have to write and maintain that extra code.

@jonathandung Well I’m quite certain I have done things like this in various xBase languages of old for a start.

@ndc86430 Because in this circumstance the config string is coming from elsewhere and the actual arguments may not always be fixed.

Use a Dict comprehension instead of a list comprehension to make the dict.


str_in = "arg1 = 'var1', arg2 = 2, arg3 = True, arg4='var4'"

{sp[0]:sp[1] for sp in [ pair.split('=') for pair in str_in.split(',')]}

{'arg1 ': " 'var1'", ' arg2 ': ' 2', ' arg3 ': ' True', ' arg4': "'var4'"}

This one is better.
You can lose the extra quotes and spaces like this

str_in = "arg1 = 'var1', arg2 = 2, arg3 = True, arg4='var4'"

{sp[0]:sp[1] for sp in [ pair.split('=') for pair in str_in.replace(' ',''
).replace("'",'').split(',')]}


{'arg1 ': 'var1', ' arg2 ': '2', ' arg3 ': 'True', ' arg4': 'var4'}