Returns a function that maps a dict to a new dict with unique keys and
    values, kind of like a SQL SELECT clause, e.g.:

    >>> map_expression("foo=bar")({'bar': 1})
    {'foo': 1}
    >>> map_expression("foo=bar+1")({'bar': 1})
    {'foo': 2}

def map_expression(expr):
    """
    Returns a function that maps a dict to a new dict with unique keys and
    values, kind of like a SQL SELECT clause, e.g.:

    >>> map_expression("foo=bar")({'bar': 1})
    {'foo': 1}
    >>> map_expression("foo=bar+1")({'bar': 1})
    {'foo': 2}
    """
    if callable(expr):
        return expr

    # first, split the string on commas to get key/value bits
    # XXX: should we allow people to escape commas here?
    # XXX: what's a good test case for commas in an expression?
    bits = expr.split(',')
    # then, split each bit on '=' to get the key and expression strings
    exprs = [
        (bit[0].strip(), len(bit) > 1 and bit[1].strip() or '')
        for bit in [bit.split('=') for bit in bits]
    ]
    # then, convert those into a dict where each key indicates an expression()
    keys = [
        (k[0], k[1] and expression(k[1]) or None)
        for k in exprs
    ]
    key_dict = dict(keys)
    def _expr(data, **kwargs):
        vals = {}
        for key, expr in key_dict.items():
            # the SQL * selects all keys
            if key == '*':
                vals.update(data)
                continue
            # and if there's no expression, just grab the named key
            elif not expr:
                vals[key] = data.get(key)
                continue
            # otherwise, execute the expression
            # XXX: this will throw an exception if the named key doesn't exist
            # in the data dict!
            else:
                vals[key] = expr(data, **kwargs)
        return vals
    _expr.__doc__ = expr
    _expr.keys = map(lambda k: k[0], keys)
    return _expr