Python parse string containing functions, lists and dicts
<p>I'm trying to find way to parse string that can contain variable, function, list, or dict written in python syntax separated with ",". Whitespace should be usable anywhere, so split with "," when its not inside (), [] or {}.</p>

<p>Example string: <code>"variable, function1(1,3), function2([1,3],2), ['list_item_1','list_item_2'],{'dict_key_1': "dict_item_1"}"</code></p>

<p>Another example string: <code>"variable,function1(1, 3) , function2( [1,3],2), ['list_item_1','list_item_2'],{'dict_key_1': "dict_item_1"}"</code></p>

<p>Example output <code>["variable", "function1(1,3)", "function2([1,3],2)", "['list_item_1','list_item_2']", "{'dict_key_1': "dict_item_1"}"]</code></p>

<p>edit:
Reason for the code is to parse string an then run it with <code>exec("var = &amp;s" % list[x])</code>. (yes i know this might not be recommended way to do stuff)</p>

<p>Regular expressions aren't very good for parsing the complexity of arbitrary code. What exactly are you trying to accomplish? You can (unsafely) use <code>eval</code> to just evaluate the string as code. Or if you're trying to understand it without <code>eval</code>ing it, you can use <a href="https://docs.python.org/3/library/ast.html" rel="nofollow">the <code>ast</code></a> or <a href="https://docs.python.org/3/library/dis.html" rel="nofollow"><code>dis</code> modules</a> for various forms of inspection.</p>

python regex string-parsing