Try-except for flow control in reading Sqlite

Antoon Pardon antoon.pardon at rece.vub.ac.be
Mon Oct 28 05:48:16 EDT 2013


Op 28-10-13 07:18, Steven D'Aprano schreef:
> On Sun, 27 Oct 2013 20:43:07 -0700, Victor Hooi wrote:
> 
>> Hi,
>>
>> I'd like to double-check something regarding using try-except for
>> controlling flow.
>>
>> I have a script that needs to lookup things in a SQLite database.
>>
>> If the SQLite database file doesn't exist, I'd like to create an empty
>> database, and then setup the schema.
>>
>> Is it acceptable to use try-except in order to achieve this? E.g.:
>>
>>     try:
>>         # Try to open up the SQLite file, and lookup the required
>>         entries
>>     except OSError:
>>         # Open an empty SQLite file, and create the schema
> 
> Yes, that's the right way to do it.
> 
> 
>> My thinking is that it is (easier to ask forgiveness than permission),
>> but I just wanted to check if there is a better way of achieving this?
>>
>> I'd also be doing the same thing for checking if a file is gzipped or
>> not - we try to open it as a gzip, then as an ordinary text file, and if
>> that also fails, raise a parsing error.
> 
> Correct.
> 
> The problem with checking in advance is that there is a race condition 
> between checking and the using the file:

There is also a race condition here. You open the SQLite file and it
fails. Then another process creates the SQLite file and stores things
in it and then when you open the SQLite file as an empty file and create
the schema, the previous work is lost.

-- 
Antoon Pardon



More information about the Python-list mailing list