CSV performance
Peter Otten
__peter__ at web.de
Wed Apr 29 03:16:33 EDT 2009
Lawrence D'Oliveiro wrote:
> In message <gt47lc$kar$03$1 at news.t-online.com>, Peter Otten wrote:
>
>> gc.disable()
>> # create many small objects that you want to keep
>> gc.enable()
>
> Every time I see something like this, I feel the urge to save the previous
> state and restore it afterwards:
>
> save_enabled = gc.isenabled()
> gc.disable()
> # create many small objects that you want to keep
> if save_enabled :
> gc.enable()
> #end if
>
> Maybe that's just me. :)
There's probably someone out there who does nested GC states on a daily
basis ;)
When I see the sequence
save state
change state
do something
restore state
I feel compelled to throw in a try ... finally
save state
try:
change state
do something
finally:
restore state
which in turn leads to
import gc
from contextlib import contextmanager
@contextmanager
def gcdisabled():
was_enabled = gc.isenabled()
gc.disable()
try:
yield
finally:
if was_enabled:
gc.enable()
if __name__ == "__main__":
try:
with gcdisabled():
assert not gc.isenabled()
try:
with gcdisabled():
assert not gc.isenabled()
1/0
finally:
assert not gc.isenabled()
except ZeroDivisionError:
pass
assert gc.isenabled()
So far, so good. But is it thread-safe?
I think you are beginning to see why the original suggestion was my best
option...
Peter
More information about the Python-list
mailing list