Python converts string to argument list

Is it possible to convert a string to an argument list in python?

def func(**args): for a in args: print a, args[a] func(a=2, b=3) # I want the following work like above code s='a=2, b=3' func(s) 

I know:

a list may, just use * list, but a list cannot have an element such as: a = 2

and eval can evaluate only expression

which will look like this:

 def func2(*args): for a in args: print a list1=[1,2,3] func2(*list1) func2(*eval('1,2,3')) 
+6
source share
3 answers

You can massage the input string into the dictionary, and then call your function using, for example,

 >>> x='a=2, b=3' >>> args = dict(e.split('=') for e in x.split(', ')) >>> f(**args) a 2 b 3 
+8
source

You need a dictionary, not a list of arguments. You would also be better off using ast.literal_eval() to evaluate only Python literals:

 from ast import literal_eval params = "{'a': 2, 'b': 3}" func(**literal_eval(params)) 

Before you go this route, make sure that you first examine other options for sorting options, such as argparse for command line options, or JSON for transferring or saving at the network or file level.

+7
source

You can use the string as a list of arguments directly when you call eval , for example.

 def func(**args): for a in args: print( a, args[a]) s='a=2, b=3' eval('func(' + s + ')') >>>b 3 >>>a 2 

note that func must be in the namespace to invoke eval to work as follows.

0
source

Source: https://habr.com/ru/post/958978/


All Articles