Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python try except finally: Invalid syntax error (what's wrong with this code?)

I am trying to use finally in the following function, however, Python reports a Syntax error. I'm sure I'm doing something silly, but I can't seem to spot it ...

Snippet follows below:

# Store ids with key
# Returns GUID (used to clear table after words)
def storeIdsInTemporaryTable(dbinfo, id_list):
    conn = dbinfo['db_connection']

    guid = genutils.getGUID()
    orig_tableinfo = dbinfo['table']
    orig_datarows = dbinfo['datarows']

    metadata = dbinfo['metadata']

    sql = "INSERT INTO temporary_data_key (key) VALUES ({0}) RETURNING id".format(guid)
    key_id = executeSQLonDbConnection(dbinfo, sql, return_field='id')

    tableinfo = Table('temporary_data', metadata, autoload=True)
    datarows = []

    for id_value in id_list:
        datarows.append( { 'key_id': key_id, 'id_value': id_value} )

    try:
        insertToDb(dbinfo)
    except:
        guid = None # to indicate an error occured
        if key_id:
            conn.execute("DELETE FROM temporary_data_key WHERE key={0}".format(guid)

    finally:
        dbinfo['table'] = orig_tableinfo
        dbinfo['datarows'] = orig_datarows

    return guid

What is causing the syntax error?

As an aside, I am aware that I need to wrap the two inserts in a transaction, but for some reason, I can't get transactions to work (SQLALchemy throws a transaction related error) - so thats for another question another time..

[[Edit]]

The exception error (now fixed) was:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/path/to/script.py", line 1632
    finally:
          ^
SyntaxError: invalid syntax
like image 531
Homunculus Reticulli Avatar asked Jun 08 '12 09:06

Homunculus Reticulli


1 Answers

Are you using a Python < 2.5? try except finally was only added in 2.5 and before you had to wrap try except in a try finally.

like image 176
Sebastian Blask Avatar answered Nov 15 '22 07:11

Sebastian Blask