Skip to content

Commit

Permalink
Merge pull request #63 from laurence-hudson-mindfoundry/master
Browse files Browse the repository at this point in the history
Make string literal quote types configurable
  • Loading branch information
cansadadeserfeliz committed Jan 15, 2021
2 parents 7962872 + b9fe701 commit 0eb6c5a
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
6 changes: 4 additions & 2 deletions py_expression_eval/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -329,7 +329,9 @@ def append(self, a, b):
a.append(b)
return a

def __init__(self):
def __init__(self, string_literal_quotes = ("'", "\"")):
self.string_literal_quotes = string_literal_quotes

self.success = False
self.errormsg = ''
self.expression = ''
Expand Down Expand Up @@ -662,7 +664,7 @@ def isString(self):
r = False
str = ''
startpos = self.pos
if self.pos < len(self.expression) and self.expression[self.pos] in ("'", "\""):
if self.pos < len(self.expression) and self.expression[self.pos] in self.string_literal_quotes:
quote_type = self.expression[self.pos]
self.pos += 1
while self.pos < len(self.expression):
Expand Down
19 changes: 19 additions & 0 deletions py_expression_eval/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ def test_parser(self):

# but '"a b"' can *not* be used as a variable
self.assertEqual(parser.parse('"a b"*2').evaluate({'"a b"': 2}), "a ba b")
# unless parse configured to allow double quoted variables (i.e. allow multi-word vars)
parser2 = Parser(string_literal_quotes=("'")) # only single, not double!
self.assertEqual(parser2.parse('"a b"*2').evaluate({'"a b"':2}),4)

# evaluate
self.assertExactEqual(parser.parse('1').evaluate({}), 1)
Expand Down Expand Up @@ -215,15 +218,31 @@ def test_custom_functions_with_inline_strings(self):
expr = parser.parse("func(1, \"func(2, 4)\")")
self.assertEqual(expr.variables(), ['func'])

expr = parser.parse("func(1, 'func(2, 4)')")
self.assertEqual(expr.variables(), ['func'])

parser2 = Parser(string_literal_quotes=("'"))
expr = parser2.parse("func(1, \"func(2, 4)\")")
self.assertEqual(expr.variables(), ['func', "\"func(2, 4)\""])

expr = parser2.parse("func(1, 'func(2, 4)')")
self.assertEqual(expr.variables(), ['func'])

def test_custom_functions_substitute_strings(self):
def func(var, str):
if str == "custom text":
return 1
if str == "foo":
return 2
return 0

parser = Parser()
expr = parser.parse("func(1, \"custom text\")")
self.assertEqual(expr.evaluate({"func": func}), 1)

parser = Parser(string_literal_quotes=("'"))
expr = parser.parse("func(1, \"custom text\")")
self.assertEqual(expr.evaluate({"func": func, "\"custom text\"": "foo" }), 2)

def test_decimals(self):
parser = Parser()
Expand Down

0 comments on commit 0eb6c5a

Please sign in to comment.