How can I use the python compile function on an empty string?

Question:

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).

Asked By: rs028

||

Answers:

You could try a ternary operator to handle this case:

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

Update

An alternate code to solve this would be to use a try/except block. The try block would attempt to compile the expression, and the except block would handle the case of an empty string. The code would look like this:

YSUM = {}
for a in Y:
    try:
        YSUM[a[0]] = compile(a[1],'<string>','eval')
    except SyntaxError:
        YSUM[a[0]] = 0
Answered By: João Paiva

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)
Answered By: JonSG
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.