13

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'))
1
  • Something like argparse should do it. have a look at how to call parse_args() with arguments. Commented Nov 28, 2013 at 10:44

3 Answers 3

17

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
Sign up to request clarification or add additional context in comments.

4 Comments

First seen this syntax. Thank you. I don't know why tuple(e.split('=')) for e in x.split(', ') will cause syntax error, isn't it an argument of dict()? Is there an explain about this rule?
@AylwynLake: It is a generator expression which in turn is a generalized form of list comprehensions.
But a and b are of strings and not integers. How do I convert them to integers?
@zeeshankhan You could massage the dictionary a bit further and apply int to all values, e.g. args = {k: int(v) for k, v in args.items()}
14

You want a dictionary, not an 'argument list'. You also would be better off using ast.literal_eval() to evaluate just Python literals:

from ast import literal_eval

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

Before you go this route, make sure you've explored other options for marshalling options first, such as argparse for command-line options, or JSON for network or file-based transfer or persistence.

11 Comments

+1 but this solution may not be applicable in case the a=2, b=3 string is user input (e.g. from a configuration file or the like); you'd rather not allow evaluating arbitrary Python code. :-}
@FrerichRaabe: The OP seemed to be looking for the equivalent of args "(1, 2, 3)" and func2(*literal_eval(args)) here; e.g. something that would produce the right python structure to apply to call.
@MartijnPieters: I mean as Frerich Raabe said. I want to read from config file of tables, then use sqlalchemy to auto generate tables. when processing Column('id', Integer, primary_key = True). Then ask this question.
@AylwynLake: And you cannot use a configuration format that lets you specify the id, type and other options as separate entries?
@naxa: right, no, that's not a Python literal, you'll have to parse that directly.
|
2

You can use the string as an argument list directly in an call to eval, e.g.

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 needs to be in the namespace for the eval call to work like this.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.