3 ms·
> Python doesn't do anything for resources The "with" blocks can help with certain kinds of resources, for example: with open('foo.txt', 'r') as inf:
by piinbinary 7y ago
> Python doesn't do anything for resources
The "with" blocks can help with certain kinds of resources, for example:
with open('foo.txt', 'r') as inf:
data = inf.readlines()
- nerdponx 7y agoI think the point was that Python has no general tools to resource management, even if it provided ad-hoc access to the filesystem and threads.
- jhayward 7y agoI would claim that Python's context protocol [1] is exactly a general tool for resource management. [1] https://docs.python.org/3/reference/datamodel.html#with-statement-context-managers https://docs.python.org/3/reference/datamodel.html#with-stat...
- deathanatos 7y agoThat statement was too vague, you're right. I meant that it doesn't automatically do anything. I'm aware of with (it's mentioned in the post you're responding to ;) ). The thing about `with` (and similar constructs in other languages) is that you must remember to use them at every single site of use. If you forget, while the resource usually gets cleaned up when the language's GC decides to finalize the object, it's non-deterministic and might be too late. The consequences of forgetting are significantly better vs. C, as the GC will usually get to it in time, but that's not something I'd like to depend on. But the amount of "effort" and possibilities for mistakes is, generally, the same as C (in number, not severity): each resource allocation and each resource free requires the programmer's attention — excepting the specific, and I grant, quite common, case of memory, which one can say the GC will handle for you. RAII makes it s.t. you don't have to remember except in the (hopefully rare) case of implementing a new resource, and you can treat variables holding resources at sites-of-use like any other variable. For your specific example, if you can do w/o the list of lines (which I find is often possible) Python's actually got a somewhat nicer construct w/ Path: pathlib.Path('foo.txt').read_text() This only reads the data into a single string, whereas yours is a list of strings. Slight different, but usually it is acceptable. But it moves the required `with` into Path's helper method, so then it's harder for you to forget it. But this is a specific case (reading all data in a file), and doesn't generalize.
- piinbinary 7y agoGood point. There is a big gulf between "can do for you" and "automatically does for you." I really appreciate the fact that Rust does it automatically (and that it's not easy to turn that automatic management off).