Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading