[Tutor] associating two objects without ORM and processing a text file

Steven D'Aprano steve at pearwood.info
Sat Feb 16 07:21:52 CET 2013


On 15/02/13 16:38, eryksun wrote:
> On Thu, Feb 14, 2013 at 4:33 PM, Prasad, Ramit
> <ramit.prasad at jpmorgan.com>  wrote:
>> My knee jerk response is a try/finally block, but I am sure there
>> are better ways.
>
> The atexit.register decorator hooks sys.exitfunc:
>
> http://docs.python.org/2/library/atexit


I find a try...finally block more readable and obvious than a hidden
atexit function. At least the try...finally block is explicit:


try:
     main()
finally:
     do_stuff()


while atexit can be set anywhere and isn't obvious. It's also somewhat
risky, since you never know when some library you import will silently
replace it with their own hook.

Also, keep in mind that you can't rely on atexit hooks to run. Or the
finally block for that matter. They can fail to run when:


- the Python process is killed from the outside, say using "kill -9"
   under Linux;

- or the entire computer goes down, say after a power failure;

- or the operating system crashes and takes everything else down;

- or something calls os._exit() while your code is running, say some
   external library.


So if you're serious about saving data, you cannot afford to wait until
the program quits before saving the user's work. You should be saving
whenever the user makes some change.



-- 
Steven


More information about the Tutor mailing list