alexmojaki / pure_eval

Safely evaluate AST nodes without side effects
MIT License
42 stars 14 forks source link

Evaluation of lists/tuples/dicts/sets #5

Closed pwwang closed 3 years ago

pwwang commented 3 years ago
x = y = 1
array = [x, y]

# This can be evaluated:
array[0]
# but this can't:
[x, y][0]

If we add this to Evaluator._handle:

        if isinstance(node, ast.List):
            return [self[elt] for elt in node.elts]
        if isinstance(node, ast.Tuple):
            return tuple(self[elt] for elt in node.elts)
        if isinstance(node, ast.Set):
            return set(self[elt] for elt in node.elts)
        if isinstance(node, ast.Dict):
            return {
                self[key]: self[val]
                for key, val in zip(node.keys, node.values)
            }

Some tests would break. Looks like you intended not to evaluate them like that.

Any thoughts?

alexmojaki commented 3 years ago

This is just something I didn't bother to do, and the tests relied on that but they probably shouldn't have. Happy to accept a PR. But you need to check that it's safe to hash the keys of the set/dict first.

pwwang commented 3 years ago

By the way, any thoughts about an API like eval. Something like:

pure_eval(source_or_node, globals, locals)

When I first came in, I was expecting something like that, since it is called pure_eval.

alexmojaki commented 3 years ago

nah