Hi everyone!
I am coming from Python background, and in Python we have context managers.
These are objects encapsulating the try-catch-finally block, and usually are used to cleanup resources, like closing the open file. In Python community, most developers consider context managers a very neat feature of the language and you really can find them often in the code.
So, my question is: why is this feature missing completely in the js world? I could not find a single library. I think I can imagine what it could look like:
import With from 'missing-context-managers'
import open from 'some-file-utils'
With(open(file_path), (file) => {
// file is open now
console.log(file.getContents())
})
// file is closed now
From what I understand, the respective aspects of the language (error handling) is pretty much the same in python and javascript. What is the difference? Why one community finds a feature useful and the other - completely not?
P. S. I am not really asking if you consider context managers useful, just what is the possible difference between js/nodejs and python in this aspect.
I think much of this stems from just having resources that need to be cleaned up: open sockets, file descriptors, etc. Python solves this with context managers, C++ with destructors, Golang (kinda) with
defer
, Java (kinda) with finalizers, Rust with theDrop
trait, and so on....but JavaScript in the browser never had those sorts of concerns. You'd never need worry about forgetting to close a file, because you couldn't open a file in the first place. You didn't need to worry about releasing mutexes or locks, because JavaScript was single-threaded. It's only with Node that we're starting to have some of those concerns, and I don't have any insight into Node's development. However, it does seem like proper support for something like a context manager would likely require support from the language, and Node doesn't fork JavaScript itself, so its hands are, in a sense, tied. :)