import gc gc_was_enabled = gc.isenabled() if gc_was_enabled: gc.collect() gc.disable() # insert some time-critical code here if gc_was_enabled: gc.enable()