Reputation: 585
I'm using python3.6 in virtualenv. And I wonder if I use with object from outside with statement.
This is example code for the question.
with tempfile.NamedTemporaryFile(delete=False) as tf:
tf.write(audio_stream)
# outside of with
print(tf.name) # is it dangerous?
I want to do only write in with statement, and do other stuff outside of with. (Such as tf.name
). Is there a potential threat to access the tf
object from outside with? (Unintentional garbage collection, etc.)
If that's not recommended, I wonder the exact reason as well. thanks
Upvotes: 1
Views: 41
Reputation: 77337
There is no unintentional garbage collection. Each class of object decides what exiting the with
means to it, so there is no hard rule. Typically held-resources like an underlying file handle are closed but other attributes that don't normally change during a close are unchanged.
In your case, the temp file is closed so read/write/seek etc... don't work but the name attribute is safe to read.
If you really need to know for a given object, open its source and look at its __exit__
method.
Upvotes: 1