Skip to content

Commit

Permalink
Add support for dict comprehension
Browse files Browse the repository at this point in the history
  • Loading branch information
Sergey Kovalev committed Jun 11, 2019
1 parent 164ee88 commit 695bb68
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
10 changes: 7 additions & 3 deletions simpleeval.py
Original file line number Diff line number Diff line change
Expand Up @@ -524,6 +524,7 @@ def __init__(self, operators=None, functions=None, names=None):
ast.List: self._eval_list,
ast.Set: self._eval_set,
ast.ListComp: self._eval_comprehension,
ast.DictComp: lambda node: self._eval_comprehension(node, is_dict=True),
ast.GeneratorExp: self._eval_comprehension,
})

Expand All @@ -544,8 +545,8 @@ def _eval_list(self, node):
def _eval_set(self, node):
return set(self._eval(x) for x in node.elts)

def _eval_comprehension(self, node):
to_return = []
def _eval_comprehension(self, node, is_dict=False):
to_return = {} if is_dict else []

extra_names = {}

Expand Down Expand Up @@ -584,7 +585,10 @@ def do_generator(gi=0):
if len(node.generators) > gi + 1:
do_generator(gi+1)
else:
to_return.append(self._eval(node.elt))
if is_dict:
to_return[self._eval(node.key)] = self._eval(node.value)
else:
to_return.append(self._eval(node.elt))

try:
do_generator()
Expand Down
10 changes: 10 additions & 0 deletions test_simpleeval.py
Original file line number Diff line number Diff line change
Expand Up @@ -650,6 +650,16 @@ def test_no_leaking_names(self):
self.s.eval('x')


class TestDictComprehensions(DRYTest):
""" Test the comprehensions support of the compound-types edition of the class. """

def setUp(self):
self.s = EvalWithCompoundTypes()

def test_basic(self):
self.t('{a: a for a in [1,2,3]}', {1: 1, 2: 2, 3: 3})


class TestNames(DRYTest):
""" 'names', what other languages call variables... """

Expand Down

0 comments on commit 695bb68

Please sign in to comment.