3 ms·
I'm not sure it is fair to attribute this to Python's GC model, in that what is commonly thought of as garbage collection is not involved with the issue being d
by gizmo686 6y ago
I'm not sure it is fair to attribute this to Python's GC model, in that what is commonly thought of as garbage collection is not involved with the issue being discussed.
However, in principle, this issue is very simmilar to that which garbage collectors set out to solve.
In effect, python's context managers combined with the "with" syntax recreate the sementics of C's local variables in that:
1) They can be passed outside the lexical scope in which they were defined but
2) They're usage is illegal after execution has exited the "block" in which they are defined.
3) There is nothing which prevents a programmer from keeping and attempt to use a reference to them after execution has left the code block.
The approach I take in python is the same I take in C. Most of the time, I only need to file for a short period, so I can "stack" allocate it with a context manager and let the runtime handle closing it for me. In cases where stack-like sementic do not fit, you need to use heap-like semantics and manually open/close it.
- wwright 6y agoIf you’re not familiar with Rust, one of the core features is that you can “pass” or “borrow” that stack-like scoping in a safe way. IE, if you create a file handle, it gets automatically cleaned up when the current scope ends… unless you transfer ownership to other code, and then it is cleaned when THAT scope ends. It also prevents references from dangling after the resource has been cleaned, even in other classes or functions. This lets you model ownership rather than memory, and the compiler will translate that (for the most part) to memory management for you. What I was trying to say is that I think managing ownership as a first-class language feature is more generally useful than trying to abstract away the concern with something like GC.