I try to use the context manager to have all the clean up code in the finally:
part of my fonction.
- One goal of the clean up is to make sure that all references to the class
initialize_stuff()
are set to None. - using the code below, there is still an active reference to the
initialize_stuff()
at the end - I can "force" the variable to None, but I may forget it when I use the context manager, I expect the context manager to do it.
Is it possible? How?
Notes:
- using
__enter__()
and__exit__()
has the same issue - The full problem I'm trying to solve (it's a simplified version here): Excel doesn't close if I use the "with" keyword instead of "inline" python
import contextlib
import gc
class initialize_stuff(object):
def use(self):
pass
@contextlib.contextmanager
def do_things():
try:
release_me = initialize_stuff()
yield release_me
finally:
release_me = None
gc.collect()
with do_things() as release_me:
release_me.use()
# release_me = None
if release_me is not None:
print("release_me is not released")
else:
print("yeah")