RFC: Proposal: Deterministic Object Destruction
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Sat Mar 3 18:49:51 EST 2018
On Sat, 03 Mar 2018 12:37:08 -0500, Richard Damon wrote:
> With RAII and immediate destruction on end of scope, we can automate the
> release, without it and you need a lot of explicit code to manage these
> resources.
Not so much.
with resource_i_care_about() as rsrc:
process(rsrc)
is hardly what I call "a lot of explicit code". Yes, there's some code in
the context manager, but you write that *once* (if it isn't already
written for you!) and you're done.
I know that laziness and hubris are programmer virtues, but there is
still such a thing as *too much laziness*. RAII works in C++ where
instances are allocated in the stack, but even there, if you have an
especially long-lived function, your resources won't be closed promptly.
In Python terms:
def function():
x = open_resource()
process(x)
# and we're done with x now, but too lazy to explicitly close it
sleep(10000) # Simulate some more work. Lots of work.
return
# and finally x is closed (2.8 hours after you finished using it)
The answer in C++ is "well don't do that then". The answer is Python is,
"don't be so lazy, just use a with statement".
If you want deterministic closing of resources, with statements are the
way to do it.
def function():
with open_resource() as x:
process(x)
# and x is guaranteed to be closed
sleep(10000) # Simulate some more work. Lots of work.
return
--
Steve
More information about the Python-list
mailing list