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.
@callahad Finally I have a hypothesis: that the missing library is just missing.
Probably, when facing with the need, say, to read a file (abstract example!) js developers write:
merging
With
andopen
into theopen
function. I have actually very little experience in nodejs world, so I need proof :).@sindresorhus @gaearon is this true ?
So, nothing, imho, really stops js community from writing some kind of contextlib with neat and powerfull stuff like
ExitStack
.@callahad About what you've written on the support in other languages: I don't think
destructors / finalizers can be directly compared to context managers:
the latter do error handling within a scope of a code-block or function,
and the former - just the resource cleanup (special case of error handling, you can't have different cleanup logic depending on which exception was raised), usually without any garantees in which scope or when it will be done.
But talking about scripting languages, Ruby has "code blocks" which are not less powerful than python context
managers.