Just a small recipe, showing a neat use of the eval
python builtin,
to unpack a string that contains python code for either a symbol or
a sequence of symbols (that may further nest).
This rather unusual requirement is used by Evoque Templating
to parse and prepare for loop variables for runtime evaluation.
We let the eval
python builtin do all the work:
class _UnpackGlobals(dict):
def __getitem__(self, name):
return name
def unpack_symbol(symbol, globals=_UnpackGlobals()):
“”” If compound symbol (list, tuple, nested) unpack to atomic symbols “””
return eval(symbol, globals, None)
def __getitem__(self, name):
return name
def unpack_symbol(symbol, globals=_UnpackGlobals()):
“”” If compound symbol (list, tuple, nested) unpack to atomic symbols “””
return eval(symbol, globals, None)
A few examples in a python interactive session
should make what this does very clear:
>>> unpack_symbol(“a”)
‘a’
>>> unpack_symbol(“a, b”)
(‘a’, ‘b’)
>>> unpack_symbol(“(a, b)”)
(‘a’, ‘b’)
>>> unpack_symbol(“[a, b]”)
[‘a’, ‘b’]
>>> unpack_symbol(“[a, b, (c, d)]”)
[‘a’, ‘b’, (‘c’, ‘d’)]
>>> unpack_symbol(“[a, b, (c, [one, two, three], d)]”)
[‘a’, ‘b’, (‘c’, [‘one’, ‘two’, ‘three’], ‘d’)]
>>>
‘a’
>>> unpack_symbol(“a, b”)
(‘a’, ‘b’)
>>> unpack_symbol(“(a, b)”)
(‘a’, ‘b’)
>>> unpack_symbol(“[a, b]”)
[‘a’, ‘b’]
>>> unpack_symbol(“[a, b, (c, d)]”)
[‘a’, ‘b’, (‘c’, ‘d’)]
>>> unpack_symbol(“[a, b, (c, [one, two, three], d)]”)
[‘a’, ‘b’, (‘c’, [‘one’, ‘two’, ‘three’], ‘d’)]
>>>
A related thread on comp.lang.python:
How
to split a string containing nested commas-separated substrings
Your comments are welcome.