1

(please help me clarify the title)

This is what I'd like to do:

s = "'arg1', 'arg2', foo='bar', baz='qux'"
def m(*args, **kwargs):
  return args, kwargs

args, kwargs = m(magic(s))
# args = ['arg1', 'arg2']
# kwargs = {'foo': 'bar', 'baz'='qux'}

What is the definition of magic()?

Parsing the string myself is a last resort since it's fraught with pitfalls (what if arg1 has a comma in it? what if arg2 has quotes in it? etc).

2
  • 1
    Why do you want to do this? If s comes from the user, any non-horrendously-complicated ways to do this will be full of security risks. Commented Sep 23, 2011 at 21:27
  • @Karl s comes from a configuration file. The bulk of the file is not Pythonic at all, but I'm building in some macro-handling that will benefit from this sort of syntax. Commented Sep 24, 2011 at 3:09

2 Answers 2

3

With s and m defined as you have them:

>>> args, kwargs = eval('m(%s)' % s)
>>> args
('arg1', 'arg2')
>>> kwargs
{'foo': 'bar', 'baz': 'qux'}
Sign up to request clarification or add additional context in comments.

Comments

0

Take a look at eval, but be aware that bad things can happen if you're not careful.

6 Comments

Python code is entirely source. Bad things can happen by people editing the source. eval() has no more risks than are already inherent in Python.
The additional bad thing is that you can execute user-provided code if you're not paying attention. This is related to the problem of using input instead of raw_input for user I/O.
Python code is entirely source. You can execute user-provided code at any time. "Paying attention" has no bearing on this. eval() is not evil. Any more than any dynamic, interpreted language is evil.
I never said that eval is evil. If you accept input from a source outside of the currently executing program that may make into an eval , you have assumed additional risk. Pretending that executable input from outside of the program is the same as known source may lead to "bad things" ranging from sub-opitmal performance to security breaches to software crashes. All programs are entirely source at some level, and all programs that allow for the execution of arbitrary code from arbitrary sources have serious risks that are not shared by programs that does not allow code to be injected.
"All programs are entirely source at some level". True, but not the point here. Python source in .py files and python source as input to eval is equally suspicious. Eval is not evil. Yes, it's a source of crashes. But it's not inherently bad.
|

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.