How to split a string containing nested commas-separated substrings

mario mario at
Wed Jun 25 08:30:56 CEST 2008

I have actually highlighted a small neat recipe for doing such
unpacking, that I use for parsing arbitrary parameters in Evoque
Templating. I never needed to handle "callable" parameters though, as
you do in your 3rd string example, so the little "unpack_symbol"
recipe I have publiched earlier does not handle it... anyhow, what I
referring to are:

Evoque Templating:
Code highlight:

However, a little variation of the aboverecipe can do what you are
looking for, in a rather cute way. The difference is to make the
original recipe handle "callable strings", and I achieve this by
modifying the recipe like so:

class callable_str(str):
    def __call__(s, *args):
        return s+str(args)

class _UnpackGlobals(dict):
    def __getitem__(self, name):
        return callable_str(name)

def unpack_symbol(symbol, globals=_UnpackGlobals()):
    """ If compound symbol (list, tuple, nested) unpack to atomic
symbols """
    return eval(symbol, globals, None)

Now, calling unpack_symbol() on each sample string gives the following
tuple of strings:

>>> unpack_symbol('foo, bar, baz')
('foo', 'bar', 'baz')
>>> unpack_symbol('foo, "bar, baz", blurf')
('foo', 'bar, baz', 'blurf')
>>> unpack_symbol('foo, bar(baz, blurf), mumble')
('foo', "bar('baz', 'blurf')", 'mumble')

Mario Ruggier

More information about the Python-list mailing list