-2

I have a piece of code that calculates the sum of a number of variables. For example, with 3 variables (A = 1, B = 2, C = 3) it outputs the sum X = 6. The way the code is implemented this is set up as a list with two strings:

Y = [['X', 'A+B+C']]

The list is compiled to create a sum which is then entered in a dictionary and used by the rest of the code:

YSUM = {}
for a in Y:
    YSUM[a[0]] = compile(a[1],'<string>','eval')

The code works fine, but there are instances in which there are no variables to sum and therefore the related string in the list is empty: Y = [['X', '']]. In this case, the output of the sum should be zero or null. But I can't find a way to do it. The compile function complains about an empty string (SyntaxError: unexpected EOF while parsing), but doesn't seem it can accept an alternative (compile() arg 1 must be a string, bytes or AST object).

point618
  • 1,309
  • 2
  • 10
  • 23
  • "In this case, the output of the sum should be zero or null." Why? If you write `a =` in Python source code, would you expect that to cause `a` to become zero or `None`? The purpose of all of these tools you are considering - `eval`, `compile` etc. - is to deal with text *that could be valid Python*. An empty string is not a valid Python expression. (Did you try just checking for this condition separately? Why is there an actual question here?) – Karl Knechtel Feb 20 '23 at 15:37
  • 2
    Also, standard warning: [**Do not ever use `eval` (or `exec`) on data that could possibly come from outside the program in any form. It is a critical security risk. You allow the author of the data to run arbitrary code on your computer. It cannot easily be sandboxed, and proper sandboxing is harder than using a proper tool for the job.**](https://stackoverflow.com/questions/1832940/why-is-using-eval-a-bad-practice) – Karl Knechtel Feb 20 '23 at 15:38
  • @KarlKnechtel Sorry that was poorly phrased. What I mean is that zero/null is the expected value of the sum in case there are no variables to sum. Because `a=` means nothing it should (somehow) return `a=0`. Hope it makes more sense. – point618 Feb 20 '23 at 15:47
  • So just check for it and handle it? You already know that the tools you are using don't accept this input (and that they have a good reason for it); you already know what the input is; you already know what you want to happen in that case. – Karl Knechtel Feb 20 '23 at 16:03

1 Answers1

1

What if you bypass calling compile():

Y = [['X', '']]
YSUM = {}
for a in Y:
    YSUM[a[0]] = compile(a[1],'<string>','eval') if a[1] else None
print(YSUM)
JonSG
  • 10,542
  • 2
  • 25
  • 36