Search code examples
pythoneval

python convert a string to arguments list


Can I convert a string to arguments 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:

list can, just use *list, but list can't have an element like: a=2

and eval can only evaluate expression

which would be like:

def func2(*args):
    for a in args:
        print a

list1=[1,2,3]
func2(*list1)
func2(*eval('1,2,3'))

Solution

  • You could massage the input string into a dictionary and then call your function with that, e.g.

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