psycopg2: proper positioning of .commit() within try: except: blocks

Rob Cliffe rob.cliffe at btinternet.com
Sun Sep 8 09:58:03 EDT 2024


On 07/09/2024 22:20, Karsten Hilbert via Python-list wrote:
> Am Sat, Sep 07, 2024 at 02:09:28PM -0700 schrieb Adrian Klaver:
>
>>> Right, and this was suggested elsewhere ;)
>>>
>>> And, yeah, the actual code is much more involved :-D
>>>
>> I see that.
>>
>> The question is does the full code you show fail?
>>
>> The code sample you show in your original post is doing something very different then
>> what you show in your latest post. At this point I do not understand the exact problem
>> we are dealing with.
> We are not dealing with an unsolved problem. I had been
> asking for advice  where to best place that .commit() call in
> case I am overlooking benefits and drawbacks of choices.
>
> The
>
> 	try:
> 		do something
> 	except:
> 		log something
> 	finally:
> 		.commit()
>
> cadence is fairly Pythonic and elegant in that it ensures the
> the .commit() will always be reached regardless of exceptions
> being thrown or not and them being handled or not.
>
> It is also insufficient because the .commit() itself may
> elicit exceptions (from the database).
>
> So there's choices:
>
> Ugly:
>
> 	try:
> 		do something
> 	except:
> 		log something
> 	finally:
> 		try:
> 			.commit()
> 		except:
> 			log some more
>
> Fair but not feeling quite safe:
>
> 	try:
> 		do something
> 		.commit()
> 	except:
> 		log something
>
> Boring and repetitive and safe(r):
>
> 	try:
> 		do something
> 	except:
> 		log something
> 	try:
> 		.commit()
> 	except:
> 		log something
>
> I eventually opted for the last version, except for factoring
> out the second try: except: block.
>
> Best,
> Karsten
> --
> GPG  40BE 5B0E C98E 1713 AFA6  5BC0 3BEA AC80 7D4F C89B
Unless I'm missing something, the 1st & 3rd versions always do the 
commit() even after the first bit fails, which seems wrong.
I suggest the 1st version but replacing "finally" by "else".  Then the 
try-commit-except will not be executed if the "something" fails.
Perhaps the extra indentation of the second try block is a bit ugly, but 
it is more important that it does the right thing.
If it is convenient (it may not be) to put the whole thing in a 
function, you may feel that the follwing is less ugly:

	try:
		do something
	except:
		log something
		return
	try:
		.commit()
	except:
		log some more
	return

Best wishes
Rob Cliffe



More information about the Python-list mailing list